client.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013
  1. // TODO:
  2. // * add `.connected` or similar property to allow immediate connection
  3. // status checking
  4. // * add/improve debug output during user authentication phase
  5. 'use strict';
  6. const {
  7. createHash,
  8. getHashes,
  9. randomFillSync,
  10. } = require('crypto');
  11. const { Socket } = require('net');
  12. const { lookup: dnsLookup } = require('dns');
  13. const EventEmitter = require('events');
  14. const HASHES = getHashes();
  15. const {
  16. COMPAT,
  17. CHANNEL_EXTENDED_DATATYPE: { STDERR },
  18. CHANNEL_OPEN_FAILURE,
  19. DEFAULT_CIPHER,
  20. DEFAULT_COMPRESSION,
  21. DEFAULT_KEX,
  22. DEFAULT_MAC,
  23. DEFAULT_SERVER_HOST_KEY,
  24. DISCONNECT_REASON,
  25. DISCONNECT_REASON_BY_VALUE,
  26. SUPPORTED_CIPHER,
  27. SUPPORTED_COMPRESSION,
  28. SUPPORTED_KEX,
  29. SUPPORTED_MAC,
  30. SUPPORTED_SERVER_HOST_KEY,
  31. } = require('./protocol/constants.js');
  32. const { init: cryptoInit } = require('./protocol/crypto.js');
  33. const Protocol = require('./protocol/Protocol.js');
  34. const { parseKey } = require('./protocol/keyParser.js');
  35. const { SFTP } = require('./protocol/SFTP.js');
  36. const {
  37. bufferCopy,
  38. makeBufferParser,
  39. makeError,
  40. readUInt32BE,
  41. sigSSHToASN1,
  42. writeUInt32BE,
  43. } = require('./protocol/utils.js');
  44. const { AgentContext, createAgent, isAgent } = require('./agent.js');
  45. const {
  46. Channel,
  47. MAX_WINDOW,
  48. PACKET_SIZE,
  49. windowAdjust,
  50. WINDOW_THRESHOLD,
  51. } = require('./Channel.js');
  52. const {
  53. ChannelManager,
  54. generateAlgorithmList,
  55. isWritable,
  56. onChannelOpenFailure,
  57. onCHANNEL_CLOSE,
  58. } = require('./utils.js');
  59. const bufferParser = makeBufferParser();
  60. const sigParser = makeBufferParser();
  61. const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/;
  62. const noop = (err) => {};
  63. class Client extends EventEmitter {
  64. constructor() {
  65. super();
  66. this.config = {
  67. host: undefined,
  68. port: undefined,
  69. localAddress: undefined,
  70. localPort: undefined,
  71. forceIPv4: undefined,
  72. forceIPv6: undefined,
  73. keepaliveCountMax: undefined,
  74. keepaliveInterval: undefined,
  75. readyTimeout: undefined,
  76. ident: undefined,
  77. username: undefined,
  78. password: undefined,
  79. privateKey: undefined,
  80. tryKeyboard: undefined,
  81. agent: undefined,
  82. allowAgentFwd: undefined,
  83. authHandler: undefined,
  84. hostHashAlgo: undefined,
  85. hostHashCb: undefined,
  86. strictVendor: undefined,
  87. debug: undefined
  88. };
  89. this._agent = undefined;
  90. this._readyTimeout = undefined;
  91. this._chanMgr = undefined;
  92. this._callbacks = undefined;
  93. this._forwarding = undefined;
  94. this._forwardingUnix = undefined;
  95. this._acceptX11 = undefined;
  96. this._agentFwdEnabled = undefined;
  97. this._remoteVer = undefined;
  98. this._protocol = undefined;
  99. this._sock = undefined;
  100. this._resetKA = undefined;
  101. }
  102. connect(cfg) {
  103. if (this._sock && isWritable(this._sock)) {
  104. this.once('close', () => {
  105. this.connect(cfg);
  106. });
  107. this.end();
  108. return this;
  109. }
  110. this.config.host = cfg.hostname || cfg.host || 'localhost';
  111. this.config.port = cfg.port || 22;
  112. this.config.localAddress = (typeof cfg.localAddress === 'string'
  113. ? cfg.localAddress
  114. : undefined);
  115. this.config.localPort = (typeof cfg.localPort === 'string'
  116. || typeof cfg.localPort === 'number'
  117. ? cfg.localPort
  118. : undefined);
  119. this.config.forceIPv4 = cfg.forceIPv4 || false;
  120. this.config.forceIPv6 = cfg.forceIPv6 || false;
  121. this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number'
  122. && cfg.keepaliveCountMax >= 0
  123. ? cfg.keepaliveCountMax
  124. : 3);
  125. this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number'
  126. && cfg.keepaliveInterval > 0
  127. ? cfg.keepaliveInterval
  128. : 0);
  129. this.config.readyTimeout = (typeof cfg.readyTimeout === 'number'
  130. && cfg.readyTimeout >= 0
  131. ? cfg.readyTimeout
  132. : 20000);
  133. this.config.ident = (typeof cfg.ident === 'string'
  134. || Buffer.isBuffer(cfg.ident)
  135. ? cfg.ident
  136. : undefined);
  137. const algorithms = {
  138. kex: undefined,
  139. serverHostKey: undefined,
  140. cs: {
  141. cipher: undefined,
  142. mac: undefined,
  143. compress: undefined,
  144. lang: [],
  145. },
  146. sc: undefined,
  147. };
  148. let allOfferDefaults = true;
  149. if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) {
  150. algorithms.kex = generateAlgorithmList(cfg.algorithms.kex,
  151. DEFAULT_KEX,
  152. SUPPORTED_KEX);
  153. if (algorithms.kex !== DEFAULT_KEX)
  154. allOfferDefaults = false;
  155. algorithms.serverHostKey =
  156. generateAlgorithmList(cfg.algorithms.serverHostKey,
  157. DEFAULT_SERVER_HOST_KEY,
  158. SUPPORTED_SERVER_HOST_KEY);
  159. if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY)
  160. allOfferDefaults = false;
  161. algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher,
  162. DEFAULT_CIPHER,
  163. SUPPORTED_CIPHER);
  164. if (algorithms.cs.cipher !== DEFAULT_CIPHER)
  165. allOfferDefaults = false;
  166. algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac,
  167. DEFAULT_MAC,
  168. SUPPORTED_MAC);
  169. if (algorithms.cs.mac !== DEFAULT_MAC)
  170. allOfferDefaults = false;
  171. algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress,
  172. DEFAULT_COMPRESSION,
  173. SUPPORTED_COMPRESSION);
  174. if (algorithms.cs.compress !== DEFAULT_COMPRESSION)
  175. allOfferDefaults = false;
  176. if (!allOfferDefaults)
  177. algorithms.sc = algorithms.cs;
  178. }
  179. if (typeof cfg.username === 'string')
  180. this.config.username = cfg.username;
  181. else if (typeof cfg.user === 'string')
  182. this.config.username = cfg.user;
  183. else
  184. throw new Error('Invalid username');
  185. this.config.password = (typeof cfg.password === 'string'
  186. ? cfg.password
  187. : undefined);
  188. this.config.privateKey = (typeof cfg.privateKey === 'string'
  189. || Buffer.isBuffer(cfg.privateKey)
  190. ? cfg.privateKey
  191. : undefined);
  192. this.config.localHostname = (typeof cfg.localHostname === 'string'
  193. ? cfg.localHostname
  194. : undefined);
  195. this.config.localUsername = (typeof cfg.localUsername === 'string'
  196. ? cfg.localUsername
  197. : undefined);
  198. this.config.tryKeyboard = (cfg.tryKeyboard === true);
  199. if (typeof cfg.agent === 'string' && cfg.agent.length)
  200. this.config.agent = createAgent(cfg.agent);
  201. else if (isAgent(cfg.agent))
  202. this.config.agent = cfg.agent;
  203. else
  204. this.config.agent = undefined;
  205. this.config.allowAgentFwd = (cfg.agentForward === true
  206. && this.config.agent !== undefined);
  207. let authHandler = this.config.authHandler = (
  208. typeof cfg.authHandler === 'function'
  209. || Array.isArray(cfg.authHandler)
  210. ? cfg.authHandler
  211. : undefined
  212. );
  213. this.config.strictVendor = (typeof cfg.strictVendor === 'boolean'
  214. ? cfg.strictVendor
  215. : true);
  216. const debug = this.config.debug = (typeof cfg.debug === 'function'
  217. ? cfg.debug
  218. : undefined);
  219. if (cfg.agentForward === true && !this.config.allowAgentFwd) {
  220. throw new Error(
  221. 'You must set a valid agent path to allow agent forwarding'
  222. );
  223. }
  224. let callbacks = this._callbacks = [];
  225. this._chanMgr = new ChannelManager(this);
  226. this._forwarding = {};
  227. this._forwardingUnix = {};
  228. this._acceptX11 = 0;
  229. this._agentFwdEnabled = false;
  230. this._agent = (this.config.agent ? this.config.agent : undefined);
  231. this._remoteVer = undefined;
  232. let privateKey;
  233. if (this.config.privateKey) {
  234. privateKey = parseKey(this.config.privateKey, cfg.passphrase);
  235. if (privateKey instanceof Error)
  236. throw new Error(`Cannot parse privateKey: ${privateKey.message}`);
  237. if (Array.isArray(privateKey)) {
  238. // OpenSSH's newer format only stores 1 key for now
  239. privateKey = privateKey[0];
  240. }
  241. if (privateKey.getPrivatePEM() === null) {
  242. throw new Error(
  243. 'privateKey value does not contain a (valid) private key'
  244. );
  245. }
  246. }
  247. let hostVerifier;
  248. if (typeof cfg.hostVerifier === 'function') {
  249. const hashCb = cfg.hostVerifier;
  250. let hasher;
  251. if (HASHES.indexOf(cfg.hostHash) !== -1) {
  252. // Default to old behavior of hashing on user's behalf
  253. hasher = createHash(cfg.hostHash);
  254. }
  255. hostVerifier = (key, verify) => {
  256. if (hasher) {
  257. hasher.update(key);
  258. key = hasher.digest('hex');
  259. }
  260. const ret = hashCb(key, verify);
  261. if (ret !== undefined)
  262. verify(ret);
  263. };
  264. }
  265. const sock = this._sock = (cfg.sock || new Socket());
  266. let ready = false;
  267. let sawHeader = false;
  268. if (this._protocol)
  269. this._protocol.cleanup();
  270. const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => {
  271. debug(`Debug output from server: ${JSON.stringify(msg)}`);
  272. });
  273. const proto = this._protocol = new Protocol({
  274. ident: this.config.ident,
  275. offer: (allOfferDefaults ? undefined : algorithms),
  276. onWrite: (data) => {
  277. if (isWritable(sock))
  278. sock.write(data);
  279. },
  280. onError: (err) => {
  281. if (err.level === 'handshake')
  282. clearTimeout(this._readyTimeout);
  283. if (!proto._destruct)
  284. sock.removeAllListeners('data');
  285. this.emit('error', err);
  286. try {
  287. sock.end();
  288. } catch {}
  289. },
  290. onHeader: (header) => {
  291. sawHeader = true;
  292. this._remoteVer = header.versions.software;
  293. if (header.greeting)
  294. this.emit('greeting', header.greeting);
  295. },
  296. onHandshakeComplete: (negotiated) => {
  297. this.emit('handshake', negotiated);
  298. if (!ready) {
  299. ready = true;
  300. proto.service('ssh-userauth');
  301. }
  302. },
  303. debug,
  304. hostVerifier,
  305. messageHandlers: {
  306. DEBUG: DEBUG_HANDLER,
  307. DISCONNECT: (p, reason, desc) => {
  308. if (reason !== DISCONNECT_REASON.BY_APPLICATION) {
  309. if (!desc) {
  310. desc = DISCONNECT_REASON_BY_VALUE[reason];
  311. if (desc === undefined)
  312. desc = `Unexpected disconnection reason: ${reason}`;
  313. }
  314. const err = new Error(desc);
  315. err.code = reason;
  316. this.emit('error', err);
  317. }
  318. sock.end();
  319. },
  320. SERVICE_ACCEPT: (p, name) => {
  321. if (name === 'ssh-userauth')
  322. tryNextAuth();
  323. },
  324. USERAUTH_BANNER: (p, msg) => {
  325. this.emit('banner', msg);
  326. },
  327. USERAUTH_SUCCESS: (p) => {
  328. // Start keepalive mechanism
  329. resetKA();
  330. clearTimeout(this._readyTimeout);
  331. this.emit('ready');
  332. },
  333. USERAUTH_FAILURE: (p, authMethods, partialSuccess) => {
  334. if (curAuth.type === 'agent') {
  335. const pos = curAuth.agentCtx.pos();
  336. debug && debug(`Client: Agent key #${pos + 1} failed`);
  337. return tryNextAgentKey();
  338. }
  339. debug && debug(`Client: ${curAuth.type} auth failed`);
  340. curPartial = partialSuccess;
  341. curAuthsLeft = authMethods;
  342. tryNextAuth();
  343. },
  344. USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => {
  345. if (curAuth.type === 'password') {
  346. // TODO: support a `changePrompt()` on `curAuth` that defaults to
  347. // emitting 'change password' as before
  348. this.emit('change password', prompt, (newPassword) => {
  349. proto.authPassword(
  350. this.config.username,
  351. this.config.password,
  352. newPassword
  353. );
  354. });
  355. }
  356. },
  357. USERAUTH_PK_OK: (p) => {
  358. if (curAuth.type === 'agent') {
  359. const key = curAuth.agentCtx.currentKey();
  360. proto.authPK(curAuth.username, key, (buf, cb) => {
  361. curAuth.agentCtx.sign(key, buf, {}, (err, signed) => {
  362. if (err) {
  363. err.level = 'agent';
  364. this.emit('error', err);
  365. } else {
  366. return cb(signed);
  367. }
  368. tryNextAgentKey();
  369. });
  370. });
  371. } else if (curAuth.type === 'publickey') {
  372. proto.authPK(curAuth.username, curAuth.key, (buf, cb) => {
  373. const signature = curAuth.key.sign(buf);
  374. if (signature instanceof Error) {
  375. signature.message =
  376. `Error signing data with key: ${signature.message}`;
  377. signature.level = 'client-authentication';
  378. this.emit('error', signature);
  379. return tryNextAuth();
  380. }
  381. cb(signature);
  382. });
  383. }
  384. },
  385. USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => {
  386. if (curAuth.type === 'keyboard-interactive') {
  387. const nprompts = (Array.isArray(prompts) ? prompts.length : 0);
  388. if (nprompts === 0) {
  389. debug && debug(
  390. 'Client: Sending automatic USERAUTH_INFO_RESPONSE'
  391. );
  392. proto.authInfoRes();
  393. return;
  394. }
  395. // We sent a keyboard-interactive user authentication request and
  396. // now the server is sending us the prompts we need to present to
  397. // the user
  398. curAuth.prompt(
  399. name,
  400. instructions,
  401. '',
  402. prompts,
  403. (answers) => {
  404. proto.authInfoRes(answers);
  405. }
  406. );
  407. }
  408. },
  409. REQUEST_SUCCESS: (p, data) => {
  410. if (callbacks.length)
  411. callbacks.shift()(false, data);
  412. },
  413. REQUEST_FAILURE: (p) => {
  414. if (callbacks.length)
  415. callbacks.shift()(true);
  416. },
  417. GLOBAL_REQUEST: (p, name, wantReply, data) => {
  418. switch (name) {
  419. case 'hostkeys-00@openssh.com':
  420. // Automatically verify keys before passing to end user
  421. hostKeysProve(this, data, (err, keys) => {
  422. if (err)
  423. return;
  424. this.emit('hostkeys', keys);
  425. });
  426. if (wantReply)
  427. proto.requestSuccess();
  428. break;
  429. default:
  430. // Auto-reject all other global requests, this can be especially
  431. // useful if the server is sending us dummy keepalive global
  432. // requests
  433. if (wantReply)
  434. proto.requestFailure();
  435. }
  436. },
  437. CHANNEL_OPEN: (p, info) => {
  438. // Handle incoming requests from server, typically a forwarded TCP or
  439. // X11 connection
  440. onCHANNEL_OPEN(this, info);
  441. },
  442. CHANNEL_OPEN_CONFIRMATION: (p, info) => {
  443. const channel = this._chanMgr.get(info.recipient);
  444. if (typeof channel !== 'function')
  445. return;
  446. const isSFTP = (channel.type === 'sftp');
  447. const type = (isSFTP ? 'session' : channel.type);
  448. const chanInfo = {
  449. type,
  450. incoming: {
  451. id: info.recipient,
  452. window: MAX_WINDOW,
  453. packetSize: PACKET_SIZE,
  454. state: 'open'
  455. },
  456. outgoing: {
  457. id: info.sender,
  458. window: info.window,
  459. packetSize: info.packetSize,
  460. state: 'open'
  461. }
  462. };
  463. const instance = (
  464. isSFTP
  465. ? new SFTP(this, chanInfo, { debug })
  466. : new Channel(this, chanInfo)
  467. );
  468. this._chanMgr.update(info.recipient, instance);
  469. channel(undefined, instance);
  470. },
  471. CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => {
  472. const channel = this._chanMgr.get(recipient);
  473. if (typeof channel !== 'function')
  474. return;
  475. const info = { reason, description };
  476. onChannelOpenFailure(this, recipient, info, channel);
  477. },
  478. CHANNEL_DATA: (p, recipient, data) => {
  479. const channel = this._chanMgr.get(recipient);
  480. if (typeof channel !== 'object' || channel === null)
  481. return;
  482. // The remote party should not be sending us data if there is no
  483. // window space available ...
  484. // TODO: raise error on data with not enough window?
  485. if (channel.incoming.window === 0)
  486. return;
  487. channel.incoming.window -= data.length;
  488. if (channel.push(data) === false) {
  489. channel._waitChanDrain = true;
  490. return;
  491. }
  492. if (channel.incoming.window <= WINDOW_THRESHOLD)
  493. windowAdjust(channel);
  494. },
  495. CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => {
  496. if (type !== STDERR)
  497. return;
  498. const channel = this._chanMgr.get(recipient);
  499. if (typeof channel !== 'object' || channel === null)
  500. return;
  501. // The remote party should not be sending us data if there is no
  502. // window space available ...
  503. // TODO: raise error on data with not enough window?
  504. if (channel.incoming.window === 0)
  505. return;
  506. channel.incoming.window -= data.length;
  507. if (!channel.stderr.push(data)) {
  508. channel._waitChanDrain = true;
  509. return;
  510. }
  511. if (channel.incoming.window <= WINDOW_THRESHOLD)
  512. windowAdjust(channel);
  513. },
  514. CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => {
  515. const channel = this._chanMgr.get(recipient);
  516. if (typeof channel !== 'object' || channel === null)
  517. return;
  518. // The other side is allowing us to send `amount` more bytes of data
  519. channel.outgoing.window += amount;
  520. if (channel._waitWindow) {
  521. channel._waitWindow = false;
  522. if (channel._chunk) {
  523. channel._write(channel._chunk, null, channel._chunkcb);
  524. } else if (channel._chunkcb) {
  525. channel._chunkcb();
  526. } else if (channel._chunkErr) {
  527. channel.stderr._write(channel._chunkErr,
  528. null,
  529. channel._chunkcbErr);
  530. } else if (channel._chunkcbErr) {
  531. channel._chunkcbErr();
  532. }
  533. }
  534. },
  535. CHANNEL_SUCCESS: (p, recipient) => {
  536. const channel = this._chanMgr.get(recipient);
  537. if (typeof channel !== 'object' || channel === null)
  538. return;
  539. this._resetKA();
  540. if (channel._callbacks.length)
  541. channel._callbacks.shift()(false);
  542. },
  543. CHANNEL_FAILURE: (p, recipient) => {
  544. const channel = this._chanMgr.get(recipient);
  545. if (typeof channel !== 'object' || channel === null)
  546. return;
  547. this._resetKA();
  548. if (channel._callbacks.length)
  549. channel._callbacks.shift()(true);
  550. },
  551. CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => {
  552. const channel = this._chanMgr.get(recipient);
  553. if (typeof channel !== 'object' || channel === null)
  554. return;
  555. const exit = channel._exit;
  556. if (exit.code !== undefined)
  557. return;
  558. switch (type) {
  559. case 'exit-status':
  560. channel.emit('exit', exit.code = data);
  561. return;
  562. case 'exit-signal':
  563. channel.emit('exit',
  564. exit.code = null,
  565. exit.signal = `SIG${data.signal}`,
  566. exit.dump = data.coreDumped,
  567. exit.desc = data.errorMessage);
  568. return;
  569. }
  570. // Keepalive request? OpenSSH will send one as a channel request if
  571. // there is a channel open
  572. if (wantReply)
  573. p.channelFailure(channel.outgoing.id);
  574. },
  575. CHANNEL_EOF: (p, recipient) => {
  576. const channel = this._chanMgr.get(recipient);
  577. if (typeof channel !== 'object' || channel === null)
  578. return;
  579. if (channel.incoming.state !== 'open')
  580. return;
  581. channel.incoming.state = 'eof';
  582. if (channel.readable)
  583. channel.push(null);
  584. if (channel.stderr.readable)
  585. channel.stderr.push(null);
  586. },
  587. CHANNEL_CLOSE: (p, recipient) => {
  588. onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient));
  589. },
  590. },
  591. });
  592. sock.pause();
  593. // TODO: check keepalive implementation
  594. // Keepalive-related
  595. const kainterval = this.config.keepaliveInterval;
  596. const kacountmax = this.config.keepaliveCountMax;
  597. let kacount = 0;
  598. let katimer;
  599. const sendKA = () => {
  600. if (++kacount > kacountmax) {
  601. clearInterval(katimer);
  602. if (sock.readable) {
  603. const err = new Error('Keepalive timeout');
  604. err.level = 'client-timeout';
  605. this.emit('error', err);
  606. sock.destroy();
  607. }
  608. return;
  609. }
  610. if (isWritable(sock)) {
  611. // Append dummy callback to keep correct callback order
  612. callbacks.push(resetKA);
  613. proto.ping();
  614. } else {
  615. clearInterval(katimer);
  616. }
  617. };
  618. function resetKA() {
  619. if (kainterval > 0) {
  620. kacount = 0;
  621. clearInterval(katimer);
  622. if (isWritable(sock))
  623. katimer = setInterval(sendKA, kainterval);
  624. }
  625. }
  626. this._resetKA = resetKA;
  627. const onDone = (() => {
  628. let called = false;
  629. return () => {
  630. if (called)
  631. return;
  632. called = true;
  633. if (wasConnected && !sawHeader) {
  634. const err =
  635. makeError('Connection lost before handshake', 'protocol', true);
  636. this.emit('error', err);
  637. }
  638. };
  639. })();
  640. const onConnect = (() => {
  641. let called = false;
  642. return () => {
  643. if (called)
  644. return;
  645. called = true;
  646. wasConnected = true;
  647. debug && debug('Socket connected');
  648. this.emit('connect');
  649. cryptoInit.then(() => {
  650. sock.on('data', (data) => {
  651. try {
  652. proto.parse(data, 0, data.length);
  653. } catch (ex) {
  654. this.emit('error', ex);
  655. try {
  656. if (isWritable(sock))
  657. sock.end();
  658. } catch {}
  659. }
  660. });
  661. // Drain stderr if we are connection hopping using an exec stream
  662. if (sock.stderr && typeof sock.stderr.resume === 'function')
  663. sock.stderr.resume();
  664. sock.resume();
  665. }).catch((err) => {
  666. this.emit('error', err);
  667. try {
  668. if (isWritable(sock))
  669. sock.end();
  670. } catch {}
  671. });
  672. };
  673. })();
  674. let wasConnected = false;
  675. sock.on('connect', onConnect)
  676. .on('timeout', () => {
  677. this.emit('timeout');
  678. }).on('error', (err) => {
  679. debug && debug(`Socket error: ${err.message}`);
  680. clearTimeout(this._readyTimeout);
  681. err.level = 'client-socket';
  682. this.emit('error', err);
  683. }).on('end', () => {
  684. debug && debug('Socket ended');
  685. onDone();
  686. proto.cleanup();
  687. clearTimeout(this._readyTimeout);
  688. clearInterval(katimer);
  689. this.emit('end');
  690. }).on('close', () => {
  691. debug && debug('Socket closed');
  692. onDone();
  693. proto.cleanup();
  694. clearTimeout(this._readyTimeout);
  695. clearInterval(katimer);
  696. this.emit('close');
  697. // Notify outstanding channel requests of disconnection ...
  698. const callbacks_ = callbacks;
  699. callbacks = this._callbacks = [];
  700. const err = new Error('No response from server');
  701. for (let i = 0; i < callbacks_.length; ++i)
  702. callbacks_[i](err);
  703. // Simulate error for any channels waiting to be opened
  704. this._chanMgr.cleanup(err);
  705. });
  706. // Begin authentication handling ===========================================
  707. let curAuth;
  708. let curPartial = null;
  709. let curAuthsLeft = null;
  710. const authsAllowed = ['none'];
  711. if (this.config.password !== undefined)
  712. authsAllowed.push('password');
  713. if (privateKey !== undefined)
  714. authsAllowed.push('publickey');
  715. if (this._agent !== undefined)
  716. authsAllowed.push('agent');
  717. if (this.config.tryKeyboard)
  718. authsAllowed.push('keyboard-interactive');
  719. if (privateKey !== undefined
  720. && this.config.localHostname !== undefined
  721. && this.config.localUsername !== undefined) {
  722. authsAllowed.push('hostbased');
  723. }
  724. if (Array.isArray(authHandler))
  725. authHandler = makeSimpleAuthHandler(authHandler);
  726. else if (typeof authHandler !== 'function')
  727. authHandler = makeSimpleAuthHandler(authsAllowed);
  728. let hasSentAuth = false;
  729. const doNextAuth = (nextAuth) => {
  730. if (hasSentAuth)
  731. return;
  732. hasSentAuth = true;
  733. if (nextAuth === false) {
  734. const err = new Error('All configured authentication methods failed');
  735. err.level = 'client-authentication';
  736. this.emit('error', err);
  737. this.end();
  738. return;
  739. }
  740. if (typeof nextAuth === 'string') {
  741. // Remain backwards compatible with original `authHandler()` usage,
  742. // which only supported passing names of next method to try using data
  743. // from the `connect()` config object
  744. const type = nextAuth;
  745. if (authsAllowed.indexOf(type) === -1)
  746. return skipAuth(`Authentication method not allowed: ${type}`);
  747. const username = this.config.username;
  748. switch (type) {
  749. case 'password':
  750. nextAuth = { type, username, password: this.config.password };
  751. break;
  752. case 'publickey':
  753. nextAuth = { type, username, key: privateKey };
  754. break;
  755. case 'hostbased':
  756. nextAuth = {
  757. type,
  758. username,
  759. key: privateKey,
  760. localHostname: this.config.localHostname,
  761. localUsername: this.config.localUsername,
  762. };
  763. break;
  764. case 'agent':
  765. nextAuth = {
  766. type,
  767. username,
  768. agentCtx: new AgentContext(this._agent),
  769. };
  770. break;
  771. case 'keyboard-interactive':
  772. nextAuth = {
  773. type,
  774. username,
  775. prompt: (...args) => this.emit('keyboard-interactive', ...args),
  776. };
  777. break;
  778. case 'none':
  779. nextAuth = { type, username };
  780. break;
  781. default:
  782. return skipAuth(
  783. `Skipping unsupported authentication method: ${nextAuth}`
  784. );
  785. }
  786. } else if (typeof nextAuth !== 'object' || nextAuth === null) {
  787. return skipAuth(
  788. `Skipping invalid authentication attempt: ${nextAuth}`
  789. );
  790. } else {
  791. const username = nextAuth.username;
  792. if (typeof username !== 'string') {
  793. return skipAuth(
  794. `Skipping invalid authentication attempt: ${nextAuth}`
  795. );
  796. }
  797. const type = nextAuth.type;
  798. switch (type) {
  799. case 'password': {
  800. const { password } = nextAuth;
  801. if (typeof password !== 'string' && !Buffer.isBuffer(password))
  802. return skipAuth('Skipping invalid password auth attempt');
  803. nextAuth = { type, username, password };
  804. break;
  805. }
  806. case 'publickey': {
  807. const key = parseKey(nextAuth.key, nextAuth.passphrase);
  808. if (key instanceof Error)
  809. return skipAuth('Skipping invalid key auth attempt');
  810. if (!key.isPrivateKey())
  811. return skipAuth('Skipping non-private key');
  812. nextAuth = { type, username, key };
  813. break;
  814. }
  815. case 'hostbased': {
  816. const { localHostname, localUsername } = nextAuth;
  817. const key = parseKey(nextAuth.key, nextAuth.passphrase);
  818. if (key instanceof Error
  819. || typeof localHostname !== 'string'
  820. || typeof localUsername !== 'string') {
  821. return skipAuth('Skipping invalid hostbased auth attempt');
  822. }
  823. if (!key.isPrivateKey())
  824. return skipAuth('Skipping non-private key');
  825. nextAuth = { type, username, key, localHostname, localUsername };
  826. break;
  827. }
  828. case 'agent': {
  829. let agent = nextAuth.agent;
  830. if (typeof agent === 'string' && agent.length) {
  831. agent = createAgent(agent);
  832. } else if (!isAgent(agent)) {
  833. return skipAuth(
  834. `Skipping invalid agent: ${nextAuth.agent}`
  835. );
  836. }
  837. nextAuth = { type, username, agentCtx: new AgentContext(agent) };
  838. break;
  839. }
  840. case 'keyboard-interactive': {
  841. const { prompt } = nextAuth;
  842. if (typeof prompt !== 'function') {
  843. return skipAuth(
  844. 'Skipping invalid keyboard-interactive auth attempt'
  845. );
  846. }
  847. nextAuth = { type, username, prompt };
  848. break;
  849. }
  850. case 'none':
  851. nextAuth = { type, username };
  852. break;
  853. default:
  854. return skipAuth(
  855. `Skipping unsupported authentication method: ${nextAuth}`
  856. );
  857. }
  858. }
  859. curAuth = nextAuth;
  860. // Begin authentication method's process
  861. try {
  862. const username = curAuth.username;
  863. switch (curAuth.type) {
  864. case 'password':
  865. proto.authPassword(username, curAuth.password);
  866. break;
  867. case 'publickey':
  868. proto.authPK(username, curAuth.key);
  869. break;
  870. case 'hostbased':
  871. proto.authHostbased(username,
  872. curAuth.key,
  873. curAuth.localHostname,
  874. curAuth.localUsername,
  875. (buf, cb) => {
  876. const signature = curAuth.key.sign(buf);
  877. if (signature instanceof Error) {
  878. signature.message =
  879. `Error while signing with key: ${signature.message}`;
  880. signature.level = 'client-authentication';
  881. this.emit('error', signature);
  882. return tryNextAuth();
  883. }
  884. cb(signature);
  885. });
  886. break;
  887. case 'agent':
  888. curAuth.agentCtx.init((err) => {
  889. if (err) {
  890. err.level = 'agent';
  891. this.emit('error', err);
  892. return tryNextAuth();
  893. }
  894. tryNextAgentKey();
  895. });
  896. break;
  897. case 'keyboard-interactive':
  898. proto.authKeyboard(username);
  899. break;
  900. case 'none':
  901. proto.authNone(username);
  902. break;
  903. }
  904. } finally {
  905. hasSentAuth = false;
  906. }
  907. };
  908. function skipAuth(msg) {
  909. debug && debug(msg);
  910. process.nextTick(tryNextAuth);
  911. }
  912. function tryNextAuth() {
  913. hasSentAuth = false;
  914. const auth = authHandler(curAuthsLeft, curPartial, doNextAuth);
  915. if (hasSentAuth || auth === undefined)
  916. return;
  917. doNextAuth(auth);
  918. }
  919. const tryNextAgentKey = () => {
  920. if (curAuth.type === 'agent') {
  921. const key = curAuth.agentCtx.nextKey();
  922. if (key === false) {
  923. debug && debug('Agent: No more keys left to try');
  924. debug && debug('Client: agent auth failed');
  925. tryNextAuth();
  926. } else {
  927. const pos = curAuth.agentCtx.pos();
  928. debug && debug(`Agent: Trying key #${pos + 1}`);
  929. proto.authPK(curAuth.username, key);
  930. }
  931. }
  932. };
  933. const startTimeout = () => {
  934. if (this.config.readyTimeout > 0) {
  935. this._readyTimeout = setTimeout(() => {
  936. const err = new Error('Timed out while waiting for handshake');
  937. err.level = 'client-timeout';
  938. this.emit('error', err);
  939. sock.destroy();
  940. }, this.config.readyTimeout);
  941. }
  942. };
  943. if (!cfg.sock) {
  944. let host = this.config.host;
  945. const forceIPv4 = this.config.forceIPv4;
  946. const forceIPv6 = this.config.forceIPv6;
  947. debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`);
  948. const doConnect = () => {
  949. startTimeout();
  950. sock.connect({
  951. host,
  952. port: this.config.port,
  953. localAddress: this.config.localAddress,
  954. localPort: this.config.localPort
  955. });
  956. sock.setNoDelay(true);
  957. sock.setMaxListeners(0);
  958. sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0);
  959. };
  960. if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) {
  961. doConnect();
  962. } else {
  963. dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => {
  964. if (err) {
  965. const type = (forceIPv4 ? 'IPv4' : 'IPv6');
  966. const error = new Error(
  967. `Error while looking up ${type} address for '${host}': ${err}`
  968. );
  969. clearTimeout(this._readyTimeout);
  970. error.level = 'client-dns';
  971. this.emit('error', error);
  972. this.emit('close');
  973. return;
  974. }
  975. host = address;
  976. doConnect();
  977. });
  978. }
  979. } else {
  980. // Custom socket passed in
  981. startTimeout();
  982. if (typeof sock.connecting === 'boolean') {
  983. // net.Socket
  984. if (!sock.connecting) {
  985. // Already connected
  986. onConnect();
  987. }
  988. } else {
  989. // Assume socket/stream is already "connected"
  990. onConnect();
  991. }
  992. }
  993. return this;
  994. }
  995. end() {
  996. if (this._sock && isWritable(this._sock)) {
  997. this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);
  998. this._sock.end();
  999. }
  1000. return this;
  1001. }
  1002. destroy() {
  1003. this._sock && isWritable(this._sock) && this._sock.destroy();
  1004. return this;
  1005. }
  1006. exec(cmd, opts, cb) {
  1007. if (!this._sock || !isWritable(this._sock))
  1008. throw new Error('Not connected');
  1009. if (typeof opts === 'function') {
  1010. cb = opts;
  1011. opts = {};
  1012. }
  1013. const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) };
  1014. openChannel(this, 'session', extraOpts, (err, chan) => {
  1015. if (err) {
  1016. cb(err);
  1017. return;
  1018. }
  1019. const todo = [];
  1020. function reqCb(err) {
  1021. if (err) {
  1022. chan.close();
  1023. cb(err);
  1024. return;
  1025. }
  1026. if (todo.length)
  1027. todo.shift()();
  1028. }
  1029. if (this.config.allowAgentFwd === true
  1030. || (opts
  1031. && opts.agentForward === true
  1032. && this._agent !== undefined)) {
  1033. todo.push(() => reqAgentFwd(chan, reqCb));
  1034. }
  1035. if (typeof opts === 'object' && opts !== null) {
  1036. if (typeof opts.env === 'object' && opts.env !== null)
  1037. reqEnv(chan, opts.env);
  1038. if ((typeof opts.pty === 'object' && opts.pty !== null)
  1039. || opts.pty === true) {
  1040. todo.push(() => reqPty(chan, opts.pty, reqCb));
  1041. }
  1042. if ((typeof opts.x11 === 'object' && opts.x11 !== null)
  1043. || opts.x11 === 'number'
  1044. || opts.x11 === true) {
  1045. todo.push(() => reqX11(chan, opts.x11, reqCb));
  1046. }
  1047. }
  1048. todo.push(() => reqExec(chan, cmd, opts, cb));
  1049. todo.shift()();
  1050. });
  1051. return this;
  1052. }
  1053. shell(wndopts, opts, cb) {
  1054. if (!this._sock || !isWritable(this._sock))
  1055. throw new Error('Not connected');
  1056. if (typeof wndopts === 'function') {
  1057. cb = wndopts;
  1058. wndopts = opts = undefined;
  1059. } else if (typeof opts === 'function') {
  1060. cb = opts;
  1061. opts = undefined;
  1062. }
  1063. if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) {
  1064. opts = wndopts;
  1065. wndopts = undefined;
  1066. }
  1067. openChannel(this, 'session', (err, chan) => {
  1068. if (err) {
  1069. cb(err);
  1070. return;
  1071. }
  1072. const todo = [];
  1073. function reqCb(err) {
  1074. if (err) {
  1075. chan.close();
  1076. cb(err);
  1077. return;
  1078. }
  1079. if (todo.length)
  1080. todo.shift()();
  1081. }
  1082. if (this.config.allowAgentFwd === true
  1083. || (opts
  1084. && opts.agentForward === true
  1085. && this._agent !== undefined)) {
  1086. todo.push(() => reqAgentFwd(chan, reqCb));
  1087. }
  1088. if (wndopts !== false)
  1089. todo.push(() => reqPty(chan, wndopts, reqCb));
  1090. if (typeof opts === 'object' && opts !== null) {
  1091. if (typeof opts.env === 'object' && opts.env !== null)
  1092. reqEnv(chan, opts.env);
  1093. if ((typeof opts.x11 === 'object' && opts.x11 !== null)
  1094. || opts.x11 === 'number'
  1095. || opts.x11 === true) {
  1096. todo.push(() => reqX11(chan, opts.x11, reqCb));
  1097. }
  1098. }
  1099. todo.push(() => reqShell(chan, cb));
  1100. todo.shift()();
  1101. });
  1102. return this;
  1103. }
  1104. subsys(name, cb) {
  1105. if (!this._sock || !isWritable(this._sock))
  1106. throw new Error('Not connected');
  1107. openChannel(this, 'session', (err, chan) => {
  1108. if (err) {
  1109. cb(err);
  1110. return;
  1111. }
  1112. reqSubsystem(chan, name, (err, stream) => {
  1113. if (err) {
  1114. cb(err);
  1115. return;
  1116. }
  1117. cb(undefined, stream);
  1118. });
  1119. });
  1120. return this;
  1121. }
  1122. forwardIn(bindAddr, bindPort, cb) {
  1123. if (!this._sock || !isWritable(this._sock))
  1124. throw new Error('Not connected');
  1125. // Send a request for the server to start forwarding TCP connections to us
  1126. // on a particular address and port
  1127. const wantReply = (typeof cb === 'function');
  1128. if (wantReply) {
  1129. this._callbacks.push((had_err, data) => {
  1130. if (had_err) {
  1131. cb(had_err !== true
  1132. ? had_err
  1133. : new Error(`Unable to bind to ${bindAddr}:${bindPort}`));
  1134. return;
  1135. }
  1136. let realPort = bindPort;
  1137. if (bindPort === 0 && data && data.length >= 4) {
  1138. realPort = readUInt32BE(data, 0);
  1139. if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG))
  1140. bindPort = realPort;
  1141. }
  1142. this._forwarding[`${bindAddr}:${bindPort}`] = realPort;
  1143. cb(undefined, realPort);
  1144. });
  1145. }
  1146. this._protocol.tcpipForward(bindAddr, bindPort, wantReply);
  1147. return this;
  1148. }
  1149. unforwardIn(bindAddr, bindPort, cb) {
  1150. if (!this._sock || !isWritable(this._sock))
  1151. throw new Error('Not connected');
  1152. // Send a request to stop forwarding us new connections for a particular
  1153. // address and port
  1154. const wantReply = (typeof cb === 'function');
  1155. if (wantReply) {
  1156. this._callbacks.push((had_err) => {
  1157. if (had_err) {
  1158. cb(had_err !== true
  1159. ? had_err
  1160. : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`));
  1161. return;
  1162. }
  1163. delete this._forwarding[`${bindAddr}:${bindPort}`];
  1164. cb();
  1165. });
  1166. }
  1167. this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply);
  1168. return this;
  1169. }
  1170. forwardOut(srcIP, srcPort, dstIP, dstPort, cb) {
  1171. if (!this._sock || !isWritable(this._sock))
  1172. throw new Error('Not connected');
  1173. // Send a request to forward a TCP connection to the server
  1174. const cfg = {
  1175. srcIP: srcIP,
  1176. srcPort: srcPort,
  1177. dstIP: dstIP,
  1178. dstPort: dstPort
  1179. };
  1180. if (typeof cb !== 'function')
  1181. cb = noop;
  1182. openChannel(this, 'direct-tcpip', cfg, cb);
  1183. return this;
  1184. }
  1185. openssh_noMoreSessions(cb) {
  1186. if (!this._sock || !isWritable(this._sock))
  1187. throw new Error('Not connected');
  1188. const wantReply = (typeof cb === 'function');
  1189. if (!this.config.strictVendor
  1190. || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {
  1191. if (wantReply) {
  1192. this._callbacks.push((had_err) => {
  1193. if (had_err) {
  1194. cb(had_err !== true
  1195. ? had_err
  1196. : new Error('Unable to disable future sessions'));
  1197. return;
  1198. }
  1199. cb();
  1200. });
  1201. }
  1202. this._protocol.openssh_noMoreSessions(wantReply);
  1203. return this;
  1204. }
  1205. if (!wantReply)
  1206. return this;
  1207. process.nextTick(
  1208. cb,
  1209. new Error(
  1210. 'strictVendor enabled and server is not OpenSSH or compatible version'
  1211. )
  1212. );
  1213. return this;
  1214. }
  1215. openssh_forwardInStreamLocal(socketPath, cb) {
  1216. if (!this._sock || !isWritable(this._sock))
  1217. throw new Error('Not connected');
  1218. const wantReply = (typeof cb === 'function');
  1219. if (!this.config.strictVendor
  1220. || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {
  1221. if (wantReply) {
  1222. this._callbacks.push((had_err) => {
  1223. if (had_err) {
  1224. cb(had_err !== true
  1225. ? had_err
  1226. : new Error(`Unable to bind to ${socketPath}`));
  1227. return;
  1228. }
  1229. this._forwardingUnix[socketPath] = true;
  1230. cb();
  1231. });
  1232. }
  1233. this._protocol.openssh_streamLocalForward(socketPath, wantReply);
  1234. return this;
  1235. }
  1236. if (!wantReply)
  1237. return this;
  1238. process.nextTick(
  1239. cb,
  1240. new Error(
  1241. 'strictVendor enabled and server is not OpenSSH or compatible version'
  1242. )
  1243. );
  1244. return this;
  1245. }
  1246. openssh_unforwardInStreamLocal(socketPath, cb) {
  1247. if (!this._sock || !isWritable(this._sock))
  1248. throw new Error('Not connected');
  1249. const wantReply = (typeof cb === 'function');
  1250. if (!this.config.strictVendor
  1251. || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {
  1252. if (wantReply) {
  1253. this._callbacks.push((had_err) => {
  1254. if (had_err) {
  1255. cb(had_err !== true
  1256. ? had_err
  1257. : new Error(`Unable to unbind from ${socketPath}`));
  1258. return;
  1259. }
  1260. delete this._forwardingUnix[socketPath];
  1261. cb();
  1262. });
  1263. }
  1264. this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply);
  1265. return this;
  1266. }
  1267. if (!wantReply)
  1268. return this;
  1269. process.nextTick(
  1270. cb,
  1271. new Error(
  1272. 'strictVendor enabled and server is not OpenSSH or compatible version'
  1273. )
  1274. );
  1275. return this;
  1276. }
  1277. openssh_forwardOutStreamLocal(socketPath, cb) {
  1278. if (!this._sock || !isWritable(this._sock))
  1279. throw new Error('Not connected');
  1280. if (typeof cb !== 'function')
  1281. cb = noop;
  1282. if (!this.config.strictVendor
  1283. || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {
  1284. openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb);
  1285. return this;
  1286. }
  1287. process.nextTick(
  1288. cb,
  1289. new Error(
  1290. 'strictVendor enabled and server is not OpenSSH or compatible version'
  1291. )
  1292. );
  1293. return this;
  1294. }
  1295. sftp(cb) {
  1296. if (!this._sock || !isWritable(this._sock))
  1297. throw new Error('Not connected');
  1298. openChannel(this, 'sftp', (err, sftp) => {
  1299. if (err) {
  1300. cb(err);
  1301. return;
  1302. }
  1303. reqSubsystem(sftp, 'sftp', (err, sftp_) => {
  1304. if (err) {
  1305. cb(err);
  1306. return;
  1307. }
  1308. function removeListeners() {
  1309. sftp.removeListener('ready', onReady);
  1310. sftp.removeListener('error', onError);
  1311. sftp.removeListener('exit', onExit);
  1312. sftp.removeListener('close', onExit);
  1313. }
  1314. function onReady() {
  1315. // TODO: do not remove exit/close in case remote end closes the
  1316. // channel abruptly and we need to notify outstanding callbacks
  1317. removeListeners();
  1318. cb(undefined, sftp);
  1319. }
  1320. function onError(err) {
  1321. removeListeners();
  1322. cb(err);
  1323. }
  1324. function onExit(code, signal) {
  1325. removeListeners();
  1326. let msg;
  1327. if (typeof code === 'number')
  1328. msg = `Received exit code ${code} while establishing SFTP session`;
  1329. else if (signal !== undefined)
  1330. msg = `Received signal ${signal} while establishing SFTP session`;
  1331. else
  1332. msg = 'Received unexpected SFTP session termination';
  1333. const err = new Error(msg);
  1334. err.code = code;
  1335. err.signal = signal;
  1336. cb(err);
  1337. }
  1338. sftp.on('ready', onReady)
  1339. .on('error', onError)
  1340. .on('exit', onExit)
  1341. .on('close', onExit);
  1342. sftp._init();
  1343. });
  1344. });
  1345. return this;
  1346. }
  1347. }
  1348. function openChannel(self, type, opts, cb) {
  1349. // Ask the server to open a channel for some purpose
  1350. // (e.g. session (sftp, exec, shell), or forwarding a TCP connection
  1351. const initWindow = MAX_WINDOW;
  1352. const maxPacket = PACKET_SIZE;
  1353. if (typeof opts === 'function') {
  1354. cb = opts;
  1355. opts = {};
  1356. }
  1357. const wrapper = (err, stream) => {
  1358. cb(err, stream);
  1359. };
  1360. wrapper.type = type;
  1361. const localChan = self._chanMgr.add(wrapper);
  1362. if (localChan === -1) {
  1363. cb(new Error('No free channels available'));
  1364. return;
  1365. }
  1366. switch (type) {
  1367. case 'session':
  1368. case 'sftp':
  1369. self._protocol.session(localChan, initWindow, maxPacket);
  1370. break;
  1371. case 'direct-tcpip':
  1372. self._protocol.directTcpip(localChan, initWindow, maxPacket, opts);
  1373. break;
  1374. case 'direct-streamlocal@openssh.com':
  1375. self._protocol.openssh_directStreamLocal(
  1376. localChan, initWindow, maxPacket, opts
  1377. );
  1378. break;
  1379. default:
  1380. throw new Error(`Unsupported channel type: ${type}`);
  1381. }
  1382. }
  1383. function reqX11(chan, screen, cb) {
  1384. // Asks server to start sending us X11 connections
  1385. const cfg = {
  1386. single: false,
  1387. protocol: 'MIT-MAGIC-COOKIE-1',
  1388. cookie: undefined,
  1389. screen: 0
  1390. };
  1391. if (typeof screen === 'function') {
  1392. cb = screen;
  1393. } else if (typeof screen === 'object' && screen !== null) {
  1394. if (typeof screen.single === 'boolean')
  1395. cfg.single = screen.single;
  1396. if (typeof screen.screen === 'number')
  1397. cfg.screen = screen.screen;
  1398. if (typeof screen.protocol === 'string')
  1399. cfg.protocol = screen.protocol;
  1400. if (typeof screen.cookie === 'string')
  1401. cfg.cookie = screen.cookie;
  1402. else if (Buffer.isBuffer(screen.cookie))
  1403. cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length);
  1404. }
  1405. if (cfg.cookie === undefined)
  1406. cfg.cookie = randomCookie();
  1407. const wantReply = (typeof cb === 'function');
  1408. if (chan.outgoing.state !== 'open') {
  1409. if (wantReply)
  1410. cb(new Error('Channel is not open'));
  1411. return;
  1412. }
  1413. if (wantReply) {
  1414. chan._callbacks.push((had_err) => {
  1415. if (had_err) {
  1416. cb(had_err !== true ? had_err : new Error('Unable to request X11'));
  1417. return;
  1418. }
  1419. chan._hasX11 = true;
  1420. ++chan._client._acceptX11;
  1421. chan.once('close', () => {
  1422. if (chan._client._acceptX11)
  1423. --chan._client._acceptX11;
  1424. });
  1425. cb();
  1426. });
  1427. }
  1428. chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply);
  1429. }
  1430. function reqPty(chan, opts, cb) {
  1431. let rows = 24;
  1432. let cols = 80;
  1433. let width = 640;
  1434. let height = 480;
  1435. let term = 'vt100';
  1436. let modes = null;
  1437. if (typeof opts === 'function') {
  1438. cb = opts;
  1439. } else if (typeof opts === 'object' && opts !== null) {
  1440. if (typeof opts.rows === 'number')
  1441. rows = opts.rows;
  1442. if (typeof opts.cols === 'number')
  1443. cols = opts.cols;
  1444. if (typeof opts.width === 'number')
  1445. width = opts.width;
  1446. if (typeof opts.height === 'number')
  1447. height = opts.height;
  1448. if (typeof opts.term === 'string')
  1449. term = opts.term;
  1450. if (typeof opts.modes === 'object')
  1451. modes = opts.modes;
  1452. }
  1453. const wantReply = (typeof cb === 'function');
  1454. if (chan.outgoing.state !== 'open') {
  1455. if (wantReply)
  1456. cb(new Error('Channel is not open'));
  1457. return;
  1458. }
  1459. if (wantReply) {
  1460. chan._callbacks.push((had_err) => {
  1461. if (had_err) {
  1462. cb(had_err !== true
  1463. ? had_err
  1464. : new Error('Unable to request a pseudo-terminal'));
  1465. return;
  1466. }
  1467. cb();
  1468. });
  1469. }
  1470. chan._client._protocol.pty(chan.outgoing.id,
  1471. rows,
  1472. cols,
  1473. height,
  1474. width,
  1475. term,
  1476. modes,
  1477. wantReply);
  1478. }
  1479. function reqAgentFwd(chan, cb) {
  1480. const wantReply = (typeof cb === 'function');
  1481. if (chan.outgoing.state !== 'open') {
  1482. wantReply && cb(new Error('Channel is not open'));
  1483. return;
  1484. }
  1485. if (chan._client._agentFwdEnabled) {
  1486. wantReply && cb(false);
  1487. return;
  1488. }
  1489. chan._client._agentFwdEnabled = true;
  1490. chan._callbacks.push((had_err) => {
  1491. if (had_err) {
  1492. chan._client._agentFwdEnabled = false;
  1493. if (wantReply) {
  1494. cb(had_err !== true
  1495. ? had_err
  1496. : new Error('Unable to request agent forwarding'));
  1497. }
  1498. return;
  1499. }
  1500. if (wantReply)
  1501. cb();
  1502. });
  1503. chan._client._protocol.openssh_agentForward(chan.outgoing.id, true);
  1504. }
  1505. function reqShell(chan, cb) {
  1506. if (chan.outgoing.state !== 'open') {
  1507. cb(new Error('Channel is not open'));
  1508. return;
  1509. }
  1510. chan._callbacks.push((had_err) => {
  1511. if (had_err) {
  1512. cb(had_err !== true ? had_err : new Error('Unable to open shell'));
  1513. return;
  1514. }
  1515. chan.subtype = 'shell';
  1516. cb(undefined, chan);
  1517. });
  1518. chan._client._protocol.shell(chan.outgoing.id, true);
  1519. }
  1520. function reqExec(chan, cmd, opts, cb) {
  1521. if (chan.outgoing.state !== 'open') {
  1522. cb(new Error('Channel is not open'));
  1523. return;
  1524. }
  1525. chan._callbacks.push((had_err) => {
  1526. if (had_err) {
  1527. cb(had_err !== true ? had_err : new Error('Unable to exec'));
  1528. return;
  1529. }
  1530. chan.subtype = 'exec';
  1531. chan.allowHalfOpen = (opts.allowHalfOpen !== false);
  1532. cb(undefined, chan);
  1533. });
  1534. chan._client._protocol.exec(chan.outgoing.id, cmd, true);
  1535. }
  1536. function reqEnv(chan, env) {
  1537. if (chan.outgoing.state !== 'open')
  1538. return;
  1539. const keys = Object.keys(env || {});
  1540. for (let i = 0; i < keys.length; ++i) {
  1541. const key = keys[i];
  1542. const val = env[key];
  1543. chan._client._protocol.env(chan.outgoing.id, key, val, false);
  1544. }
  1545. }
  1546. function reqSubsystem(chan, name, cb) {
  1547. if (chan.outgoing.state !== 'open') {
  1548. cb(new Error('Channel is not open'));
  1549. return;
  1550. }
  1551. chan._callbacks.push((had_err) => {
  1552. if (had_err) {
  1553. cb(had_err !== true
  1554. ? had_err
  1555. : new Error(`Unable to start subsystem: ${name}`));
  1556. return;
  1557. }
  1558. chan.subtype = 'subsystem';
  1559. cb(undefined, chan);
  1560. });
  1561. chan._client._protocol.subsystem(chan.outgoing.id, name, true);
  1562. }
  1563. // TODO: inline implementation into single call site
  1564. function onCHANNEL_OPEN(self, info) {
  1565. // The server is trying to open a channel with us, this is usually when
  1566. // we asked the server to forward us connections on some port and now they
  1567. // are asking us to accept/deny an incoming connection on their side
  1568. let localChan = -1;
  1569. let reason;
  1570. const accept = () => {
  1571. const chanInfo = {
  1572. type: info.type,
  1573. incoming: {
  1574. id: localChan,
  1575. window: MAX_WINDOW,
  1576. packetSize: PACKET_SIZE,
  1577. state: 'open'
  1578. },
  1579. outgoing: {
  1580. id: info.sender,
  1581. window: info.window,
  1582. packetSize: info.packetSize,
  1583. state: 'open'
  1584. }
  1585. };
  1586. const stream = new Channel(self, chanInfo);
  1587. self._chanMgr.update(localChan, stream);
  1588. self._protocol.channelOpenConfirm(info.sender,
  1589. localChan,
  1590. MAX_WINDOW,
  1591. PACKET_SIZE);
  1592. return stream;
  1593. };
  1594. const reject = () => {
  1595. if (reason === undefined) {
  1596. if (localChan === -1)
  1597. reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;
  1598. else
  1599. reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;
  1600. }
  1601. if (localChan !== -1)
  1602. self._chanMgr.remove(localChan);
  1603. self._protocol.channelOpenFail(info.sender, reason, '');
  1604. };
  1605. const reserveChannel = () => {
  1606. localChan = self._chanMgr.add();
  1607. if (localChan === -1) {
  1608. reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;
  1609. if (self.config.debug) {
  1610. self.config.debug(
  1611. 'Client: Automatic rejection of incoming channel open: '
  1612. + 'no channels available'
  1613. );
  1614. }
  1615. }
  1616. return (localChan !== -1);
  1617. };
  1618. const data = info.data;
  1619. switch (info.type) {
  1620. case 'forwarded-tcpip': {
  1621. const val = self._forwarding[`${data.destIP}:${data.destPort}`];
  1622. if (val !== undefined && reserveChannel()) {
  1623. if (data.destPort === 0)
  1624. data.destPort = val;
  1625. self.emit('tcp connection', data, accept, reject);
  1626. return;
  1627. }
  1628. break;
  1629. }
  1630. case 'forwarded-streamlocal@openssh.com':
  1631. if (self._forwardingUnix[data.socketPath] !== undefined
  1632. && reserveChannel()) {
  1633. self.emit('unix connection', data, accept, reject);
  1634. return;
  1635. }
  1636. break;
  1637. case 'auth-agent@openssh.com':
  1638. if (self._agentFwdEnabled
  1639. && typeof self._agent.getStream === 'function'
  1640. && reserveChannel()) {
  1641. self._agent.getStream((err, stream) => {
  1642. if (err)
  1643. return reject();
  1644. const upstream = accept();
  1645. upstream.pipe(stream).pipe(upstream);
  1646. });
  1647. return;
  1648. }
  1649. break;
  1650. case 'x11':
  1651. if (self._acceptX11 !== 0 && reserveChannel()) {
  1652. self.emit('x11', data, accept, reject);
  1653. return;
  1654. }
  1655. break;
  1656. default:
  1657. // Automatically reject any unsupported channel open requests
  1658. reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;
  1659. if (self.config.debug) {
  1660. self.config.debug(
  1661. 'Client: Automatic rejection of unsupported incoming channel open '
  1662. + `type: ${info.type}`
  1663. );
  1664. }
  1665. }
  1666. if (reason === undefined) {
  1667. reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;
  1668. if (self.config.debug) {
  1669. self.config.debug(
  1670. 'Client: Automatic rejection of unexpected incoming channel open for: '
  1671. + info.type
  1672. );
  1673. }
  1674. }
  1675. reject();
  1676. }
  1677. const randomCookie = (() => {
  1678. const buffer = Buffer.allocUnsafe(16);
  1679. return () => {
  1680. randomFillSync(buffer, 0, 16);
  1681. return buffer.hexSlice(0, 16);
  1682. };
  1683. })();
  1684. function makeSimpleAuthHandler(authList) {
  1685. if (!Array.isArray(authList))
  1686. throw new Error('authList must be an array');
  1687. let a = 0;
  1688. return (authsLeft, partialSuccess, cb) => {
  1689. if (a === authList.length)
  1690. return false;
  1691. return authList[a++];
  1692. };
  1693. }
  1694. function hostKeysProve(client, keys_, cb) {
  1695. if (!client._sock || !isWritable(client._sock))
  1696. return;
  1697. if (typeof cb !== 'function')
  1698. cb = noop;
  1699. if (!Array.isArray(keys_))
  1700. throw new TypeError('Invalid keys argument type');
  1701. const keys = [];
  1702. for (const key of keys_) {
  1703. const parsed = parseKey(key);
  1704. if (parsed instanceof Error)
  1705. throw parsed;
  1706. keys.push(parsed);
  1707. }
  1708. if (!client.config.strictVendor
  1709. || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) {
  1710. client._callbacks.push((had_err, data) => {
  1711. if (had_err) {
  1712. cb(had_err !== true
  1713. ? had_err
  1714. : new Error('Server failed to prove supplied keys'));
  1715. return;
  1716. }
  1717. // TODO: move all of this parsing/verifying logic out of the client?
  1718. const ret = [];
  1719. let keyIdx = 0;
  1720. bufferParser.init(data, 0);
  1721. while (bufferParser.avail()) {
  1722. if (keyIdx === keys.length)
  1723. break;
  1724. const key = keys[keyIdx++];
  1725. const keyPublic = key.getPublicSSH();
  1726. const sigEntry = bufferParser.readString();
  1727. sigParser.init(sigEntry, 0);
  1728. const type = sigParser.readString(true);
  1729. let value = sigParser.readString();
  1730. let algo;
  1731. if (type !== key.type) {
  1732. if (key.type === 'ssh-rsa') {
  1733. switch (type) {
  1734. case 'rsa-sha2-256':
  1735. algo = 'sha256';
  1736. break;
  1737. case 'rsa-sha2-512':
  1738. algo = 'sha512';
  1739. break;
  1740. default:
  1741. continue;
  1742. }
  1743. } else {
  1744. continue;
  1745. }
  1746. }
  1747. const sessionID = client._protocol._kex.sessionID;
  1748. const verifyData = Buffer.allocUnsafe(
  1749. 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length
  1750. );
  1751. let p = 0;
  1752. writeUInt32BE(verifyData, 29, p);
  1753. verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29);
  1754. writeUInt32BE(verifyData, sessionID.length, p += 29);
  1755. bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4);
  1756. writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length);
  1757. bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4);
  1758. if (!(value = sigSSHToASN1(value, type)))
  1759. continue;
  1760. if (key.verify(verifyData, value, algo) === true)
  1761. ret.push(key);
  1762. }
  1763. sigParser.clear();
  1764. bufferParser.clear();
  1765. cb(null, ret);
  1766. });
  1767. client._protocol.openssh_hostKeysProve(keys);
  1768. return;
  1769. }
  1770. process.nextTick(
  1771. cb,
  1772. new Error(
  1773. 'strictVendor enabled and server is not OpenSSH or compatible version'
  1774. )
  1775. );
  1776. }
  1777. module.exports = Client;