-
Notifications
You must be signed in to change notification settings - Fork 665
/
client.js
2141 lines (1899 loc) · 61.9 KB
/
client.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:
// * add `.connected` or similar property to allow immediate connection
// status checking
// * add/improve debug output during user authentication phase
'use strict';
const {
createHash,
getHashes,
randomFillSync,
} = require('crypto');
const { Socket } = require('net');
const { lookup: dnsLookup } = require('dns');
const EventEmitter = require('events');
const HASHES = getHashes();
const {
COMPAT,
CHANNEL_EXTENDED_DATATYPE: { STDERR },
CHANNEL_OPEN_FAILURE,
DEFAULT_CIPHER,
DEFAULT_COMPRESSION,
DEFAULT_KEX,
DEFAULT_MAC,
DEFAULT_SERVER_HOST_KEY,
DISCONNECT_REASON,
DISCONNECT_REASON_BY_VALUE,
SUPPORTED_CIPHER,
SUPPORTED_COMPRESSION,
SUPPORTED_KEX,
SUPPORTED_MAC,
SUPPORTED_SERVER_HOST_KEY,
} = require('./protocol/constants.js');
const { init: cryptoInit } = require('./protocol/crypto.js');
const Protocol = require('./protocol/Protocol.js');
const { parseKey } = require('./protocol/keyParser.js');
const { SFTP } = require('./protocol/SFTP.js');
const {
bufferCopy,
makeBufferParser,
makeError,
readUInt32BE,
sigSSHToASN1,
writeUInt32BE,
} = require('./protocol/utils.js');
const { AgentContext, createAgent, isAgent } = require('./agent.js');
const {
Channel,
MAX_WINDOW,
PACKET_SIZE,
windowAdjust,
WINDOW_THRESHOLD,
} = require('./Channel.js');
const {
ChannelManager,
generateAlgorithmList,
isWritable,
onChannelOpenFailure,
onCHANNEL_CLOSE,
} = require('./utils.js');
const bufferParser = makeBufferParser();
const sigParser = makeBufferParser();
const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/;
const noop = (err) => {};
class Client extends EventEmitter {
constructor() {
super();
this.config = {
host: undefined,
port: undefined,
localAddress: undefined,
localPort: undefined,
forceIPv4: undefined,
forceIPv6: undefined,
keepaliveCountMax: undefined,
keepaliveInterval: undefined,
readyTimeout: undefined,
ident: undefined,
username: undefined,
password: undefined,
privateKey: undefined,
tryKeyboard: undefined,
agent: undefined,
allowAgentFwd: undefined,
authHandler: undefined,
hostHashAlgo: undefined,
hostHashCb: undefined,
strictVendor: undefined,
debug: undefined
};
this._agent = undefined;
this._readyTimeout = undefined;
this._chanMgr = undefined;
this._callbacks = undefined;
this._forwarding = undefined;
this._forwardingUnix = undefined;
this._acceptX11 = undefined;
this._agentFwdEnabled = undefined;
this._remoteVer = undefined;
this._protocol = undefined;
this._sock = undefined;
this._resetKA = undefined;
}
connect(cfg) {
if (this._sock && isWritable(this._sock)) {
this.once('close', () => {
this.connect(cfg);
});
this.end();
return this;
}
this.config.host = cfg.hostname || cfg.host || 'localhost';
this.config.port = cfg.port || 22;
this.config.localAddress = (typeof cfg.localAddress === 'string'
? cfg.localAddress
: undefined);
this.config.localPort = (typeof cfg.localPort === 'string'
|| typeof cfg.localPort === 'number'
? cfg.localPort
: undefined);
this.config.forceIPv4 = cfg.forceIPv4 || false;
this.config.forceIPv6 = cfg.forceIPv6 || false;
this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number'
&& cfg.keepaliveCountMax >= 0
? cfg.keepaliveCountMax
: 3);
this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number'
&& cfg.keepaliveInterval > 0
? cfg.keepaliveInterval
: 0);
this.config.readyTimeout = (typeof cfg.readyTimeout === 'number'
&& cfg.readyTimeout >= 0
? cfg.readyTimeout
: 20000);
this.config.ident = (typeof cfg.ident === 'string'
|| Buffer.isBuffer(cfg.ident)
? cfg.ident
: undefined);
const algorithms = {
kex: undefined,
serverHostKey: undefined,
cs: {
cipher: undefined,
mac: undefined,
compress: undefined,
lang: [],
},
sc: undefined,
};
let allOfferDefaults = true;
if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) {
algorithms.kex = generateAlgorithmList(cfg.algorithms.kex,
DEFAULT_KEX,
SUPPORTED_KEX);
if (algorithms.kex !== DEFAULT_KEX)
allOfferDefaults = false;
algorithms.serverHostKey =
generateAlgorithmList(cfg.algorithms.serverHostKey,
DEFAULT_SERVER_HOST_KEY,
SUPPORTED_SERVER_HOST_KEY);
if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY)
allOfferDefaults = false;
algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher,
DEFAULT_CIPHER,
SUPPORTED_CIPHER);
if (algorithms.cs.cipher !== DEFAULT_CIPHER)
allOfferDefaults = false;
algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac,
DEFAULT_MAC,
SUPPORTED_MAC);
if (algorithms.cs.mac !== DEFAULT_MAC)
allOfferDefaults = false;
algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress,
DEFAULT_COMPRESSION,
SUPPORTED_COMPRESSION);
if (algorithms.cs.compress !== DEFAULT_COMPRESSION)
allOfferDefaults = false;
if (!allOfferDefaults)
algorithms.sc = algorithms.cs;
}
if (typeof cfg.username === 'string')
this.config.username = cfg.username;
else if (typeof cfg.user === 'string')
this.config.username = cfg.user;
else
throw new Error('Invalid username');
this.config.password = (typeof cfg.password === 'string'
? cfg.password
: undefined);
this.config.privateKey = (typeof cfg.privateKey === 'string'
|| Buffer.isBuffer(cfg.privateKey)
? cfg.privateKey
: undefined);
this.config.localHostname = (typeof cfg.localHostname === 'string'
? cfg.localHostname
: undefined);
this.config.localUsername = (typeof cfg.localUsername === 'string'
? cfg.localUsername
: undefined);
this.config.tryKeyboard = (cfg.tryKeyboard === true);
if (typeof cfg.agent === 'string' && cfg.agent.length)
this.config.agent = createAgent(cfg.agent);
else if (isAgent(cfg.agent))
this.config.agent = cfg.agent;
else
this.config.agent = undefined;
this.config.allowAgentFwd = (cfg.agentForward === true
&& this.config.agent !== undefined);
let authHandler = this.config.authHandler = (
typeof cfg.authHandler === 'function'
|| Array.isArray(cfg.authHandler)
? cfg.authHandler
: undefined
);
this.config.strictVendor = (typeof cfg.strictVendor === 'boolean'
? cfg.strictVendor
: true);
const debug = this.config.debug = (typeof cfg.debug === 'function'
? cfg.debug
: undefined);
if (cfg.agentForward === true && !this.config.allowAgentFwd) {
throw new Error(
'You must set a valid agent path to allow agent forwarding'
);
}
let callbacks = this._callbacks = [];
this._chanMgr = new ChannelManager(this);
this._forwarding = {};
this._forwardingUnix = {};
this._acceptX11 = 0;
this._agentFwdEnabled = false;
this._agent = (this.config.agent ? this.config.agent : undefined);
this._remoteVer = undefined;
let privateKey;
if (this.config.privateKey) {
privateKey = parseKey(this.config.privateKey, cfg.passphrase);
if (privateKey instanceof Error)
throw new Error(`Cannot parse privateKey: ${privateKey.message}`);
if (Array.isArray(privateKey)) {
// OpenSSH's newer format only stores 1 key for now
privateKey = privateKey[0];
}
if (privateKey.getPrivatePEM() === null) {
throw new Error(
'privateKey value does not contain a (valid) private key'
);
}
}
let hostVerifier;
if (typeof cfg.hostVerifier === 'function') {
const hashCb = cfg.hostVerifier;
let hashAlgo;
if (HASHES.indexOf(cfg.hostHash) !== -1) {
// Default to old behavior of hashing on user's behalf
hashAlgo = cfg.hostHash;
}
hostVerifier = (key, verify) => {
if (hashAlgo)
key = createHash(hashAlgo).update(key).digest('hex');
const ret = hashCb(key, verify);
if (ret !== undefined)
verify(ret);
};
}
const sock = this._sock = (cfg.sock || new Socket());
let ready = false;
let sawHeader = false;
if (this._protocol)
this._protocol.cleanup();
const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {
debug(`Debug output from server: ${JSON.stringify(msg)}`);
});
let serverSigAlgs;
const proto = this._protocol = new Protocol({
ident: this.config.ident,
offer: (allOfferDefaults ? undefined : algorithms),
onWrite: (data) => {
if (isWritable(sock))
sock.write(data);
},
onError: (err) => {
if (err.level === 'handshake')
clearTimeout(this._readyTimeout);
if (!proto._destruct)
sock.removeAllListeners('data');
this.emit('error', err);
try {
sock.end();
} catch {}
},
onHeader: (header) => {
sawHeader = true;
this._remoteVer = header.versions.software;
if (header.greeting)
this.emit('greeting', header.greeting);
},
onHandshakeComplete: (negotiated) => {
this.emit('handshake', negotiated);
if (!ready) {
ready = true;
proto.service('ssh-userauth');
}
},
debug,
hostVerifier,
messageHandlers: {
DEBUG: DEBUG_HANDLER,
DISCONNECT: (p, reason, desc) => {
if (reason !== DISCONNECT_REASON.BY_APPLICATION) {
if (!desc) {
desc = DISCONNECT_REASON_BY_VALUE[reason];
if (desc === undefined)
desc = `Unexpected disconnection reason: ${reason}`;
}
const err = new Error(desc);
err.code = reason;
this.emit('error', err);
}
sock.end();
},
SERVICE_ACCEPT: (p, name) => {
if (name === 'ssh-userauth')
tryNextAuth();
},
EXT_INFO: (p, exts) => {
if (serverSigAlgs === undefined) {
for (const ext of exts) {
if (ext.name === 'server-sig-algs') {
serverSigAlgs = ext.algs;
return;
}
}
serverSigAlgs = null;
}
},
USERAUTH_BANNER: (p, msg) => {
this.emit('banner', msg);
},
USERAUTH_SUCCESS: (p) => {
// Start keepalive mechanism
resetKA();
clearTimeout(this._readyTimeout);
this.emit('ready');
},
USERAUTH_FAILURE: (p, authMethods, partialSuccess) => {
// For key-based authentication, check if we should retry the current
// key with a different algorithm first
if (curAuth.keyAlgos) {
const oldKeyAlgo = curAuth.keyAlgos[0][0];
if (debug)
debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`);
curAuth.keyAlgos.shift();
if (curAuth.keyAlgos.length) {
const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0];
switch (curAuth.type) {
case 'agent':
proto.authPK(
curAuth.username,
curAuth.agentCtx.currentKey(),
keyAlgo
);
return;
case 'publickey':
proto.authPK(curAuth.username, curAuth.key, keyAlgo);
return;
case 'hostbased':
proto.authHostbased(curAuth.username,
curAuth.key,
curAuth.localHostname,
curAuth.localUsername,
keyAlgo,
(buf, cb) => {
const signature = curAuth.key.sign(buf, hashAlgo);
if (signature instanceof Error) {
signature.message =
`Error while signing with key: ${signature.message}`;
signature.level = 'client-authentication';
this.emit('error', signature);
return tryNextAuth();
}
cb(signature);
});
return;
}
} else {
curAuth.keyAlgos = undefined;
}
}
if (curAuth.type === 'agent') {
const pos = curAuth.agentCtx.pos();
debug && debug(`Client: Agent key #${pos + 1} failed`);
return tryNextAgentKey();
}
debug && debug(`Client: ${curAuth.type} auth failed`);
curPartial = partialSuccess;
curAuthsLeft = authMethods;
tryNextAuth();
},
USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => {
if (curAuth.type === 'password') {
// TODO: support a `changePrompt()` on `curAuth` that defaults to
// emitting 'change password' as before
this.emit('change password', prompt, (newPassword) => {
proto.authPassword(
this.config.username,
this.config.password,
newPassword
);
});
}
},
USERAUTH_PK_OK: (p) => {
let keyAlgo;
let hashAlgo;
if (curAuth.keyAlgos)
[keyAlgo, hashAlgo] = curAuth.keyAlgos[0];
if (curAuth.type === 'agent') {
const key = curAuth.agentCtx.currentKey();
proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => {
const opts = { hash: hashAlgo };
curAuth.agentCtx.sign(key, buf, opts, (err, signed) => {
if (err) {
err.level = 'agent';
this.emit('error', err);
} else {
return cb(signed);
}
tryNextAgentKey();
});
});
} else if (curAuth.type === 'publickey') {
proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => {
const signature = curAuth.key.sign(buf, hashAlgo);
if (signature instanceof Error) {
signature.message =
`Error signing data with key: ${signature.message}`;
signature.level = 'client-authentication';
this.emit('error', signature);
return tryNextAuth();
}
cb(signature);
});
}
},
USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => {
if (curAuth.type === 'keyboard-interactive') {
const nprompts = (Array.isArray(prompts) ? prompts.length : 0);
if (nprompts === 0) {
debug && debug(
'Client: Sending automatic USERAUTH_INFO_RESPONSE'
);
proto.authInfoRes();
return;
}
// We sent a keyboard-interactive user authentication request and
// now the server is sending us the prompts we need to present to
// the user
curAuth.prompt(
name,
instructions,
'',
prompts,
(answers) => {
proto.authInfoRes(answers);
}
);
}
},
REQUEST_SUCCESS: (p, data) => {
if (callbacks.length)
callbacks.shift()(false, data);
},
REQUEST_FAILURE: (p) => {
if (callbacks.length)
callbacks.shift()(true);
},
GLOBAL_REQUEST: (p, name, wantReply, data) => {
switch (name) {
case 'hostkeys-00@openssh.com':
// Automatically verify keys before passing to end user
hostKeysProve(this, data, (err, keys) => {
if (err)
return;
this.emit('hostkeys', keys);
});
if (wantReply)
proto.requestSuccess();
break;
default:
// Auto-reject all other global requests, this can be especially
// useful if the server is sending us dummy keepalive global
// requests
if (wantReply)
proto.requestFailure();
}
},
CHANNEL_OPEN: (p, info) => {
// Handle incoming requests from server, typically a forwarded TCP or
// X11 connection
onCHANNEL_OPEN(this, info);
},
CHANNEL_OPEN_CONFIRMATION: (p, info) => {
const channel = this._chanMgr.get(info.recipient);
if (typeof channel !== 'function')
return;
const isSFTP = (channel.type === 'sftp');
const type = (isSFTP ? 'session' : channel.type);
const chanInfo = {
type,
incoming: {
id: info.recipient,
window: MAX_WINDOW,
packetSize: PACKET_SIZE,
state: 'open'
},
outgoing: {
id: info.sender,
window: info.window,
packetSize: info.packetSize,
state: 'open'
}
};
const instance = (
isSFTP
? new SFTP(this, chanInfo, { debug })
: new Channel(this, chanInfo)
);
this._chanMgr.update(info.recipient, instance);
channel(undefined, instance);
},
CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {
const channel = this._chanMgr.get(recipient);
if (typeof channel !== 'function')
return;
const info = { reason, description };
onChannelOpenFailure(this, recipient, info, channel);
},
CHANNEL_DATA: (p, recipient, data) => {
const channel = this._chanMgr.get(recipient);
if (typeof channel !== 'object' || channel === null)
return;
// The remote party should not be sending us data if there is no
// window space available ...
// TODO: raise error on data with not enough window?
if (channel.incoming.window === 0)
return;
channel.incoming.window -= data.length;
if (channel.push(data) === false) {
channel._waitChanDrain = true;
return;
}
if (channel.incoming.window <= WINDOW_THRESHOLD)
windowAdjust(channel);
},
CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {
if (type !== STDERR)
return;
const channel = this._chanMgr.get(recipient);
if (typeof channel !== 'object' || channel === null)
return;
// The remote party should not be sending us data if there is no
// window space available ...
// TODO: raise error on data with not enough window?
if (channel.incoming.window === 0)
return;
channel.incoming.window -= data.length;
if (!channel.stderr.push(data)) {
channel._waitChanDrain = true;
return;
}
if (channel.incoming.window <= WINDOW_THRESHOLD)
windowAdjust(channel);
},
CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {
const channel = this._chanMgr.get(recipient);
if (typeof channel !== 'object' || channel === null)
return;
// The other side is allowing us to send `amount` more bytes of data
channel.outgoing.window += amount;
if (channel._waitWindow) {
channel._waitWindow = false;
if (channel._chunk) {
channel._write(channel._chunk, null, channel._chunkcb);
} else if (channel._chunkcb) {
channel._chunkcb();
} else if (channel._chunkErr) {
channel.stderr._write(channel._chunkErr,
null,
channel._chunkcbErr);
} else if (channel._chunkcbErr) {
channel._chunkcbErr();
}
}
},
CHANNEL_SUCCESS: (p, recipient) => {
const channel = this._chanMgr.get(recipient);
if (typeof channel !== 'object' || channel === null)
return;
this._resetKA();
if (channel._callbacks.length)
channel._callbacks.shift()(false);
},
CHANNEL_FAILURE: (p, recipient) => {
const channel = this._chanMgr.get(recipient);
if (typeof channel !== 'object' || channel === null)
return;
this._resetKA();
if (channel._callbacks.length)
channel._callbacks.shift()(true);
},
CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {
const channel = this._chanMgr.get(recipient);
if (typeof channel !== 'object' || channel === null)
return;
const exit = channel._exit;
if (exit.code !== undefined)
return;
switch (type) {
case 'exit-status':
channel.emit('exit', exit.code = data);
return;
case 'exit-signal':
channel.emit('exit',
exit.code = null,
exit.signal = `SIG${data.signal}`,
exit.dump = data.coreDumped,
exit.desc = data.errorMessage);
return;
}
// Keepalive request? OpenSSH will send one as a channel request if
// there is a channel open
if (wantReply)
p.channelFailure(channel.outgoing.id);
},
CHANNEL_EOF: (p, recipient) => {
const channel = this._chanMgr.get(recipient);
if (typeof channel !== 'object' || channel === null)
return;
if (channel.incoming.state !== 'open')
return;
channel.incoming.state = 'eof';
if (channel.readable)
channel.push(null);
if (channel.stderr.readable)
channel.stderr.push(null);
},
CHANNEL_CLOSE: (p, recipient) => {
onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient));
},
},
});
sock.pause();
// TODO: check keepalive implementation
// Keepalive-related
const kainterval = this.config.keepaliveInterval;
const kacountmax = this.config.keepaliveCountMax;
let kacount = 0;
let katimer;
const sendKA = () => {
if (++kacount > kacountmax) {
clearInterval(katimer);
if (sock.readable) {
const err = new Error('Keepalive timeout');
err.level = 'client-timeout';
this.emit('error', err);
sock.destroy();
}
return;
}
if (isWritable(sock)) {
// Append dummy callback to keep correct callback order
callbacks.push(resetKA);
proto.ping();
} else {
clearInterval(katimer);
}
};
function resetKA() {
if (kainterval > 0) {
kacount = 0;
clearInterval(katimer);
if (isWritable(sock))
katimer = setInterval(sendKA, kainterval);
}
}
this._resetKA = resetKA;
const onDone = (() => {
let called = false;
return () => {
if (called)
return;
called = true;
if (wasConnected && !sawHeader) {
const err =
makeError('Connection lost before handshake', 'protocol', true);
this.emit('error', err);
}
};
})();
const onConnect = (() => {
let called = false;
return () => {
if (called)
return;
called = true;
wasConnected = true;
debug && debug('Socket connected');
this.emit('connect');
cryptoInit.then(() => {
proto.start();
sock.on('data', (data) => {
try {
proto.parse(data, 0, data.length);
} catch (ex) {
this.emit('error', ex);
try {
if (isWritable(sock))
sock.end();
} catch {}
}
});
// Drain stderr if we are connection hopping using an exec stream
if (sock.stderr && typeof sock.stderr.resume === 'function')
sock.stderr.resume();
sock.resume();
}).catch((err) => {
this.emit('error', err);
try {
if (isWritable(sock))
sock.end();
} catch {}
});
};
})();
let wasConnected = false;
sock.on('connect', onConnect)
.on('timeout', () => {
this.emit('timeout');
}).on('error', (err) => {
debug && debug(`Socket error: ${err.message}`);
clearTimeout(this._readyTimeout);
err.level = 'client-socket';
this.emit('error', err);
}).on('end', () => {
debug && debug('Socket ended');
onDone();
proto.cleanup();
clearTimeout(this._readyTimeout);
clearInterval(katimer);
this.emit('end');
}).on('close', () => {
debug && debug('Socket closed');
onDone();
proto.cleanup();
clearTimeout(this._readyTimeout);
clearInterval(katimer);
this.emit('close');
// Notify outstanding channel requests of disconnection ...
const callbacks_ = callbacks;
callbacks = this._callbacks = [];
const err = new Error('No response from server');
for (let i = 0; i < callbacks_.length; ++i)
callbacks_[i](err);
// Simulate error for any channels waiting to be opened
this._chanMgr.cleanup(err);
});
// Begin authentication handling ===========================================
let curAuth;
let curPartial = null;
let curAuthsLeft = null;
const authsAllowed = ['none'];
if (this.config.password !== undefined)
authsAllowed.push('password');
if (privateKey !== undefined)
authsAllowed.push('publickey');
if (this._agent !== undefined)
authsAllowed.push('agent');
if (this.config.tryKeyboard)
authsAllowed.push('keyboard-interactive');
if (privateKey !== undefined
&& this.config.localHostname !== undefined
&& this.config.localUsername !== undefined) {
authsAllowed.push('hostbased');
}
if (Array.isArray(authHandler))
authHandler = makeSimpleAuthHandler(authHandler);
else if (typeof authHandler !== 'function')
authHandler = makeSimpleAuthHandler(authsAllowed);
let hasSentAuth = false;
const doNextAuth = (nextAuth) => {
if (hasSentAuth)
return;
hasSentAuth = true;
if (nextAuth === false) {
const err = new Error('All configured authentication methods failed');
err.level = 'client-authentication';
this.emit('error', err);
this.end();
return;
}
if (typeof nextAuth === 'string') {
// Remain backwards compatible with original `authHandler()` usage,
// which only supported passing names of next method to try using data
// from the `connect()` config object
const type = nextAuth;
if (authsAllowed.indexOf(type) === -1)
return skipAuth(`Authentication method not allowed: ${type}`);
const username = this.config.username;
switch (type) {
case 'password':
nextAuth = { type, username, password: this.config.password };
break;
case 'publickey':
nextAuth = { type, username, key: privateKey };
break;
case 'hostbased':
nextAuth = {
type,
username,
key: privateKey,
localHostname: this.config.localHostname,
localUsername: this.config.localUsername,
};
break;
case 'agent':
nextAuth = {
type,
username,
agentCtx: new AgentContext(this._agent),
};
break;
case 'keyboard-interactive':
nextAuth = {
type,
username,
prompt: (...args) => this.emit('keyboard-interactive', ...args),
};
break;
case 'none':
nextAuth = { type, username };
break;
default:
return skipAuth(
`Skipping unsupported authentication method: ${nextAuth}`
);
}
} else if (typeof nextAuth !== 'object' || nextAuth === null) {
return skipAuth(
`Skipping invalid authentication attempt: ${nextAuth}`
);
} else {
const username = nextAuth.username;
if (typeof username !== 'string') {
return skipAuth(
`Skipping invalid authentication attempt: ${nextAuth}`
);
}
const type = nextAuth.type;
switch (type) {
case 'password': {
const { password } = nextAuth;
if (typeof password !== 'string' && !Buffer.isBuffer(password))
return skipAuth('Skipping invalid password auth attempt');
nextAuth = { type, username, password };
break;
}
case 'publickey': {
const key = parseKey(nextAuth.key, nextAuth.passphrase);
if (key instanceof Error)
return skipAuth('Skipping invalid key auth attempt');
if (!key.isPrivateKey())
return skipAuth('Skipping non-private key');
nextAuth = { type, username, key };
break;
}
case 'hostbased': {
const { localHostname, localUsername } = nextAuth;
const key = parseKey(nextAuth.key, nextAuth.passphrase);
if (key instanceof Error
|| typeof localHostname !== 'string'
|| typeof localUsername !== 'string') {
return skipAuth('Skipping invalid hostbased auth attempt');
}
if (!key.isPrivateKey())
return skipAuth('Skipping non-private key');
nextAuth = { type, username, key, localHostname, localUsername };
break;
}
case 'agent': {
let agent = nextAuth.agent;
if (typeof agent === 'string' && agent.length) {
agent = createAgent(agent);
} else if (!isAgent(agent)) {
return skipAuth(
`Skipping invalid agent: ${nextAuth.agent}`
);
}
nextAuth = { type, username, agentCtx: new AgentContext(agent) };
break;
}
case 'keyboard-interactive': {
const { prompt } = nextAuth;
if (typeof prompt !== 'function') {
return skipAuth(
'Skipping invalid keyboard-interactive auth attempt'
);
}
nextAuth = { type, username, prompt };
break;
}
case 'none':
nextAuth = { type, username };
break;
default:
return skipAuth(
`Skipping unsupported authentication method: ${nextAuth}`
);
}
}
curAuth = nextAuth;
// Begin authentication method's process
try {
const username = curAuth.username;
switch (curAuth.type) {
case 'password':
proto.authPassword(username, curAuth.password);
break;
case 'publickey': {