-
Notifications
You must be signed in to change notification settings - Fork 144
/
ssh.js
5374 lines (4691 loc) · 160 KB
/
ssh.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: * Automatic re-key every (configurable) n bytes or length of time
// - RFC suggests every 1GB of transmitted data or 1 hour, whichever
// comes sooner
// * Filter control codes from strings
// (as per http://tools.ietf.org/html/rfc4251#section-9.2)
var crypto = require('crypto');
var zlib = require('zlib');
var TransformStream = require('stream').Transform;
var inherits = require('util').inherits;
var inspect = require('util').inspect;
var StreamSearch = require('streamsearch');
var Ber = require('asn1').Ber;
var readUInt32BE = require('./buffer-helpers').readUInt32BE;
var writeUInt32BE = require('./buffer-helpers').writeUInt32BE;
var consts = require('./constants');
var utils = require('./utils');
var iv_inc = utils.iv_inc;
var readString = utils.readString;
var readInt = utils.readInt;
var DSASigBERToBare = utils.DSASigBERToBare;
var ECDSASigASN1ToSSH = utils.ECDSASigASN1ToSSH;
var sigSSHToASN1 = utils.sigSSHToASN1;
var parseDERKey = require('./keyParser').parseDERKey;
var CIPHER_INFO = consts.CIPHER_INFO;
var HMAC_INFO = consts.HMAC_INFO;
var MESSAGE = consts.MESSAGE;
var DYNAMIC_KEXDH_MESSAGE = consts.DYNAMIC_KEXDH_MESSAGE;
var KEXDH_MESSAGE = consts.KEXDH_MESSAGE;
var ALGORITHMS = consts.ALGORITHMS;
var DISCONNECT_REASON = consts.DISCONNECT_REASON;
var CHANNEL_OPEN_FAILURE = consts.CHANNEL_OPEN_FAILURE;
var SSH_TO_OPENSSL = consts.SSH_TO_OPENSSL;
var TERMINAL_MODE = consts.TERMINAL_MODE;
var SIGNALS = consts.SIGNALS;
var EDDSA_SUPPORTED = consts.EDDSA_SUPPORTED;
var CURVE25519_SUPPORTED = consts.CURVE25519_SUPPORTED;
var BUGS = consts.BUGS;
var BUGGY_IMPLS = consts.BUGGY_IMPLS;
var BUGGY_IMPLS_LEN = BUGGY_IMPLS.length;
var MODULE_VER = require('../package.json').version;
var I = 0;
var IN_INIT = I++;
var IN_GREETING = I++;
var IN_HEADER = I++;
var IN_PACKETBEFORE = I++;
var IN_PACKET = I++;
var IN_PACKETDATA = I++;
var IN_PACKETDATAVERIFY = I++;
var IN_PACKETDATAAFTER = I++;
var OUT_INIT = I++;
var OUT_READY = I++;
var OUT_REKEYING = I++;
var MAX_SEQNO = 4294967295;
var MAX_PACKET_SIZE = 35000;
var MAX_PACKETS_REKEYING = 50;
var EXP_TYPE_HEADER = 0;
var EXP_TYPE_LF = 1;
var EXP_TYPE_BYTES = 2; // Waits until n bytes have been seen
var Z_PARTIAL_FLUSH = zlib.Z_PARTIAL_FLUSH;
var ZLIB_OPTS = { flush: Z_PARTIAL_FLUSH };
var RE_NULL = /\x00/g;
var IDENT_PREFIX_BUFFER = Buffer.from('SSH-');
var EMPTY_BUFFER = Buffer.allocUnsafe(0);
var HMAC_COMPUTE = Buffer.allocUnsafe(9);
var PING_PACKET = 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
]);
var NEWKEYS_PACKET = Buffer.from([MESSAGE.NEWKEYS]);
var USERAUTH_SUCCESS_PACKET = Buffer.from([MESSAGE.USERAUTH_SUCCESS]);
var REQUEST_SUCCESS_PACKET = Buffer.from([MESSAGE.REQUEST_SUCCESS]);
var REQUEST_FAILURE_PACKET = Buffer.from([MESSAGE.REQUEST_FAILURE]);
var NO_TERMINAL_MODES_BUFFER = Buffer.from([TERMINAL_MODE.TTY_OP_END]);
var KEXDH_GEX_REQ_PACKET = Buffer.from([
MESSAGE.KEXDH_GEX_REQUEST,
// Minimal size in bits of an acceptable group
0, 0, 4, 0, // 1024, modp2
// Preferred size in bits of the group the server will send
0, 0, 16, 0, // 4096, modp16
// Maximal size in bits of an acceptable group
0, 0, 32, 0 // 8192, modp18
]);
function DEBUG_NOOP(msg) {}
function SSH2Stream(cfg) {
if (typeof cfg !== 'object' || cfg === null)
cfg = {};
TransformStream.call(this, {
highWaterMark: (typeof cfg.highWaterMark === 'number'
? cfg.highWaterMark
: 32 * 1024)
});
this._needContinue = false;
this.bytesSent = this.bytesReceived = 0;
this.debug = (typeof cfg.debug === 'function' ? cfg.debug : DEBUG_NOOP);
this.server = (cfg.server === true);
this.maxPacketSize = (typeof cfg.maxPacketSize === 'number'
? cfg.maxPacketSize
: MAX_PACKET_SIZE);
// Bitmap that indicates any bugs the remote side has. This is determined
// by the reported software version.
this.remoteBugs = 0;
if (this.server) {
// TODO: Remove when we support group exchange for server implementation
this.remoteBugs = BUGS.BAD_DHGEX;
}
this.readable = true;
var self = this;
var hostKeys = cfg.hostKeys;
if (this.server && (typeof hostKeys !== 'object' || hostKeys === null))
throw new Error('hostKeys must be an object keyed on host key type');
this.config = {
// Server
hostKeys: hostKeys, // All keys supported by server
// Client/Server
ident: 'SSH-2.0-'
+ (cfg.ident
|| ('ssh2js' + MODULE_VER + (this.server ? 'srv' : ''))),
algorithms: {
kex: ALGORITHMS.KEX,
kexBuf: ALGORITHMS.KEX_BUF,
serverHostKey: ALGORITHMS.SERVER_HOST_KEY,
serverHostKeyBuf: ALGORITHMS.SERVER_HOST_KEY_BUF,
cipher: ALGORITHMS.CIPHER,
cipherBuf: ALGORITHMS.CIPHER_BUF,
hmac: ALGORITHMS.HMAC,
hmacBuf: ALGORITHMS.HMAC_BUF,
compress: ALGORITHMS.COMPRESS,
compressBuf: ALGORITHMS.COMPRESS_BUF
}
};
// RFC 4253 states the identification string must not contain NULL
this.config.ident.replace(RE_NULL, '');
if (this.config.ident.length + 2 /* Account for "\r\n" */ > 255)
throw new Error('ident too long');
if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) {
var algos = cfg.algorithms;
if (Array.isArray(algos.kex) && algos.kex.length > 0) {
this.config.algorithms.kex = algos.kex;
if (!Buffer.isBuffer(algos.kexBuf))
algos.kexBuf = Buffer.from(algos.kex.join(','), 'ascii');
this.config.algorithms.kexBuf = algos.kexBuf;
}
if (Array.isArray(algos.serverHostKey) && algos.serverHostKey.length > 0) {
this.config.algorithms.serverHostKey = algos.serverHostKey;
if (!Buffer.isBuffer(algos.serverHostKeyBuf)) {
algos.serverHostKeyBuf = Buffer.from(algos.serverHostKey.join(','),
'ascii');
}
this.config.algorithms.serverHostKeyBuf = algos.serverHostKeyBuf;
}
if (Array.isArray(algos.cipher) && algos.cipher.length > 0) {
this.config.algorithms.cipher = algos.cipher;
if (!Buffer.isBuffer(algos.cipherBuf))
algos.cipherBuf = Buffer.from(algos.cipher.join(','), 'ascii');
this.config.algorithms.cipherBuf = algos.cipherBuf;
}
if (Array.isArray(algos.hmac) && algos.hmac.length > 0) {
this.config.algorithms.hmac = algos.hmac;
if (!Buffer.isBuffer(algos.hmacBuf))
algos.hmacBuf = Buffer.from(algos.hmac.join(','), 'ascii');
this.config.algorithms.hmacBuf = algos.hmacBuf;
}
if (Array.isArray(algos.compress) && algos.compress.length > 0) {
this.config.algorithms.compress = algos.compress;
if (!Buffer.isBuffer(algos.compressBuf))
algos.compressBuf = Buffer.from(algos.compress.join(','), 'ascii');
this.config.algorithms.compressBuf = algos.compressBuf;
}
}
this.reset(true);
// Common events
this.on('end', function() {
// Let GC collect any Buffers we were previously storing
self.readable = false;
self._state = undefined;
self.reset();
self._state.outgoing.bufSeqno = undefined;
});
this.on('DISCONNECT', function(reason, code, desc, lang) {
onDISCONNECT(self, reason, code, desc, lang);
});
this.on('KEXINIT', function(init, firstFollows) {
onKEXINIT(self, init, firstFollows);
});
this.on('NEWKEYS', function() { onNEWKEYS(self); });
if (this.server) {
// Server-specific events
this.on('KEXDH_INIT', function(e) { onKEXDH_INIT(self, e); });
} else {
// Client-specific events
this.on('KEXDH_REPLY', function(info) { onKEXDH_REPLY(self, info); })
.on('KEXDH_GEX_GROUP',
function(prime, gen) { onKEXDH_GEX_GROUP(self, prime, gen); });
}
if (this.server) {
// Greeting displayed before the ssh identification string is sent, this is
// usually ignored by most clients
if (typeof cfg.greeting === 'string' && cfg.greeting.length) {
if (cfg.greeting.slice(-2) === '\r\n')
this.push(cfg.greeting);
else
this.push(cfg.greeting + '\r\n');
}
// Banner shown after the handshake completes, but before user
// authentication begins
if (typeof cfg.banner === 'string' && cfg.banner.length) {
if (cfg.banner.slice(-2) === '\r\n')
this.banner = cfg.banner;
else
this.banner = cfg.banner + '\r\n';
}
}
this.debug('DEBUG: Local ident: ' + inspect(this.config.ident));
this.push(this.config.ident + '\r\n');
this._state.incoming.expectedPacket = 'KEXINIT';
}
inherits(SSH2Stream, TransformStream);
SSH2Stream.prototype.__read = TransformStream.prototype._read;
SSH2Stream.prototype._read = function(n) {
if (this._needContinue) {
this._needContinue = false;
this.emit('continue');
}
return this.__read(n);
};
SSH2Stream.prototype.__push = TransformStream.prototype.push;
SSH2Stream.prototype.push = function(chunk, encoding) {
var ret = this.__push(chunk, encoding);
this._needContinue = (ret === false);
return ret;
};
SSH2Stream.prototype._cleanup = function(callback) {
this.reset();
this.debug('DEBUG: Parser: Malformed packet');
callback && callback(new Error('Malformed packet'));
};
SSH2Stream.prototype._transform = function(chunk, encoding, callback, decomp) {
var skipDecrypt = false;
var decryptAuthMode = false;
var state = this._state;
var instate = state.incoming;
var outstate = state.outgoing;
var expect = instate.expect;
var decrypt = instate.decrypt;
var decompress = instate.decompress;
var chlen = chunk.length;
var chleft = 0;
var debug = this.debug;
var self = this;
var i = 0;
var p = i;
var blockLen;
var buffer;
var buf;
var r;
this.bytesReceived += chlen;
while (true) {
if (expect.type !== undefined) {
if (i >= chlen)
break;
if (expect.type === EXP_TYPE_BYTES) {
chleft = (chlen - i);
var pktLeft = (expect.buf.length - expect.ptr);
if (pktLeft <= chleft) {
chunk.copy(expect.buf, expect.ptr, i, i + pktLeft);
i += pktLeft;
buffer = expect.buf;
expect.buf = undefined;
expect.ptr = 0;
expect.type = undefined;
} else {
chunk.copy(expect.buf, expect.ptr, i);
expect.ptr += chleft;
i += chleft;
}
continue;
} else if (expect.type === EXP_TYPE_HEADER) {
i += instate.search.push(chunk);
if (expect.type !== undefined)
continue;
} else if (expect.type === EXP_TYPE_LF) {
if (++expect.ptr + 4 /* Account for "SSH-" */ > 255) {
this.reset();
debug('DEBUG: Parser: Identification string exceeded 255 characters');
return callback(new Error('Max identification string size exceeded'));
}
if (chunk[i] === 0x0A) {
expect.type = undefined;
if (p < i) {
if (expect.buf === undefined)
expect.buf = chunk.toString('ascii', p, i);
else
expect.buf += chunk.toString('ascii', p, i);
}
buffer = expect.buf;
expect.buf = undefined;
++i;
} else {
if (++i === chlen && p < i) {
if (expect.buf === undefined)
expect.buf = chunk.toString('ascii', p, i);
else
expect.buf += chunk.toString('ascii', p, i);
}
continue;
}
}
}
if (instate.status === IN_INIT) {
if (!this.readable)
return callback();
if (this.server) {
// Retrieve what should be the start of the protocol version exchange
if (!buffer) {
debug('DEBUG: Parser: IN_INIT (waiting for identification begin)');
expectData(this, EXP_TYPE_BYTES, 4);
} else {
if (buffer[0] === 0x53 // S
&& buffer[1] === 0x53 // S
&& buffer[2] === 0x48 // H
&& buffer[3] === 0x2D) { // -
instate.status = IN_GREETING;
debug('DEBUG: Parser: IN_INIT (waiting for rest of identification)');
} else {
this.reset();
debug('DEBUG: Parser: Bad identification start');
return callback(new Error('Bad identification start'));
}
}
} else {
debug('DEBUG: Parser: IN_INIT');
// Retrieve any bytes that may come before the protocol version exchange
var ss = instate.search = new StreamSearch(IDENT_PREFIX_BUFFER);
ss.on('info', function onInfo(matched, data, start, end) {
if (data) {
if (instate.greeting === undefined)
instate.greeting = data.toString('binary', start, end);
else
instate.greeting += data.toString('binary', start, end);
}
if (matched) {
expect.type = undefined;
instate.search.removeListener('info', onInfo);
}
});
ss.maxMatches = 1;
expectData(this, EXP_TYPE_HEADER);
instate.status = IN_GREETING;
}
} else if (instate.status === IN_GREETING) {
debug('DEBUG: Parser: IN_GREETING');
instate.search = undefined;
// Retrieve the identification bytes after the "SSH-" header
p = i;
expectData(this, EXP_TYPE_LF);
instate.status = IN_HEADER;
} else if (instate.status === IN_HEADER) {
debug('DEBUG: Parser: IN_HEADER');
if (buffer.charCodeAt(buffer.length - 1) === 13)
buffer = buffer.slice(0, -1);
var idxDash = buffer.indexOf('-');
var idxSpace = buffer.indexOf(' ');
var header = {
// RFC says greeting SHOULD be utf8
greeting: instate.greeting,
identRaw: 'SSH-' + buffer,
versions: {
protocol: buffer.substr(0, idxDash),
software: (idxSpace === -1
? buffer.substring(idxDash + 1)
: buffer.substring(idxDash + 1, idxSpace))
},
comments: (idxSpace > -1 ? buffer.substring(idxSpace + 1) : undefined)
};
instate.greeting = undefined;
if (header.versions.protocol !== '1.99'
&& header.versions.protocol !== '2.0') {
this.reset();
debug('DEBUG: Parser: protocol version not supported: '
+ header.versions.protocol);
return callback(new Error('Protocol version not supported'));
} else
this.emit('header', header);
if (instate.status === IN_INIT) {
// We reset from an event handler, possibly due to an unsupported SSH
// protocol version?
return;
}
var identRaw = header.identRaw;
var software = header.versions.software;
this.debug('DEBUG: Remote ident: ' + inspect(identRaw));
for (var j = 0, rule; j < BUGGY_IMPLS_LEN; ++j) {
rule = BUGGY_IMPLS[j];
if (typeof rule[0] === 'string') {
if (software === rule[0])
this.remoteBugs |= rule[1];
} else if (rule[0].test(software))
this.remoteBugs |= rule[1];
}
instate.identRaw = identRaw;
// Adjust bytesReceived first otherwise it will have an incorrectly larger
// total when we call back into this function after completing KEXINIT
this.bytesReceived -= (chlen - i);
KEXINIT(this, function() {
if (i === chlen)
callback();
else
self._transform(chunk.slice(i), encoding, callback);
});
instate.status = IN_PACKETBEFORE;
return;
} else if (instate.status === IN_PACKETBEFORE) {
blockLen = (decrypt.instance ? decrypt.info.blockLen : 8);
debug('DEBUG: Parser: IN_PACKETBEFORE (expecting ' + blockLen + ')');
// Wait for the right number of bytes so we can determine the incoming
// packet length
expectData(this, EXP_TYPE_BYTES, blockLen, decrypt.buf);
instate.status = IN_PACKET;
} else if (instate.status === IN_PACKET) {
debug('DEBUG: Parser: IN_PACKET');
if (decrypt.instance) {
decryptAuthMode = (decrypt.info.authLen > 0);
if (!decryptAuthMode)
buffer = decryptData(this, buffer);
blockLen = decrypt.info.blockLen;
} else {
decryptAuthMode = false;
blockLen = 8;
}
r = readInt(buffer, 0, this, callback);
if (r === false)
return;
var hmacInfo = instate.hmac.info;
var macSize;
if (hmacInfo)
macSize = hmacInfo.actualLen;
else
macSize = 0;
var fullPacketLen = r + 4 + macSize;
var maxPayloadLen = this.maxPacketSize;
if (decompress.instance) {
// Account for compressed payloads
// This formula is taken from dropbear which derives it from zlib's
// documentation. Explanation from dropbear:
/* For exact details see http://www.zlib.net/zlib_tech.html
* 5 bytes per 16kB block, plus 6 bytes for the stream.
* We might allocate 5 unnecessary bytes here if it's an
* exact multiple. */
maxPayloadLen += (((this.maxPacketSize / 16384) + 1) * 5 + 6);
}
if (r > maxPayloadLen
// TODO: Change 16 to "MAX(16, decrypt.info.blockLen)" when/if SSH2
// adopts 512-bit ciphers
|| fullPacketLen < (16 + macSize)
|| ((r + (decryptAuthMode ? 0 : 4)) % blockLen) !== 0) {
this.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR);
debug('DEBUG: Parser: Bad packet length (' + fullPacketLen + ')');
return callback(new Error('Bad packet length'));
}
instate.pktLen = r;
var remainLen = instate.pktLen + 4 - blockLen;
if (decryptAuthMode) {
decrypt.instance.setAAD(buffer.slice(0, 4));
debug('DEBUG: Parser: pktLen:'
+ instate.pktLen
+ ',remainLen:'
+ remainLen);
} else {
instate.padLen = buffer[4];
debug('DEBUG: Parser: pktLen:'
+ instate.pktLen
+ ',padLen:'
+ instate.padLen
+ ',remainLen:'
+ remainLen);
}
if (remainLen > 0) {
if (decryptAuthMode)
instate.pktExtra = buffer.slice(4);
else
instate.pktExtra = buffer.slice(5);
// Grab the rest of the packet
expectData(this, EXP_TYPE_BYTES, remainLen);
instate.status = IN_PACKETDATA;
} else if (remainLen < 0)
instate.status = IN_PACKETBEFORE;
else {
// Entire message fit into one block
skipDecrypt = true;
instate.status = IN_PACKETDATA;
continue;
}
} else if (instate.status === IN_PACKETDATA) {
debug('DEBUG: Parser: IN_PACKETDATA');
if (decrypt.instance) {
decryptAuthMode = (decrypt.info.authLen > 0);
if (!skipDecrypt) {
if (!decryptAuthMode)
buffer = decryptData(this, buffer);
} else {
skipDecrypt = false;
}
} else {
decryptAuthMode = false;
skipDecrypt = false;
}
var padStart = instate.pktLen - instate.padLen - 1;
// TODO: Allocate a Buffer once that is slightly larger than maxPacketSize
// (to accommodate for packet length field and MAC) and re-use that
// instead
if (instate.pktExtra) {
buf = Buffer.allocUnsafe(instate.pktExtra.length + buffer.length);
instate.pktExtra.copy(buf);
buffer.copy(buf, instate.pktExtra.length);
instate.payload = buf.slice(0, padStart);
} else {
// Entire message fit into one block
if (decryptAuthMode)
buf = buffer.slice(4);
else
buf = buffer.slice(5);
instate.payload = buffer.slice(5, 5 + padStart);
}
if (instate.hmac.info !== undefined) {
// Wait for hmac hash
var inHMACSize = decrypt.info.authLen || instate.hmac.info.actualLen;
debug('DEBUG: Parser: HMAC size:' + inHMACSize);
expectData(this, EXP_TYPE_BYTES, inHMACSize, instate.hmac.buf);
instate.status = IN_PACKETDATAVERIFY;
instate.packet = buf;
} else
instate.status = IN_PACKETDATAAFTER;
instate.pktExtra = undefined;
buf = undefined;
} else if (instate.status === IN_PACKETDATAVERIFY) {
debug('DEBUG: Parser: IN_PACKETDATAVERIFY');
// Verify packet data integrity
if (hmacVerify(this, buffer)) {
debug('DEBUG: Parser: IN_PACKETDATAVERIFY (Valid HMAC)');
instate.status = IN_PACKETDATAAFTER;
instate.packet = undefined;
} else {
this.reset();
debug('DEBUG: Parser: IN_PACKETDATAVERIFY (Invalid HMAC)');
return callback(new Error('Invalid HMAC'));
}
} else if (instate.status === IN_PACKETDATAAFTER) {
if (decompress.instance) {
if (!decomp) {
debug('DEBUG: Parser: Decompressing');
decompress.instance.write(instate.payload);
var decompBuf = [];
var decompBufLen = 0;
decompress.instance.on('readable', function() {
var buf;
while (buf = this.read()) {
decompBuf.push(buf);
decompBufLen += buf.length;
}
}).flush(Z_PARTIAL_FLUSH, function() {
decompress.instance.removeAllListeners('readable');
if (decompBuf.length === 1)
instate.payload = decompBuf[0];
else
instate.payload = Buffer.concat(decompBuf, decompBufLen);
decompBuf = null;
var nextSlice;
if (i === chlen)
nextSlice = EMPTY_BUFFER; // Avoid slicing a zero-length buffer
else
nextSlice = chunk.slice(i);
self._transform(nextSlice, encoding, callback, true);
});
return;
} else {
// Make sure we reset this after this first time in the loop,
// otherwise we could end up trying to interpret as-is another
// compressed packet that is within the same chunk
decomp = false;
}
}
this.emit('packet');
var ptype = instate.payload[0];
if (debug !== DEBUG_NOOP) {
var msgPacket = 'DEBUG: Parser: IN_PACKETDATAAFTER, packet: ';
var authMethod = state.authsQueue[0];
var msgPktType = null;
if (outstate.status === OUT_REKEYING
&& !(ptype <= 4 || (ptype >= 20 && ptype <= 49)))
msgPacket += '(enqueued) ';
if (ptype === MESSAGE.KEXDH_INIT) {
switch (state.kex.type) {
case 'group':
msgPktType = 'KEXDH_INIT';
break;
case 'groupex':
msgPktType = 'KEXDH_GEX_REQUEST';
break;
default:
msgPktType = 'KEXECDH_INIT';
}
} else if (ptype === MESSAGE.KEXDH_REPLY) {
switch (state.kex.type) {
case 'group':
msgPktType = 'KEXDH_REPLY';
break;
case 'groupex':
msgPktType = 'KEXDH_GEX_GROUP';
break;
default:
msgPktType = 'KEXECDH_REPLY';
}
} else if (ptype === MESSAGE.KEXDH_GEX_GROUP) {
msgPktType = 'KEXDH_GEX_GROUP';
} else if (ptype === MESSAGE.KEXDH_GEX_REPLY) {
msgPktType = 'KEXDH_GEX_REPLY';
} else if (ptype === 60) {
if (authMethod === 'password')
msgPktType = 'USERAUTH_PASSWD_CHANGEREQ';
else if (authMethod === 'keyboard-interactive')
msgPktType = 'USERAUTH_INFO_REQUEST';
else if (authMethod === 'publickey')
msgPktType = 'USERAUTH_PK_OK';
else
msgPktType = 'UNKNOWN PACKET 60';
} else if (ptype === 61) {
if (authMethod === 'keyboard-interactive')
msgPktType = 'USERAUTH_INFO_RESPONSE';
else
msgPktType = 'UNKNOWN PACKET 61';
}
if (msgPktType === null)
msgPktType = MESSAGE[ptype];
// Don't write debug output for messages we custom make in parsePacket()
if (ptype !== MESSAGE.CHANNEL_OPEN
&& ptype !== MESSAGE.CHANNEL_REQUEST
&& ptype !== MESSAGE.CHANNEL_SUCCESS
&& ptype !== MESSAGE.CHANNEL_FAILURE
&& ptype !== MESSAGE.CHANNEL_EOF
&& ptype !== MESSAGE.CHANNEL_CLOSE
&& ptype !== MESSAGE.CHANNEL_DATA
&& ptype !== MESSAGE.CHANNEL_EXTENDED_DATA
&& ptype !== MESSAGE.CHANNEL_WINDOW_ADJUST
&& ptype !== MESSAGE.DISCONNECT
&& ptype !== MESSAGE.USERAUTH_REQUEST
&& ptype !== MESSAGE.GLOBAL_REQUEST)
debug(msgPacket + msgPktType);
}
// Only parse packet if we are not re-keying or the packet is not a
// transport layer packet needed for re-keying
if (outstate.status === OUT_READY
|| ptype <= 4
|| (ptype >= 20 && ptype <= 49)) {
if (parsePacket(this, callback) === false)
return;
if (instate.status === IN_INIT) {
// We were reset due to some error/disagreement ?
return;
}
} else if (outstate.status === OUT_REKEYING) {
if (instate.rekeyQueue.length === MAX_PACKETS_REKEYING) {
debug('DEBUG: Parser: Max incoming re-key queue length reached');
this.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR);
return callback(
new Error('Incoming re-key queue length limit reached')
);
}
// Make sure to record the sequence number in case we need it later on
// when we drain the queue (e.g. unknown packet)
var seqno = instate.seqno;
if (++instate.seqno > MAX_SEQNO)
instate.seqno = 0;
instate.rekeyQueue.push([seqno, instate.payload]);
}
instate.status = IN_PACKETBEFORE;
instate.payload = undefined;
}
if (buffer !== undefined)
buffer = undefined;
}
callback();
};
SSH2Stream.prototype.reset = function(noend) {
if (this._state) {
var state = this._state;
state.incoming.status = IN_INIT;
state.outgoing.status = OUT_INIT;
} else {
this._state = {
authsQueue: [],
hostkeyFormat: undefined,
kex: undefined,
incoming: {
status: IN_INIT,
expectedPacket: undefined,
search: undefined,
greeting: undefined,
seqno: 0,
pktLen: undefined,
padLen: undefined,
pktExtra: undefined,
payload: undefined,
packet: undefined,
kexinit: undefined,
identRaw: undefined,
rekeyQueue: [],
ignoreNext: false,
expect: {
amount: undefined,
type: undefined,
ptr: 0,
buf: undefined
},
decrypt: {
instance: false,
info: undefined,
iv: undefined,
key: undefined,
buf: undefined,
type: undefined
},
hmac: {
info: undefined,
key: undefined,
buf: undefined,
type: false
},
decompress: {
instance: false,
type: false
}
},
outgoing: {
status: OUT_INIT,
seqno: 0,
bufSeqno: Buffer.allocUnsafe(4),
rekeyQueue: [],
kexinit: undefined,
kexsecret: undefined,
pubkey: undefined,
exchangeHash: undefined,
sessionId: undefined,
sentNEWKEYS: false,
encrypt: {
instance: false,
info: undefined,
iv: undefined,
key: undefined,
type: undefined
},
hmac: {
info: undefined,
key: undefined,
buf: undefined,
type: false
},
compress: {
instance: false,
type: false,
queue: null
}
}
};
}
if (!noend) {
if (this.readable)
this.push(null);
}
};
// Common methods
// Global
SSH2Stream.prototype.disconnect = function(reason) {
/*
byte SSH_MSG_DISCONNECT
uint32 reason code
string description in ISO-10646 UTF-8 encoding
string language tag
*/
var buf = Buffer.alloc(1 + 4 + 4 + 4);
buf[0] = MESSAGE.DISCONNECT;
if (DISCONNECT_REASON[reason] === undefined)
reason = DISCONNECT_REASON.BY_APPLICATION;
writeUInt32BE(buf, reason, 1);
this.debug('DEBUG: Outgoing: Writing DISCONNECT ('
+ DISCONNECT_REASON[reason]
+ ')');
send(this, buf);
this.reset();
return false;
};
SSH2Stream.prototype.ping = function() {
this.debug('DEBUG: Outgoing: Writing ping (GLOBAL_REQUEST: keepalive@openssh.com)');
return send(this, PING_PACKET);
};
SSH2Stream.prototype.rekey = function() {
var status = this._state.outgoing.status;
if (status === OUT_REKEYING)
throw new Error('A re-key is already in progress');
else if (status !== OUT_READY)
throw new Error('Cannot re-key yet');
this.debug('DEBUG: Outgoing: Starting re-key');
return KEXINIT(this);
};
// 'ssh-connection' service-specific
SSH2Stream.prototype.requestSuccess = function(data) {
var buf;
if (Buffer.isBuffer(data)) {
buf = Buffer.allocUnsafe(1 + data.length);
buf[0] = MESSAGE.REQUEST_SUCCESS;
data.copy(buf, 1);
} else
buf = REQUEST_SUCCESS_PACKET;
this.debug('DEBUG: Outgoing: Writing REQUEST_SUCCESS');
return send(this, buf);
};
SSH2Stream.prototype.requestFailure = function() {
this.debug('DEBUG: Outgoing: Writing REQUEST_FAILURE');
return send(this, REQUEST_FAILURE_PACKET);
};
SSH2Stream.prototype.channelSuccess = function(chan) {
// Does not consume window space
var buf = Buffer.allocUnsafe(1 + 4);
buf[0] = MESSAGE.CHANNEL_SUCCESS;
writeUInt32BE(buf, chan, 1);
this.debug('DEBUG: Outgoing: Writing CHANNEL_SUCCESS (' + chan + ')');
return send(this, buf);
};
SSH2Stream.prototype.channelFailure = function(chan) {
// Does not consume window space
var buf = Buffer.allocUnsafe(1 + 4);
buf[0] = MESSAGE.CHANNEL_FAILURE;
writeUInt32BE(buf, chan, 1);
this.debug('DEBUG: Outgoing: Writing CHANNEL_FAILURE (' + chan + ')');
return send(this, buf);
};
SSH2Stream.prototype.channelEOF = function(chan) {
// Does not consume window space
var buf = Buffer.allocUnsafe(1 + 4);
buf[0] = MESSAGE.CHANNEL_EOF;
writeUInt32BE(buf, chan, 1);
this.debug('DEBUG: Outgoing: Writing CHANNEL_EOF (' + chan + ')');
return send(this, buf);
};
SSH2Stream.prototype.channelClose = function(chan) {
// Does not consume window space
var buf = Buffer.allocUnsafe(1 + 4);
buf[0] = MESSAGE.CHANNEL_CLOSE;
writeUInt32BE(buf, chan, 1);
this.debug('DEBUG: Outgoing: Writing CHANNEL_CLOSE (' + chan + ')');
return send(this, buf);
};
SSH2Stream.prototype.channelWindowAdjust = function(chan, amount) {
// Does not consume window space
var buf = Buffer.allocUnsafe(1 + 4 + 4);
buf[0] = MESSAGE.CHANNEL_WINDOW_ADJUST;
writeUInt32BE(buf, chan, 1);
writeUInt32BE(buf, amount, 5);
this.debug('DEBUG: Outgoing: Writing CHANNEL_WINDOW_ADJUST ('
+ chan
+ ', '
+ amount
+ ')');
return send(this, buf);
};
SSH2Stream.prototype.channelData = function(chan, data) {
var dataIsBuffer = Buffer.isBuffer(data);
var dataLen = (dataIsBuffer ? data.length : Buffer.byteLength(data));
var buf = Buffer.allocUnsafe(1 + 4 + 4 + dataLen);
buf[0] = MESSAGE.CHANNEL_DATA;
writeUInt32BE(buf, chan, 1);
writeUInt32BE(buf, dataLen, 5);
if (dataIsBuffer)
data.copy(buf, 9);
else
buf.write(data, 9, dataLen, 'utf8');
this.debug('DEBUG: Outgoing: Writing CHANNEL_DATA (' + chan + ')');
return send(this, buf);
};
SSH2Stream.prototype.channelExtData = function(chan, data, type) {
var dataIsBuffer = Buffer.isBuffer(data);
var dataLen = (dataIsBuffer ? data.length : Buffer.byteLength(data));
var buf = Buffer.allocUnsafe(1 + 4 + 4 + 4 + dataLen);
buf[0] = MESSAGE.CHANNEL_EXTENDED_DATA;
writeUInt32BE(buf, chan, 1);
writeUInt32BE(buf, type, 5);
writeUInt32BE(buf, dataLen, 9);
if (dataIsBuffer)
data.copy(buf, 13);
else
buf.write(data, 13, dataLen, 'utf8');
this.debug('DEBUG: Outgoing: Writing CHANNEL_EXTENDED_DATA (' + chan + ')');
return send(this, buf);
};
SSH2Stream.prototype.channelOpenConfirm = function(remoteChan, localChan,
initWindow, maxPacket) {
var buf = Buffer.allocUnsafe(1 + 4 + 4 + 4 + 4);
buf[0] = MESSAGE.CHANNEL_OPEN_CONFIRMATION;
writeUInt32BE(buf, remoteChan, 1);
writeUInt32BE(buf, localChan, 5);