-
Notifications
You must be signed in to change notification settings - Fork 665
/
Protocol.js
2077 lines (1607 loc) · 62.4 KB
/
Protocol.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
TODO:
* Replace `buffer._pos` usage in keyParser.js and elsewhere
* Utilize optional "writev" support when writing packets from
cipher.encrypt()
* Built-in support for automatic re-keying, on by default
* Revisit receiving unexpected/unknown packets
* Error (fatal or otherwise) or ignore or pass on to user (in some or all
cases)?
* Including server/client check for single directional packet types?
* Check packets for validity or bail as early as possible?
* Automatic re-key every 2**31 packets after the last key exchange (sent or
received), as suggested by RFC4344. OpenSSH currently does this.
* Automatic re-key every so many blocks depending on cipher. RFC4344:
Because of a birthday property of block ciphers and some modes of
operation, implementations must be careful not to encrypt too many
blocks with the same encryption key.
Let L be the block length (in bits) of an SSH encryption method's
block cipher (e.g., 128 for AES). If L is at least 128, then, after
rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4)
blocks before rekeying again. If L is at least 128, then SSH
implementations should also attempt to force a rekey before receiving
more than 2**(L/4) blocks. If L is less than 128 (which is the case
for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then,
although it may be too expensive to rekey every 2**(L/4) blocks, it
is still advisable for SSH implementations to follow the original
recommendation in [RFC4253]: rekey at least once for every gigabyte
of transmitted data.
Note that if L is less than or equal to 128, then the recommendation
in this subsection supersedes the recommendation in Section 3.1. If
an SSH implementation uses a block cipher with a larger block size
(e.g., Rijndael with 256-bit blocks), then the recommendations in
Section 3.1 may supersede the recommendations in this subsection
(depending on the lengths of the packets).
*/
'use strict';
const { inspect } = require('util');
const { bindingAvailable, NullCipher, NullDecipher } = require('./crypto.js');
const {
COMPAT_CHECKS,
DISCONNECT_REASON,
MESSAGE,
SIGNALS,
TERMINAL_MODE,
} = require('./constants.js');
const {
DEFAULT_KEXINIT,
KexInit,
kexinit,
onKEXPayload,
} = require('./kex.js');
const {
parseKey,
} = require('./keyParser.js');
const MESSAGE_HANDLERS = require('./handlers.js');
const {
bufferCopy,
bufferFill,
bufferSlice,
convertSignature,
sendPacket,
writeUInt32BE,
} = require('./utils.js');
const {
PacketReader,
PacketWriter,
ZlibPacketReader,
ZlibPacketWriter,
} = require('./zlib.js');
const MODULE_VER = require('../../package.json').version;
const VALID_DISCONNECT_REASONS = new Map(
Object.values(DISCONNECT_REASON).map((n) => [n, 1])
);
const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`);
const IDENT = Buffer.from(`${IDENT_RAW}\r\n`);
const MAX_LINE_LEN = 8192;
const MAX_LINES = 1024;
const PING_PAYLOAD = Buffer.from([
MESSAGE.GLOBAL_REQUEST,
// "keepalive@openssh.com"
0, 0, 0, 21,
107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115,
115, 104, 46, 99, 111, 109,
// Request a reply
1,
]);
const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]);
function noop() {}
/*
Inbound:
* kexinit payload (needed only until exchange hash is generated)
* raw ident
* rekey packet queue
* expected packet (implemented as separate _parse() function?)
Outbound:
* kexinit payload (needed only until exchange hash is generated)
* rekey packet queue
* kex secret (needed only until NEWKEYS)
* exchange hash (needed only until NEWKEYS)
* session ID (set to exchange hash from initial handshake)
*/
class Protocol {
constructor(config) {
const onWrite = config.onWrite;
if (typeof onWrite !== 'function')
throw new Error('Missing onWrite function');
this._onWrite = (data) => { onWrite(data); };
const onError = config.onError;
if (typeof onError !== 'function')
throw new Error('Missing onError function');
this._onError = (err) => { onError(err); };
const debug = config.debug;
this._debug = (typeof debug === 'function'
? (msg) => { debug(msg); }
: undefined);
const onHeader = config.onHeader;
this._onHeader = (typeof onHeader === 'function'
? (...args) => { onHeader(...args); }
: noop);
const onPacket = config.onPacket;
this._onPacket = (typeof onPacket === 'function'
? () => { onPacket(); }
: noop);
let onHandshakeComplete = config.onHandshakeComplete;
if (typeof onHandshakeComplete !== 'function')
onHandshakeComplete = noop;
this._onHandshakeComplete = (...args) => {
this._debug && this._debug('Handshake completed');
// Process packets queued during a rekey where necessary
const oldQueue = this._queue;
if (oldQueue) {
this._queue = undefined;
this._debug && this._debug(
`Draining outbound queue (${oldQueue.length}) ...`
);
for (let i = 0; i < oldQueue.length; ++i) {
const data = oldQueue[i];
// data === payload only
// XXX: hacky
let finalized = this._packetRW.write.finalize(data);
if (finalized === data) {
const packet = this._cipher.allocPacket(data.length);
packet.set(data, 5);
finalized = packet;
}
sendPacket(this, finalized);
}
this._debug && this._debug('... finished draining outbound queue');
}
onHandshakeComplete(...args);
};
this._queue = undefined;
const messageHandlers = config.messageHandlers;
if (typeof messageHandlers === 'object' && messageHandlers !== null)
this._handlers = messageHandlers;
else
this._handlers = {};
this._onPayload = onPayload.bind(this);
this._server = !!config.server;
this._banner = undefined;
let greeting;
if (this._server) {
if (typeof config.hostKeys !== 'object' || config.hostKeys === null)
throw new Error('Missing server host key(s)');
this._hostKeys = config.hostKeys;
// Greeting displayed before the ssh identification string is sent, this
// is usually ignored by most clients
if (typeof config.greeting === 'string' && config.greeting.length) {
greeting = (config.greeting.slice(-2) === '\r\n'
? config.greeting
: `${config.greeting}\r\n`);
}
// Banner shown after the handshake completes, but before user
// authentication begins
if (typeof config.banner === 'string' && config.banner.length) {
this._banner = (config.banner.slice(-2) === '\r\n'
? config.banner
: `${config.banner}\r\n`);
}
} else {
this._hostKeys = undefined;
}
let offer = config.offer;
if (typeof offer !== 'object' || offer === null)
offer = DEFAULT_KEXINIT;
else if (offer.constructor !== KexInit)
offer = new KexInit(offer);
this._kex = undefined;
this._kexinit = undefined;
this._offer = offer;
this._cipher = new NullCipher(0, this._onWrite);
this._decipher = undefined;
this._skipNextInboundPacket = false;
this._packetRW = {
read: new PacketReader(),
write: new PacketWriter(this),
};
this._hostVerifier = (!this._server
&& typeof config.hostVerifier === 'function'
? config.hostVerifier
: undefined);
this._parse = parseHeader;
this._buffer = undefined;
this._authsQueue = [];
this._authenticated = false;
this._remoteIdentRaw = undefined;
let sentIdent;
if (typeof config.ident === 'string') {
this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`);
sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2);
sentIdent.set(this._identRaw, 0);
sentIdent[sentIdent.length - 2] = 13; // '\r'
sentIdent[sentIdent.length - 1] = 10; // '\n'
} else if (Buffer.isBuffer(config.ident)) {
const fullIdent = Buffer.allocUnsafe(8 + config.ident.length);
fullIdent.latin1Write('SSH-2.0-', 0, 8);
fullIdent.set(config.ident, 8);
this._identRaw = fullIdent;
sentIdent = Buffer.allocUnsafe(fullIdent.length + 2);
sentIdent.set(fullIdent, 0);
sentIdent[sentIdent.length - 2] = 13; // '\r'
sentIdent[sentIdent.length - 1] = 10; // '\n'
} else {
this._identRaw = IDENT_RAW;
sentIdent = IDENT;
}
this._compatFlags = 0;
if (this._debug) {
if (bindingAvailable)
this._debug('Custom crypto binding available');
else
this._debug('Custom crypto binding not available');
}
this._debug && this._debug(
`Local ident: ${inspect(this._identRaw.toString())}`
);
this.start = () => {
this.start = undefined;
if (greeting)
this._onWrite(greeting);
this._onWrite(sentIdent);
};
}
_destruct(reason) {
this._packetRW.read.cleanup();
this._packetRW.write.cleanup();
this._cipher && this._cipher.free();
this._decipher && this._decipher.free();
if (typeof reason !== 'string' || reason.length === 0)
reason = 'fatal error';
this.parse = () => {
throw new Error(`Instance unusable after ${reason}`);
};
this._onWrite = () => {
throw new Error(`Instance unusable after ${reason}`);
};
this._destruct = undefined;
}
cleanup() {
this._destruct && this._destruct();
}
parse(chunk, i, len) {
while (i < len)
i = this._parse(chunk, i, len);
}
// Protocol message API
// ===========================================================================
// Common/Shared =============================================================
// ===========================================================================
// Global
// ------
disconnect(reason) {
const pktLen = 1 + 4 + 4 + 4;
// We don't use _packetRW.write.* here because we need to make sure that
// we always get a full packet allocated because this message can be sent
// at any time -- even during a key exchange
let p = this._packetRW.write.allocStartKEX;
const packet = this._packetRW.write.alloc(pktLen, true);
const end = p + pktLen;
if (!VALID_DISCONNECT_REASONS.has(reason))
reason = DISCONNECT_REASON.PROTOCOL_ERROR;
packet[p] = MESSAGE.DISCONNECT;
writeUInt32BE(packet, reason, ++p);
packet.fill(0, p += 4, end);
this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`);
sendPacket(this, this._packetRW.write.finalize(packet, true), true);
}
ping() {
const p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(PING_PAYLOAD.length);
packet.set(PING_PAYLOAD, p);
this._debug && this._debug(
'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)'
);
sendPacket(this, this._packetRW.write.finalize(packet));
}
rekey() {
if (this._kexinit === undefined) {
this._debug && this._debug('Outbound: Initiated explicit rekey');
this._queue = [];
kexinit(this);
} else {
this._debug && this._debug('Outbound: Ignoring rekey during handshake');
}
}
// 'ssh-connection' service-specific
// ---------------------------------
requestSuccess(data) {
let p = this._packetRW.write.allocStart;
let packet;
if (Buffer.isBuffer(data)) {
packet = this._packetRW.write.alloc(1 + data.length);
packet[p] = MESSAGE.REQUEST_SUCCESS;
packet.set(data, ++p);
} else {
packet = this._packetRW.write.alloc(1);
packet[p] = MESSAGE.REQUEST_SUCCESS;
}
this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS');
sendPacket(this, this._packetRW.write.finalize(packet));
}
requestFailure() {
const p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1);
packet[p] = MESSAGE.REQUEST_FAILURE;
this._debug && this._debug('Outbound: Sending REQUEST_FAILURE');
sendPacket(this, this._packetRW.write.finalize(packet));
}
channelSuccess(chan) {
// Does not consume window space
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4);
packet[p] = MESSAGE.CHANNEL_SUCCESS;
writeUInt32BE(packet, chan, ++p);
this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`);
sendPacket(this, this._packetRW.write.finalize(packet));
}
channelFailure(chan) {
// Does not consume window space
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4);
packet[p] = MESSAGE.CHANNEL_FAILURE;
writeUInt32BE(packet, chan, ++p);
this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`);
sendPacket(this, this._packetRW.write.finalize(packet));
}
channelEOF(chan) {
// Does not consume window space
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4);
packet[p] = MESSAGE.CHANNEL_EOF;
writeUInt32BE(packet, chan, ++p);
this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`);
sendPacket(this, this._packetRW.write.finalize(packet));
}
channelClose(chan) {
// Does not consume window space
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4);
packet[p] = MESSAGE.CHANNEL_CLOSE;
writeUInt32BE(packet, chan, ++p);
this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`);
sendPacket(this, this._packetRW.write.finalize(packet));
}
channelWindowAdjust(chan, amount) {
// Does not consume window space
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + 4);
packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST;
writeUInt32BE(packet, chan, ++p);
writeUInt32BE(packet, amount, p += 4);
this._debug && this._debug(
`Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})`
);
sendPacket(this, this._packetRW.write.finalize(packet));
}
channelData(chan, data) {
const isBuffer = Buffer.isBuffer(data);
const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen);
packet[p] = MESSAGE.CHANNEL_DATA;
writeUInt32BE(packet, chan, ++p);
writeUInt32BE(packet, dataLen, p += 4);
if (isBuffer)
packet.set(data, p += 4);
else
packet.utf8Write(data, p += 4, dataLen);
this._debug && this._debug(
`Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})`
);
sendPacket(this, this._packetRW.write.finalize(packet));
}
channelExtData(chan, data, type) {
const isBuffer = Buffer.isBuffer(data);
const dataLen = (isBuffer ? data.length : Buffer.byteLength(data));
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen);
packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA;
writeUInt32BE(packet, chan, ++p);
writeUInt32BE(packet, type, p += 4);
writeUInt32BE(packet, dataLen, p += 4);
if (isBuffer)
packet.set(data, p += 4);
else
packet.utf8Write(data, p += 4, dataLen);
this._debug
&& this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`);
sendPacket(this, this._packetRW.write.finalize(packet));
}
channelOpenConfirm(remote, local, initWindow, maxPacket) {
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4);
packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION;
writeUInt32BE(packet, remote, ++p);
writeUInt32BE(packet, local, p += 4);
writeUInt32BE(packet, initWindow, p += 4);
writeUInt32BE(packet, maxPacket, p += 4);
this._debug && this._debug(
`Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})`
);
sendPacket(this, this._packetRW.write.finalize(packet));
}
channelOpenFail(remote, reason, desc) {
if (typeof desc !== 'string')
desc = '';
const descLen = Buffer.byteLength(desc);
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4);
packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE;
writeUInt32BE(packet, remote, ++p);
writeUInt32BE(packet, reason, p += 4);
writeUInt32BE(packet, descLen, p += 4);
p += 4;
if (descLen) {
packet.utf8Write(desc, p, descLen);
p += descLen;
}
writeUInt32BE(packet, 0, p); // Empty language tag
this._debug
&& this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`);
sendPacket(this, this._packetRW.write.finalize(packet));
}
// ===========================================================================
// Client-specific ===========================================================
// ===========================================================================
// Global
// ------
service(name) {
if (this._server)
throw new Error('Client-only method called in server mode');
const nameLen = Buffer.byteLength(name);
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + nameLen);
packet[p] = MESSAGE.SERVICE_REQUEST;
writeUInt32BE(packet, nameLen, ++p);
packet.utf8Write(name, p += 4, nameLen);
this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`);
sendPacket(this, this._packetRW.write.finalize(packet));
}
// 'ssh-userauth' service-specific
// -------------------------------
authPassword(username, password, newPassword) {
if (this._server)
throw new Error('Client-only method called in server mode');
const userLen = Buffer.byteLength(username);
const passLen = Buffer.byteLength(password);
const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0);
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(
1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen
+ (newPassword ? 4 + newPassLen : 0)
);
packet[p] = MESSAGE.USERAUTH_REQUEST;
writeUInt32BE(packet, userLen, ++p);
packet.utf8Write(username, p += 4, userLen);
writeUInt32BE(packet, 14, p += userLen);
packet.utf8Write('ssh-connection', p += 4, 14);
writeUInt32BE(packet, 8, p += 14);
packet.utf8Write('password', p += 4, 8);
packet[p += 8] = (newPassword ? 1 : 0);
writeUInt32BE(packet, passLen, ++p);
if (Buffer.isBuffer(password))
bufferCopy(password, packet, 0, passLen, p += 4);
else
packet.utf8Write(password, p += 4, passLen);
if (newPassword) {
writeUInt32BE(packet, newPassLen, p += passLen);
if (Buffer.isBuffer(newPassword))
bufferCopy(newPassword, packet, 0, newPassLen, p += 4);
else
packet.utf8Write(newPassword, p += 4, newPassLen);
this._debug && this._debug(
'Outbound: Sending USERAUTH_REQUEST (changed password)'
);
} else {
this._debug && this._debug(
'Outbound: Sending USERAUTH_REQUEST (password)'
);
}
this._authsQueue.push('password');
sendPacket(this, this._packetRW.write.finalize(packet));
}
authPK(username, pubKey, cbSign) {
if (this._server)
throw new Error('Client-only method called in server mode');
pubKey = parseKey(pubKey);
if (pubKey instanceof Error)
throw new Error('Invalid key');
const keyType = pubKey.type;
pubKey = pubKey.getPublicSSH();
const userLen = Buffer.byteLength(username);
const algoLen = Buffer.byteLength(keyType);
const pubKeyLen = pubKey.length;
const sessionID = this._kex.sessionID;
const sesLen = sessionID.length;
const payloadLen =
(cbSign ? 4 + sesLen : 0)
+ 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen;
let packet;
let p;
if (cbSign) {
packet = Buffer.allocUnsafe(payloadLen);
p = 0;
writeUInt32BE(packet, sesLen, p);
packet.set(sessionID, p += 4);
p += sesLen;
} else {
packet = this._packetRW.write.alloc(payloadLen);
p = this._packetRW.write.allocStart;
}
packet[p] = MESSAGE.USERAUTH_REQUEST;
writeUInt32BE(packet, userLen, ++p);
packet.utf8Write(username, p += 4, userLen);
writeUInt32BE(packet, 14, p += userLen);
packet.utf8Write('ssh-connection', p += 4, 14);
writeUInt32BE(packet, 9, p += 14);
packet.utf8Write('publickey', p += 4, 9);
packet[p += 9] = (cbSign ? 1 : 0);
writeUInt32BE(packet, algoLen, ++p);
packet.utf8Write(keyType, p += 4, algoLen);
writeUInt32BE(packet, pubKeyLen, p += algoLen);
packet.set(pubKey, p += 4);
if (!cbSign) {
this._authsQueue.push('publickey');
this._debug && this._debug(
'Outbound: Sending USERAUTH_REQUEST (publickey -- check)'
);
sendPacket(this, this._packetRW.write.finalize(packet));
return;
}
cbSign(packet, (signature) => {
signature = convertSignature(signature, keyType);
if (signature === false)
throw new Error('Error while converting handshake signature');
const sigLen = signature.length;
p = this._packetRW.write.allocStart;
packet = this._packetRW.write.alloc(
1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4
+ 4 + algoLen + 4 + sigLen
);
// TODO: simply copy from original "packet" to new `packet` to avoid
// having to write each individual field a second time?
packet[p] = MESSAGE.USERAUTH_REQUEST;
writeUInt32BE(packet, userLen, ++p);
packet.utf8Write(username, p += 4, userLen);
writeUInt32BE(packet, 14, p += userLen);
packet.utf8Write('ssh-connection', p += 4, 14);
writeUInt32BE(packet, 9, p += 14);
packet.utf8Write('publickey', p += 4, 9);
packet[p += 9] = 1;
writeUInt32BE(packet, algoLen, ++p);
packet.utf8Write(keyType, p += 4, algoLen);
writeUInt32BE(packet, pubKeyLen, p += algoLen);
packet.set(pubKey, p += 4);
writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen);
writeUInt32BE(packet, algoLen, p += 4);
packet.utf8Write(keyType, p += 4, algoLen);
writeUInt32BE(packet, sigLen, p += algoLen);
packet.set(signature, p += 4);
// Servers shouldn't send packet type 60 in response to signed publickey
// attempts, but if they do, interpret as type 60.
this._authsQueue.push('publickey');
this._debug && this._debug(
'Outbound: Sending USERAUTH_REQUEST (publickey)'
);
sendPacket(this, this._packetRW.write.finalize(packet));
});
}
authHostbased(username, pubKey, hostname, userlocal, cbSign) {
// TODO: Make DRY by sharing similar code with authPK()
if (this._server)
throw new Error('Client-only method called in server mode');
pubKey = parseKey(pubKey);
if (pubKey instanceof Error)
throw new Error('Invalid key');
const keyType = pubKey.type;
pubKey = pubKey.getPublicSSH();
const userLen = Buffer.byteLength(username);
const algoLen = Buffer.byteLength(keyType);
const pubKeyLen = pubKey.length;
const sessionID = this._kex.sessionID;
const sesLen = sessionID.length;
const hostnameLen = Buffer.byteLength(hostname);
const userlocalLen = Buffer.byteLength(userlocal);
const data = Buffer.allocUnsafe(
4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen
+ 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen
);
let p = 0;
writeUInt32BE(data, sesLen, p);
data.set(sessionID, p += 4);
data[p += sesLen] = MESSAGE.USERAUTH_REQUEST;
writeUInt32BE(data, userLen, ++p);
data.utf8Write(username, p += 4, userLen);
writeUInt32BE(data, 14, p += userLen);
data.utf8Write('ssh-connection', p += 4, 14);
writeUInt32BE(data, 9, p += 14);
data.utf8Write('hostbased', p += 4, 9);
writeUInt32BE(data, algoLen, p += 9);
data.utf8Write(keyType, p += 4, algoLen);
writeUInt32BE(data, pubKeyLen, p += algoLen);
data.set(pubKey, p += 4);
writeUInt32BE(data, hostnameLen, p += pubKeyLen);
data.utf8Write(hostname, p += 4, hostnameLen);
writeUInt32BE(data, userlocalLen, p += hostnameLen);
data.utf8Write(userlocal, p += 4, userlocalLen);
cbSign(data, (signature) => {
signature = convertSignature(signature, keyType);
if (!signature)
throw new Error('Error while converting handshake signature');
const sigLen = signature.length;
const reqDataLen = (data.length - sesLen - 4);
p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(
reqDataLen + 4 + 4 + algoLen + 4 + sigLen
);
bufferCopy(data, packet, 4 + sesLen, data.length, p);
writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen);
writeUInt32BE(packet, algoLen, p += 4);
packet.utf8Write(keyType, p += 4, algoLen);
writeUInt32BE(packet, sigLen, p += algoLen);
packet.set(signature, p += 4);
this._authsQueue.push('hostbased');
this._debug && this._debug(
'Outbound: Sending USERAUTH_REQUEST (hostbased)'
);
sendPacket(this, this._packetRW.write.finalize(packet));
});
}
authKeyboard(username) {
if (this._server)
throw new Error('Client-only method called in server mode');
const userLen = Buffer.byteLength(username);
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(
1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4
);
packet[p] = MESSAGE.USERAUTH_REQUEST;
writeUInt32BE(packet, userLen, ++p);
packet.utf8Write(username, p += 4, userLen);
writeUInt32BE(packet, 14, p += userLen);
packet.utf8Write('ssh-connection', p += 4, 14);
writeUInt32BE(packet, 20, p += 14);
packet.utf8Write('keyboard-interactive', p += 4, 20);
writeUInt32BE(packet, 0, p += 20);
writeUInt32BE(packet, 0, p += 4);
this._authsQueue.push('keyboard-interactive');
this._debug && this._debug(
'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)'
);
sendPacket(this, this._packetRW.write.finalize(packet));
}
authNone(username) {
if (this._server)
throw new Error('Client-only method called in server mode');
const userLen = Buffer.byteLength(username);
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4);
packet[p] = MESSAGE.USERAUTH_REQUEST;
writeUInt32BE(packet, userLen, ++p);
packet.utf8Write(username, p += 4, userLen);
writeUInt32BE(packet, 14, p += userLen);
packet.utf8Write('ssh-connection', p += 4, 14);
writeUInt32BE(packet, 4, p += 14);
packet.utf8Write('none', p += 4, 4);
this._authsQueue.push('none');
this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)');
sendPacket(this, this._packetRW.write.finalize(packet));
}
authInfoRes(responses) {
if (this._server)
throw new Error('Client-only method called in server mode');
let responsesTotalLen = 0;
let responseLens;
if (responses) {
responseLens = new Array(responses.length);
for (let i = 0; i < responses.length; ++i) {
const len = Buffer.byteLength(responses[i]);
responseLens[i] = len;
responsesTotalLen += 4 + len;
}
}
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen);
packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE;
if (responses) {
writeUInt32BE(packet, responses.length, ++p);
p += 4;
for (let i = 0; i < responses.length; ++i) {
const len = responseLens[i];
writeUInt32BE(packet, len, p);
p += 4;
if (len) {
packet.utf8Write(responses[i], p, len);
p += len;
}
}
} else {
writeUInt32BE(packet, 0, ++p);
}
this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE');
sendPacket(this, this._packetRW.write.finalize(packet));
}
// 'ssh-connection' service-specific
// ---------------------------------
tcpipForward(bindAddr, bindPort, wantReply) {
if (this._server)
throw new Error('Client-only method called in server mode');
const addrLen = Buffer.byteLength(bindAddr);
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4);
packet[p] = MESSAGE.GLOBAL_REQUEST;
writeUInt32BE(packet, 13, ++p);
packet.utf8Write('tcpip-forward', p += 4, 13);
packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0);
writeUInt32BE(packet, addrLen, ++p);
packet.utf8Write(bindAddr, p += 4, addrLen);
writeUInt32BE(packet, bindPort, p += addrLen);
this._debug
&& this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)');
sendPacket(this, this._packetRW.write.finalize(packet));
}
cancelTcpipForward(bindAddr, bindPort, wantReply) {
if (this._server)
throw new Error('Client-only method called in server mode');
const addrLen = Buffer.byteLength(bindAddr);
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4);
packet[p] = MESSAGE.GLOBAL_REQUEST;
writeUInt32BE(packet, 20, ++p);
packet.utf8Write('cancel-tcpip-forward', p += 4, 20);
packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0);
writeUInt32BE(packet, addrLen, ++p);
packet.utf8Write(bindAddr, p += 4, addrLen);
writeUInt32BE(packet, bindPort, p += addrLen);
this._debug
&& this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)');
sendPacket(this, this._packetRW.write.finalize(packet));
}
openssh_streamLocalForward(socketPath, wantReply) {
if (this._server)
throw new Error('Client-only method called in server mode');
const socketPathLen = Buffer.byteLength(socketPath);
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(
1 + 4 + 31 + 1 + 4 + socketPathLen
);
packet[p] = MESSAGE.GLOBAL_REQUEST;
writeUInt32BE(packet, 31, ++p);
packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31);
packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0);
writeUInt32BE(packet, socketPathLen, ++p);
packet.utf8Write(socketPath, p += 4, socketPathLen);
this._debug && this._debug(
'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)'
);
sendPacket(this, this._packetRW.write.finalize(packet));
}
openssh_cancelStreamLocalForward(socketPath, wantReply) {
if (this._server)
throw new Error('Client-only method called in server mode');
const socketPathLen = Buffer.byteLength(socketPath);
let p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(
1 + 4 + 38 + 1 + 4 + socketPathLen
);
packet[p] = MESSAGE.GLOBAL_REQUEST;
writeUInt32BE(packet, 38, ++p);
packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38);
packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0);
writeUInt32BE(packet, socketPathLen, ++p);
packet.utf8Write(socketPath, p += 4, socketPathLen);
if (this._debug) {
this._debug(
'Outbound: Sending GLOBAL_REQUEST '
+ '(cancel-streamlocal-forward@openssh.com)'
);
}
sendPacket(this, this._packetRW.write.finalize(packet));