server.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. var net = require('net');
  2. var EventEmitter = require('events').EventEmitter;
  3. var listenerCount = EventEmitter.listenerCount;
  4. var inherits = require('util').inherits;
  5. var ssh2_streams = require('ssh2-streams');
  6. var parseKey = ssh2_streams.utils.parseKey;
  7. var SSH2Stream = ssh2_streams.SSH2Stream;
  8. var SFTPStream = ssh2_streams.SFTPStream;
  9. var consts = ssh2_streams.constants;
  10. var DISCONNECT_REASON = consts.DISCONNECT_REASON;
  11. var CHANNEL_OPEN_FAILURE = consts.CHANNEL_OPEN_FAILURE;
  12. var ALGORITHMS = consts.ALGORITHMS;
  13. var Channel = require('./Channel');
  14. var KeepaliveManager = require('./keepalivemgr');
  15. var writeUInt32BE = require('./buffer-helpers').writeUInt32BE;
  16. var MAX_CHANNEL = Math.pow(2, 32) - 1;
  17. var MAX_PENDING_AUTHS = 10;
  18. var kaMgr;
  19. function Server(cfg, listener) {
  20. if (!(this instanceof Server))
  21. return new Server(cfg, listener);
  22. var hostKeys = {
  23. 'ssh-rsa': null,
  24. 'ssh-dss': null,
  25. 'ssh-ed25519': null,
  26. 'ecdsa-sha2-nistp256': null,
  27. 'ecdsa-sha2-nistp384': null,
  28. 'ecdsa-sha2-nistp521': null
  29. };
  30. var hostKeys_ = cfg.hostKeys;
  31. if (!Array.isArray(hostKeys_))
  32. throw new Error('hostKeys must be an array');
  33. var i;
  34. for (i = 0; i < hostKeys_.length; ++i) {
  35. var privateKey;
  36. if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string')
  37. privateKey = parseKey(hostKeys_[i]);
  38. else
  39. privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase);
  40. if (privateKey instanceof Error)
  41. throw new Error('Cannot parse privateKey: ' + privateKey.message);
  42. if (privateKey.getPrivatePEM() === null)
  43. throw new Error('privateKey value contains an invalid private key');
  44. if (hostKeys[privateKey.type])
  45. continue;
  46. hostKeys[privateKey.type] = privateKey;
  47. }
  48. var algorithms = {
  49. kex: undefined,
  50. kexBuf: undefined,
  51. cipher: undefined,
  52. cipherBuf: undefined,
  53. serverHostKey: undefined,
  54. serverHostKeyBuf: undefined,
  55. hmac: undefined,
  56. hmacBuf: undefined,
  57. compress: undefined,
  58. compressBuf: undefined
  59. };
  60. if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) {
  61. var algosSupported;
  62. var algoList;
  63. algoList = cfg.algorithms.kex;
  64. if (Array.isArray(algoList) && algoList.length > 0) {
  65. algosSupported = ALGORITHMS.SUPPORTED_KEX;
  66. for (i = 0; i < algoList.length; ++i) {
  67. if (algosSupported.indexOf(algoList[i]) === -1)
  68. throw new Error('Unsupported key exchange algorithm: ' + algoList[i]);
  69. }
  70. algorithms.kex = algoList;
  71. }
  72. algoList = cfg.algorithms.cipher;
  73. if (Array.isArray(algoList) && algoList.length > 0) {
  74. algosSupported = ALGORITHMS.SUPPORTED_CIPHER;
  75. for (i = 0; i < algoList.length; ++i) {
  76. if (algosSupported.indexOf(algoList[i]) === -1)
  77. throw new Error('Unsupported cipher algorithm: ' + algoList[i]);
  78. }
  79. algorithms.cipher = algoList;
  80. }
  81. algoList = cfg.algorithms.serverHostKey;
  82. var copied = false;
  83. if (Array.isArray(algoList) && algoList.length > 0) {
  84. algosSupported = ALGORITHMS.SUPPORTED_SERVER_HOST_KEY;
  85. for (i = algoList.length - 1; i >= 0; --i) {
  86. if (algosSupported.indexOf(algoList[i]) === -1) {
  87. throw new Error('Unsupported server host key algorithm: '
  88. + algoList[i]);
  89. }
  90. if (!hostKeys[algoList[i]]) {
  91. // Silently discard for now
  92. if (!copied) {
  93. algoList = algoList.slice();
  94. copied = true;
  95. }
  96. algoList.splice(i, 1);
  97. }
  98. }
  99. if (algoList.length > 0)
  100. algorithms.serverHostKey = algoList;
  101. }
  102. algoList = cfg.algorithms.hmac;
  103. if (Array.isArray(algoList) && algoList.length > 0) {
  104. algosSupported = ALGORITHMS.SUPPORTED_HMAC;
  105. for (i = 0; i < algoList.length; ++i) {
  106. if (algosSupported.indexOf(algoList[i]) === -1)
  107. throw new Error('Unsupported HMAC algorithm: ' + algoList[i]);
  108. }
  109. algorithms.hmac = algoList;
  110. }
  111. algoList = cfg.algorithms.compress;
  112. if (Array.isArray(algoList) && algoList.length > 0) {
  113. algosSupported = ALGORITHMS.SUPPORTED_COMPRESS;
  114. for (i = 0; i < algoList.length; ++i) {
  115. if (algosSupported.indexOf(algoList[i]) === -1)
  116. throw new Error('Unsupported compression algorithm: ' + algoList[i]);
  117. }
  118. algorithms.compress = algoList;
  119. }
  120. }
  121. // Make sure we at least have some kind of valid list of support key
  122. // formats
  123. if (algorithms.serverHostKey === undefined) {
  124. var hostKeyAlgos = Object.keys(hostKeys);
  125. for (i = hostKeyAlgos.length - 1; i >= 0; --i) {
  126. if (!hostKeys[hostKeyAlgos[i]])
  127. hostKeyAlgos.splice(i, 1);
  128. }
  129. algorithms.serverHostKey = hostKeyAlgos;
  130. }
  131. if (!kaMgr
  132. && Server.KEEPALIVE_INTERVAL > 0
  133. && Server.KEEPALIVE_CLIENT_INTERVAL > 0
  134. && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0) {
  135. kaMgr = new KeepaliveManager(Server.KEEPALIVE_INTERVAL,
  136. Server.KEEPALIVE_CLIENT_INTERVAL,
  137. Server.KEEPALIVE_CLIENT_COUNT_MAX);
  138. }
  139. var self = this;
  140. EventEmitter.call(this);
  141. if (typeof listener === 'function')
  142. self.on('connection', listener);
  143. var streamcfg = {
  144. algorithms: algorithms,
  145. hostKeys: hostKeys,
  146. server: true
  147. };
  148. var keys;
  149. var len;
  150. for (i = 0, keys = Object.keys(cfg), len = keys.length; i < len; ++i) {
  151. var key = keys[i];
  152. if (key === 'privateKey'
  153. || key === 'publicKey'
  154. || key === 'passphrase'
  155. || key === 'algorithms'
  156. || key === 'hostKeys'
  157. || key === 'server') {
  158. continue;
  159. }
  160. streamcfg[key] = cfg[key];
  161. }
  162. if (typeof streamcfg.debug === 'function') {
  163. var oldDebug = streamcfg.debug;
  164. var cfgKeys = Object.keys(streamcfg);
  165. }
  166. this._srv = new net.Server(function(socket) {
  167. if (self._connections >= self.maxConnections) {
  168. socket.destroy();
  169. return;
  170. }
  171. ++self._connections;
  172. socket.once('close', function(had_err) {
  173. --self._connections;
  174. // since joyent/node#993bb93e0a, we have to "read past EOF" in order to
  175. // get an `end` event on streams. thankfully adding this does not
  176. // negatively affect node versions pre-joyent/node#993bb93e0a.
  177. sshstream.read();
  178. }).on('error', function(err) {
  179. sshstream.reset();
  180. sshstream.emit('error', err);
  181. });
  182. var conncfg = streamcfg;
  183. // prepend debug output with a unique identifier in case there are multiple
  184. // clients connected at the same time
  185. if (oldDebug) {
  186. conncfg = {};
  187. for (var i = 0, key; i < cfgKeys.length; ++i) {
  188. key = cfgKeys[i];
  189. conncfg[key] = streamcfg[key];
  190. }
  191. var debugPrefix = '[' + process.hrtime().join('.') + '] ';
  192. conncfg.debug = function(msg) {
  193. oldDebug(debugPrefix + msg);
  194. };
  195. }
  196. var sshstream = new SSH2Stream(conncfg);
  197. var client = new Client(sshstream, socket);
  198. socket.pipe(sshstream).pipe(socket);
  199. // silence pre-header errors
  200. function onClientPreHeaderError(err) {}
  201. client.on('error', onClientPreHeaderError);
  202. sshstream.once('header', function(header) {
  203. if (sshstream._readableState.ended) {
  204. // already disconnected internally in SSH2Stream due to incompatible
  205. // protocol version
  206. return;
  207. } else if (!listenerCount(self, 'connection')) {
  208. // auto reject
  209. return sshstream.disconnect(DISCONNECT_REASON.BY_APPLICATION);
  210. }
  211. client.removeListener('error', onClientPreHeaderError);
  212. self.emit('connection',
  213. client,
  214. { ip: socket.remoteAddress,
  215. family: socket.remoteFamily,
  216. port: socket.remotePort,
  217. header: header });
  218. });
  219. }).on('error', function(err) {
  220. self.emit('error', err);
  221. }).on('listening', function() {
  222. self.emit('listening');
  223. }).on('close', function() {
  224. self.emit('close');
  225. });
  226. this._connections = 0;
  227. this.maxConnections = Infinity;
  228. }
  229. inherits(Server, EventEmitter);
  230. Server.prototype.listen = function() {
  231. this._srv.listen.apply(this._srv, arguments);
  232. return this;
  233. };
  234. Server.prototype.address = function() {
  235. return this._srv.address();
  236. };
  237. Server.prototype.getConnections = function(cb) {
  238. this._srv.getConnections(cb);
  239. };
  240. Server.prototype.close = function(cb) {
  241. this._srv.close(cb);
  242. return this;
  243. };
  244. Server.prototype.ref = function() {
  245. this._srv.ref();
  246. };
  247. Server.prototype.unref = function() {
  248. this._srv.unref();
  249. };
  250. function Client(stream, socket) {
  251. EventEmitter.call(this);
  252. var self = this;
  253. this._sshstream = stream;
  254. var channels = this._channels = {};
  255. this._curChan = -1;
  256. this._sock = socket;
  257. this.noMoreSessions = false;
  258. this.authenticated = false;
  259. stream.on('end', function() {
  260. socket.resume();
  261. self.emit('end');
  262. }).on('close', function(hasErr) {
  263. self.emit('close', hasErr);
  264. }).on('error', function(err) {
  265. self.emit('error', err);
  266. }).on('drain', function() {
  267. self.emit('drain');
  268. }).on('continue', function() {
  269. self.emit('continue');
  270. });
  271. var exchanges = 0;
  272. var acceptedAuthSvc = false;
  273. var pendingAuths = [];
  274. var authCtx;
  275. // begin service/auth-related ================================================
  276. stream.on('SERVICE_REQUEST', function(service) {
  277. if (exchanges === 0
  278. || acceptedAuthSvc
  279. || self.authenticated
  280. || service !== 'ssh-userauth')
  281. return stream.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);
  282. acceptedAuthSvc = true;
  283. stream.serviceAccept(service);
  284. }).on('USERAUTH_REQUEST', onUSERAUTH_REQUEST);
  285. function onUSERAUTH_REQUEST(username, service, method, methodData) {
  286. if (exchanges === 0
  287. || (authCtx
  288. && (authCtx.username !== username || authCtx.service !== service))
  289. // TODO: support hostbased auth
  290. || (method !== 'password'
  291. && method !== 'publickey'
  292. && method !== 'hostbased'
  293. && method !== 'keyboard-interactive'
  294. && method !== 'none')
  295. || pendingAuths.length === MAX_PENDING_AUTHS)
  296. return stream.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR);
  297. else if (service !== 'ssh-connection')
  298. return stream.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);
  299. // XXX: this really shouldn't be reaching into private state ...
  300. stream._state.authMethod = method;
  301. var ctx;
  302. if (method === 'keyboard-interactive') {
  303. ctx = new KeyboardAuthContext(stream, username, service, method,
  304. methodData, onAuthDecide);
  305. } else if (method === 'publickey') {
  306. ctx = new PKAuthContext(stream, username, service, method, methodData,
  307. onAuthDecide);
  308. } else if (method === 'hostbased') {
  309. ctx = new HostbasedAuthContext(stream, username, service, method,
  310. methodData, onAuthDecide);
  311. } else if (method === 'password') {
  312. ctx = new PwdAuthContext(stream, username, service, method, methodData,
  313. onAuthDecide);
  314. } else if (method === 'none')
  315. ctx = new AuthContext(stream, username, service, method, onAuthDecide);
  316. if (authCtx) {
  317. if (!authCtx._initialResponse)
  318. return pendingAuths.push(ctx);
  319. else if (authCtx._multistep && !this._finalResponse) {
  320. // RFC 4252 says to silently abort the current auth request if a new
  321. // auth request comes in before the final response from an auth method
  322. // that requires additional request/response exchanges -- this means
  323. // keyboard-interactive for now ...
  324. authCtx._cleanup && authCtx._cleanup();
  325. authCtx.emit('abort');
  326. }
  327. }
  328. authCtx = ctx;
  329. if (listenerCount(self, 'authentication'))
  330. self.emit('authentication', authCtx);
  331. else
  332. authCtx.reject();
  333. }
  334. function onAuthDecide(ctx, allowed, methodsLeft, isPartial) {
  335. if (authCtx === ctx && !self.authenticated) {
  336. if (allowed) {
  337. stream.removeListener('USERAUTH_REQUEST', onUSERAUTH_REQUEST);
  338. authCtx = undefined;
  339. self.authenticated = true;
  340. stream.authSuccess();
  341. pendingAuths = [];
  342. self.emit('ready');
  343. } else {
  344. stream.authFailure(methodsLeft, isPartial);
  345. if (pendingAuths.length) {
  346. authCtx = pendingAuths.pop();
  347. if (listenerCount(self, 'authentication'))
  348. self.emit('authentication', authCtx);
  349. else
  350. authCtx.reject();
  351. }
  352. }
  353. }
  354. }
  355. // end service/auth-related ==================================================
  356. var unsentGlobalRequestsReplies = [];
  357. function sendReplies() {
  358. var reply;
  359. while (unsentGlobalRequestsReplies.length > 0
  360. && unsentGlobalRequestsReplies[0].type) {
  361. reply = unsentGlobalRequestsReplies.shift();
  362. if (reply.type === 'SUCCESS')
  363. stream.requestSuccess(reply.buf);
  364. if (reply.type === 'FAILURE')
  365. stream.requestFailure();
  366. }
  367. }
  368. stream.on('GLOBAL_REQUEST', function(name, wantReply, data) {
  369. var reply = {
  370. type: null,
  371. buf: null
  372. };
  373. function setReply(type, buf) {
  374. reply.type = type;
  375. reply.buf = buf;
  376. sendReplies();
  377. }
  378. if (wantReply)
  379. unsentGlobalRequestsReplies.push(reply);
  380. if ((name === 'tcpip-forward'
  381. || name === 'cancel-tcpip-forward'
  382. || name === 'no-more-sessions@openssh.com'
  383. || name === 'streamlocal-forward@openssh.com'
  384. || name === 'cancel-streamlocal-forward@openssh.com')
  385. && listenerCount(self, 'request')
  386. && self.authenticated) {
  387. var accept;
  388. var reject;
  389. if (wantReply) {
  390. var replied = false;
  391. accept = function(chosenPort) {
  392. if (replied)
  393. return;
  394. replied = true;
  395. var bufPort;
  396. if (name === 'tcpip-forward'
  397. && data.bindPort === 0
  398. && typeof chosenPort === 'number') {
  399. bufPort = Buffer.allocUnsafe(4);
  400. writeUInt32BE(bufPort, chosenPort, 0);
  401. }
  402. setReply('SUCCESS', bufPort);
  403. };
  404. reject = function() {
  405. if (replied)
  406. return;
  407. replied = true;
  408. setReply('FAILURE');
  409. };
  410. }
  411. if (name === 'no-more-sessions@openssh.com') {
  412. self.noMoreSessions = true;
  413. accept && accept();
  414. return;
  415. }
  416. self.emit('request', accept, reject, name, data);
  417. } else if (wantReply)
  418. setReply('FAILURE');
  419. });
  420. stream.on('CHANNEL_OPEN', function(info) {
  421. // do early reject in some cases to prevent wasteful channel allocation
  422. if ((info.type === 'session' && self.noMoreSessions)
  423. || !self.authenticated) {
  424. var reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;
  425. return stream.channelOpenFail(info.sender, reasonCode);
  426. }
  427. var localChan = nextChannel(self);
  428. var accept;
  429. var reject;
  430. var replied = false;
  431. if (localChan === false) {
  432. // auto-reject due to no channels available
  433. return stream.channelOpenFail(info.sender,
  434. CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE);
  435. }
  436. // be optimistic, reserve channel to prevent another request from trying to
  437. // take the same channel
  438. channels[localChan] = true;
  439. reject = function() {
  440. if (replied)
  441. return;
  442. replied = true;
  443. delete channels[localChan];
  444. var reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;
  445. return stream.channelOpenFail(info.sender, reasonCode);
  446. };
  447. switch (info.type) {
  448. case 'session':
  449. if (listenerCount(self, 'session')) {
  450. accept = function() {
  451. if (replied)
  452. return;
  453. replied = true;
  454. stream.channelOpenConfirm(info.sender,
  455. localChan,
  456. Channel.MAX_WINDOW,
  457. Channel.PACKET_SIZE);
  458. return new Session(self, info, localChan);
  459. };
  460. self.emit('session', accept, reject);
  461. } else
  462. reject();
  463. break;
  464. case 'direct-tcpip':
  465. if (listenerCount(self, 'tcpip')) {
  466. accept = function() {
  467. if (replied)
  468. return;
  469. replied = true;
  470. stream.channelOpenConfirm(info.sender,
  471. localChan,
  472. Channel.MAX_WINDOW,
  473. Channel.PACKET_SIZE);
  474. var chaninfo = {
  475. type: undefined,
  476. incoming: {
  477. id: localChan,
  478. window: Channel.MAX_WINDOW,
  479. packetSize: Channel.PACKET_SIZE,
  480. state: 'open'
  481. },
  482. outgoing: {
  483. id: info.sender,
  484. window: info.window,
  485. packetSize: info.packetSize,
  486. state: 'open'
  487. }
  488. };
  489. return new Channel(chaninfo, self);
  490. };
  491. self.emit('tcpip', accept, reject, info.data);
  492. } else
  493. reject();
  494. break;
  495. case 'direct-streamlocal@openssh.com':
  496. if (listenerCount(self, 'openssh.streamlocal')) {
  497. accept = function() {
  498. if (replied)
  499. return;
  500. replied = true;
  501. stream.channelOpenConfirm(info.sender,
  502. localChan,
  503. Channel.MAX_WINDOW,
  504. Channel.PACKET_SIZE);
  505. var chaninfo = {
  506. type: undefined,
  507. incoming: {
  508. id: localChan,
  509. window: Channel.MAX_WINDOW,
  510. packetSize: Channel.PACKET_SIZE,
  511. state: 'open'
  512. },
  513. outgoing: {
  514. id: info.sender,
  515. window: info.window,
  516. packetSize: info.packetSize,
  517. state: 'open'
  518. }
  519. };
  520. return new Channel(chaninfo, self);
  521. };
  522. self.emit('openssh.streamlocal', accept, reject, info.data);
  523. } else
  524. reject();
  525. break;
  526. default:
  527. // auto-reject unsupported channel types
  528. reject();
  529. }
  530. });
  531. stream.on('NEWKEYS', function() {
  532. if (++exchanges > 1)
  533. self.emit('rekey');
  534. });
  535. if (kaMgr) {
  536. this.once('ready', function() {
  537. kaMgr.add(stream);
  538. });
  539. }
  540. }
  541. inherits(Client, EventEmitter);
  542. Client.prototype.end = function() {
  543. return this._sshstream.disconnect(DISCONNECT_REASON.BY_APPLICATION);
  544. };
  545. Client.prototype.x11 = function(originAddr, originPort, cb) {
  546. var opts = {
  547. originAddr: originAddr,
  548. originPort: originPort
  549. };
  550. return openChannel(this, 'x11', opts, cb);
  551. };
  552. Client.prototype.forwardOut = function(boundAddr, boundPort, remoteAddr,
  553. remotePort, cb) {
  554. var opts = {
  555. boundAddr: boundAddr,
  556. boundPort: boundPort,
  557. remoteAddr: remoteAddr,
  558. remotePort: remotePort
  559. };
  560. return openChannel(this, 'forwarded-tcpip', opts, cb);
  561. };
  562. Client.prototype.openssh_forwardOutStreamLocal = function(socketPath, cb) {
  563. var opts = {
  564. socketPath: socketPath
  565. };
  566. return openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb);
  567. };
  568. Client.prototype.rekey = function(cb) {
  569. var stream = this._sshstream;
  570. var ret = true;
  571. var error;
  572. try {
  573. ret = stream.rekey();
  574. } catch (ex) {
  575. error = ex;
  576. }
  577. // TODO: re-throw error if no callback?
  578. if (typeof cb === 'function') {
  579. if (error) {
  580. process.nextTick(function() {
  581. cb(error);
  582. });
  583. } else
  584. this.once('rekey', cb);
  585. }
  586. return ret;
  587. };
  588. function Session(client, info, localChan) {
  589. this.subtype = undefined;
  590. var ending = false;
  591. var self = this;
  592. var outgoingId = info.sender;
  593. var channel;
  594. var chaninfo = {
  595. type: 'session',
  596. incoming: {
  597. id: localChan,
  598. window: Channel.MAX_WINDOW,
  599. packetSize: Channel.PACKET_SIZE,
  600. state: 'open'
  601. },
  602. outgoing: {
  603. id: info.sender,
  604. window: info.window,
  605. packetSize: info.packetSize,
  606. state: 'open'
  607. }
  608. };
  609. function onREQUEST(info) {
  610. var replied = false;
  611. var accept;
  612. var reject;
  613. if (info.wantReply) {
  614. // "real session" requests will have custom accept behaviors
  615. if (info.request !== 'shell'
  616. && info.request !== 'exec'
  617. && info.request !== 'subsystem') {
  618. accept = function() {
  619. if (replied || ending || channel)
  620. return;
  621. replied = true;
  622. return client._sshstream.channelSuccess(outgoingId);
  623. };
  624. }
  625. reject = function() {
  626. if (replied || ending || channel)
  627. return;
  628. replied = true;
  629. return client._sshstream.channelFailure(outgoingId);
  630. };
  631. }
  632. if (ending) {
  633. reject && reject();
  634. return;
  635. }
  636. switch (info.request) {
  637. // "pre-real session start" requests
  638. case 'env':
  639. if (listenerCount(self, 'env')) {
  640. self.emit('env', accept, reject, {
  641. key: info.key,
  642. val: info.val
  643. });
  644. } else
  645. reject && reject();
  646. break;
  647. case 'pty-req':
  648. if (listenerCount(self, 'pty')) {
  649. self.emit('pty', accept, reject, {
  650. cols: info.cols,
  651. rows: info.rows,
  652. width: info.width,
  653. height: info.height,
  654. term: info.term,
  655. modes: info.modes,
  656. });
  657. } else
  658. reject && reject();
  659. break;
  660. case 'window-change':
  661. if (listenerCount(self, 'window-change')) {
  662. self.emit('window-change', accept, reject, {
  663. cols: info.cols,
  664. rows: info.rows,
  665. width: info.width,
  666. height: info.height
  667. });
  668. } else
  669. reject && reject();
  670. break;
  671. case 'x11-req':
  672. if (listenerCount(self, 'x11')) {
  673. self.emit('x11', accept, reject, {
  674. single: info.single,
  675. protocol: info.protocol,
  676. cookie: info.cookie,
  677. screen: info.screen
  678. });
  679. } else
  680. reject && reject();
  681. break;
  682. // "post-real session start" requests
  683. case 'signal':
  684. if (listenerCount(self, 'signal')) {
  685. self.emit('signal', accept, reject, {
  686. name: info.signal
  687. });
  688. } else
  689. reject && reject();
  690. break;
  691. // XXX: is `auth-agent-req@openssh.com` really "post-real session start"?
  692. case 'auth-agent-req@openssh.com':
  693. if (listenerCount(self, 'auth-agent'))
  694. self.emit('auth-agent', accept, reject);
  695. else
  696. reject && reject();
  697. break;
  698. // "real session start" requests
  699. case 'shell':
  700. if (listenerCount(self, 'shell')) {
  701. accept = function() {
  702. if (replied || ending || channel)
  703. return;
  704. replied = true;
  705. if (info.wantReply)
  706. client._sshstream.channelSuccess(outgoingId);
  707. channel = new Channel(chaninfo, client, { server: true });
  708. channel.subtype = self.subtype = info.request;
  709. return channel;
  710. };
  711. self.emit('shell', accept, reject);
  712. } else
  713. reject && reject();
  714. break;
  715. case 'exec':
  716. if (listenerCount(self, 'exec')) {
  717. accept = function() {
  718. if (replied || ending || channel)
  719. return;
  720. replied = true;
  721. if (info.wantReply)
  722. client._sshstream.channelSuccess(outgoingId);
  723. channel = new Channel(chaninfo, client, { server: true });
  724. channel.subtype = self.subtype = info.request;
  725. return channel;
  726. };
  727. self.emit('exec', accept, reject, {
  728. command: info.command
  729. });
  730. } else
  731. reject && reject();
  732. break;
  733. case 'subsystem':
  734. accept = function() {
  735. if (replied || ending || channel)
  736. return;
  737. replied = true;
  738. if (info.wantReply)
  739. client._sshstream.channelSuccess(outgoingId);
  740. channel = new Channel(chaninfo, client, { server: true });
  741. channel.subtype = self.subtype = (info.request + ':' + info.subsystem);
  742. if (info.subsystem === 'sftp') {
  743. var sftp = new SFTPStream({
  744. server: true,
  745. debug: client._sshstream.debug
  746. });
  747. channel.pipe(sftp).pipe(channel);
  748. return sftp;
  749. } else
  750. return channel;
  751. };
  752. if (info.subsystem === 'sftp' && listenerCount(self, 'sftp'))
  753. self.emit('sftp', accept, reject);
  754. else if (info.subsystem !== 'sftp' && listenerCount(self, 'subsystem')) {
  755. self.emit('subsystem', accept, reject, {
  756. name: info.subsystem
  757. });
  758. } else
  759. reject && reject();
  760. break;
  761. default:
  762. reject && reject();
  763. }
  764. }
  765. function onEOF() {
  766. ending = true;
  767. self.emit('eof');
  768. self.emit('end');
  769. }
  770. function onCLOSE() {
  771. ending = true;
  772. self.emit('close');
  773. }
  774. client._sshstream
  775. .on('CHANNEL_REQUEST:' + localChan, onREQUEST)
  776. .once('CHANNEL_EOF:' + localChan, onEOF)
  777. .once('CHANNEL_CLOSE:' + localChan, onCLOSE);
  778. }
  779. inherits(Session, EventEmitter);
  780. function AuthContext(stream, username, service, method, cb) {
  781. EventEmitter.call(this);
  782. var self = this;
  783. this.username = this.user = username;
  784. this.service = service;
  785. this.method = method;
  786. this._initialResponse = false;
  787. this._finalResponse = false;
  788. this._multistep = false;
  789. this._cbfinal = function(allowed, methodsLeft, isPartial) {
  790. if (!self._finalResponse) {
  791. self._finalResponse = true;
  792. cb(self, allowed, methodsLeft, isPartial);
  793. }
  794. };
  795. this._stream = stream;
  796. }
  797. inherits(AuthContext, EventEmitter);
  798. AuthContext.prototype.accept = function() {
  799. this._cleanup && this._cleanup();
  800. this._initialResponse = true;
  801. this._cbfinal(true);
  802. };
  803. AuthContext.prototype.reject = function(methodsLeft, isPartial) {
  804. this._cleanup && this._cleanup();
  805. this._initialResponse = true;
  806. this._cbfinal(false, methodsLeft, isPartial);
  807. };
  808. var RE_KBINT_SUBMETHODS = /[ \t\r\n]*,[ \t\r\n]*/g;
  809. function KeyboardAuthContext(stream, username, service, method, submethods, cb) {
  810. AuthContext.call(this, stream, username, service, method, cb);
  811. this._multistep = true;
  812. var self = this;
  813. this._cb = undefined;
  814. this._onInfoResponse = function(responses) {
  815. if (self._cb) {
  816. var callback = self._cb;
  817. self._cb = undefined;
  818. callback(responses);
  819. }
  820. };
  821. this.submethods = submethods.split(RE_KBINT_SUBMETHODS);
  822. this.on('abort', function() {
  823. self._cb && self._cb(new Error('Authentication request aborted'));
  824. });
  825. }
  826. inherits(KeyboardAuthContext, AuthContext);
  827. KeyboardAuthContext.prototype._cleanup = function() {
  828. this._stream.removeListener('USERAUTH_INFO_RESPONSE', this._onInfoResponse);
  829. };
  830. KeyboardAuthContext.prototype.prompt = function(prompts, title, instructions,
  831. cb) {
  832. if (!Array.isArray(prompts))
  833. prompts = [ prompts ];
  834. if (typeof title === 'function') {
  835. cb = title;
  836. title = instructions = undefined;
  837. } else if (typeof instructions === 'function') {
  838. cb = instructions;
  839. instructions = undefined;
  840. }
  841. for (var i = 0; i < prompts.length; ++i) {
  842. if (typeof prompts[i] === 'string') {
  843. prompts[i] = {
  844. prompt: prompts[i],
  845. echo: true
  846. };
  847. }
  848. }
  849. this._cb = cb;
  850. this._initialResponse = true;
  851. this._stream.once('USERAUTH_INFO_RESPONSE', this._onInfoResponse);
  852. return this._stream.authInfoReq(title, instructions, prompts);
  853. };
  854. function PKAuthContext(stream, username, service, method, pkInfo, cb) {
  855. AuthContext.call(this, stream, username, service, method, cb);
  856. this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };
  857. this.signature = pkInfo.signature;
  858. var sigAlgo;
  859. if (this.signature) {
  860. // TODO: move key type checking logic to ssh2-streams
  861. switch (pkInfo.keyAlgo) {
  862. case 'ssh-rsa':
  863. case 'ssh-dss':
  864. sigAlgo = 'sha1';
  865. break;
  866. case 'ssh-ed25519':
  867. sigAlgo = null;
  868. break;
  869. case 'ecdsa-sha2-nistp256':
  870. sigAlgo = 'sha256';
  871. break;
  872. case 'ecdsa-sha2-nistp384':
  873. sigAlgo = 'sha384';
  874. break;
  875. case 'ecdsa-sha2-nistp521':
  876. sigAlgo = 'sha512';
  877. break;
  878. }
  879. }
  880. this.sigAlgo = sigAlgo;
  881. this.blob = pkInfo.blob;
  882. }
  883. inherits(PKAuthContext, AuthContext);
  884. PKAuthContext.prototype.accept = function() {
  885. if (!this.signature) {
  886. this._initialResponse = true;
  887. this._stream.authPKOK(this.key.algo, this.key.data);
  888. } else {
  889. AuthContext.prototype.accept.call(this);
  890. }
  891. };
  892. function HostbasedAuthContext(stream, username, service, method, pkInfo, cb) {
  893. AuthContext.call(this, stream, username, service, method, cb);
  894. this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };
  895. this.signature = pkInfo.signature;
  896. var sigAlgo;
  897. if (this.signature) {
  898. // TODO: move key type checking logic to ssh2-streams
  899. switch (pkInfo.keyAlgo) {
  900. case 'ssh-rsa':
  901. case 'ssh-dss':
  902. sigAlgo = 'sha1';
  903. break;
  904. case 'ssh-ed25519':
  905. sigAlgo = null;
  906. break;
  907. case 'ecdsa-sha2-nistp256':
  908. sigAlgo = 'sha256';
  909. break;
  910. case 'ecdsa-sha2-nistp384':
  911. sigAlgo = 'sha384';
  912. break;
  913. case 'ecdsa-sha2-nistp521':
  914. sigAlgo = 'sha512';
  915. break;
  916. }
  917. }
  918. this.sigAlgo = sigAlgo;
  919. this.blob = pkInfo.blob;
  920. this.localHostname = pkInfo.localHostname;
  921. this.localUsername = pkInfo.localUsername;
  922. }
  923. inherits(HostbasedAuthContext, AuthContext);
  924. function PwdAuthContext(stream, username, service, method, password, cb) {
  925. AuthContext.call(this, stream, username, service, method, cb);
  926. this.password = password;
  927. }
  928. inherits(PwdAuthContext, AuthContext);
  929. function openChannel(self, type, opts, cb) {
  930. // ask the client to open a channel for some purpose
  931. // (e.g. a forwarded TCP connection)
  932. var localChan = nextChannel(self);
  933. var initWindow = Channel.MAX_WINDOW;
  934. var maxPacket = Channel.PACKET_SIZE;
  935. var ret = true;
  936. if (localChan === false)
  937. return cb(new Error('No free channels available'));
  938. if (typeof opts === 'function') {
  939. cb = opts;
  940. opts = {};
  941. }
  942. self._channels[localChan] = true;
  943. var sshstream = self._sshstream;
  944. sshstream.once('CHANNEL_OPEN_CONFIRMATION:' + localChan, function(info) {
  945. sshstream.removeAllListeners('CHANNEL_OPEN_FAILURE:' + localChan);
  946. var chaninfo = {
  947. type: type,
  948. incoming: {
  949. id: localChan,
  950. window: initWindow,
  951. packetSize: maxPacket,
  952. state: 'open'
  953. },
  954. outgoing: {
  955. id: info.sender,
  956. window: info.window,
  957. packetSize: info.packetSize,
  958. state: 'open'
  959. }
  960. };
  961. cb(undefined, new Channel(chaninfo, self, { server: true }));
  962. }).once('CHANNEL_OPEN_FAILURE:' + localChan, function(info) {
  963. sshstream.removeAllListeners('CHANNEL_OPEN_CONFIRMATION:' + localChan);
  964. delete self._channels[localChan];
  965. var err = new Error('(SSH) Channel open failure: ' + info.description);
  966. err.reason = info.reason;
  967. err.lang = info.lang;
  968. cb(err);
  969. });
  970. if (type === 'forwarded-tcpip')
  971. ret = sshstream.forwardedTcpip(localChan, initWindow, maxPacket, opts);
  972. else if (type === 'x11')
  973. ret = sshstream.x11(localChan, initWindow, maxPacket, opts);
  974. else if (type === 'forwarded-streamlocal@openssh.com') {
  975. ret = sshstream.openssh_forwardedStreamLocal(localChan,
  976. initWindow,
  977. maxPacket,
  978. opts);
  979. }
  980. return ret;
  981. }
  982. function nextChannel(self) {
  983. // get the next available channel number
  984. // fast path
  985. if (self._curChan < MAX_CHANNEL)
  986. return ++self._curChan;
  987. // slower lookup path
  988. for (var i = 0, channels = self._channels; i < MAX_CHANNEL; ++i)
  989. if (!channels[i])
  990. return i;
  991. return false;
  992. }
  993. Server.createServer = function(cfg, listener) {
  994. return new Server(cfg, listener);
  995. };
  996. Server.KEEPALIVE_INTERVAL = 1000;
  997. Server.KEEPALIVE_CLIENT_INTERVAL = 15000;
  998. Server.KEEPALIVE_CLIENT_COUNT_MAX = 3;
  999. module.exports = Server;
  1000. module.exports.IncomingClient = Client;