UNPKG

67.7 kBMarkdownView Raw
1# Description
2
3SSH2 client and server modules written in pure JavaScript for [node.js](http://nodejs.org/).
4
5Development/testing is done against OpenSSH (8.7 currently).
6
7Changes (breaking or otherwise) in v1.0.0 can be found [here](https://github.com/mscdex/ssh2/issues/935).
8
9# Table of Contents
10
11* [Requirements](#requirements)
12* [Installation](#installation)
13* [Client Examples](#client-examples)
14 * [Execute 'uptime' on a server](#execute-uptime-on-a-server)
15 * [Start an interactive shell session](#start-an-interactive-shell-session)
16 * [Send a raw HTTP request to port 80 on the server](#send-a-raw-http-request-to-port-80-on-the-server)
17 * [Forward local connections to port 8000 on the server to us](#forward-local-connections-to-port-8000-on-the-server-to-us)
18 * [Get a directory listing via SFTP](#get-a-directory-listing-via-sftp)
19 * [Connection hopping](#connection-hopping)
20 * [Forward remote X11 connections](#forward-remote-x11-connections)
21 * [Dynamic (1:1) port forwarding using a SOCKSv5 proxy (using `socksv5`)](#dynamic-11-port-forwarding-using-a-socksv5-proxy-using-socksv5)
22 * [Make HTTP(S) connections easily using a custom http(s).Agent](#make-https-connections-easily-using-a-custom-httpsagent)
23 * [Invoke an arbitrary subsystem (e.g. netconf)](#invoke-an-arbitrary-subsystem)
24* [Server Examples](#server-examples)
25 * [Password and public key authentication and non-interactive (exec) command execution](#password-and-public-key-authentication-and-non-interactive-exec-command-execution)
26 * [SFTP-only server](#sftp-only-server)
27* [API](#api)
28 * [Client](#client)
29 * [Client events](#client-events)
30 * [Client methods](#client-methods)
31 * [Server](#server)
32 * [Server events](#server-events)
33 * [Server methods](#server-methods)
34 * [Connection events](#connection-events)
35 * [Connection methods](#connection-methods)
36 * [Session events](#session-events)
37 * [Channel](#channel)
38 * [Pseudo-TTY settings](#pseudo-tty-settings)
39 * [Terminal modes](#terminal-modes)
40 * [HTTPAgent](#httpagent)
41 * [HTTPAgent methods](#httpagent-methods)
42 * [HTTPSAgent](#httpsagent)
43 * [HTTPSAgent methods](#httpsagent-methods)
44 * [Utilities](#utilities)
45
46## Requirements
47
48* [node.js](http://nodejs.org/) -- v10.16.0 or newer
49 * node v12.0.0 or newer for Ed25519 key support
50* (Optional) [`cpu-features`](https://github.com/mscdex/cpu-features) is set as an optional package dependency (you do not need to install it explicitly/separately from `ssh2`) that will be automatically built and used if possible. See the project's documentation for its own requirements.
51 * This addon is currently used to help generate an optimal default cipher list
52
53## Installation
54
55 npm install ssh2
56
57## Client Examples
58
59### Execute 'uptime' on a server
60
61```js
62const { readFileSync } = require('fs');
63
64const { Client } = require('ssh2');
65
66const conn = new Client();
67conn.on('ready', () => {
68 console.log('Client :: ready');
69 conn.exec('uptime', (err, stream) => {
70 if (err) throw err;
71 stream.on('close', (code, signal) => {
72 console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
73 conn.end();
74 }).on('data', (data) => {
75 console.log('STDOUT: ' + data);
76 }).stderr.on('data', (data) => {
77 console.log('STDERR: ' + data);
78 });
79 });
80}).connect({
81 host: '192.168.100.100',
82 port: 22,
83 username: 'frylock',
84 privateKey: readFileSync('/path/to/my/key')
85});
86
87// example output:
88// Client :: ready
89// STDOUT: 17:41:15 up 22 days, 18:09, 1 user, load average: 0.00, 0.01, 0.05
90//
91// Stream :: exit :: code: 0, signal: undefined
92// Stream :: close
93```
94
95### Start an interactive shell session
96
97```js
98const { readFileSync } = require('fs');
99
100const { Client } = require('ssh2');
101
102const conn = new Client();
103conn.on('ready', () => {
104 console.log('Client :: ready');
105 conn.shell((err, stream) => {
106 if (err) throw err;
107 stream.on('close', () => {
108 console.log('Stream :: close');
109 conn.end();
110 }).on('data', (data) => {
111 console.log('OUTPUT: ' + data);
112 });
113 stream.end('ls -l\nexit\n');
114 });
115}).connect({
116 host: '192.168.100.100',
117 port: 22,
118 username: 'frylock',
119 privateKey: readFileSync('/path/to/my/key')
120});
121
122// example output:
123// Client :: ready
124// STDOUT: Last login: Sun Jun 15 09:37:21 2014 from 192.168.100.100
125//
126// STDOUT: ls -l
127// exit
128//
129// STDOUT: frylock@athf:~$ ls -l
130//
131// STDOUT: total 8
132//
133// STDOUT: drwxr-xr-x 2 frylock frylock 4096 Nov 18 2012 mydir
134//
135// STDOUT: -rw-r--r-- 1 frylock frylock 25 Apr 11 2013 test.txt
136//
137// STDOUT: frylock@athf:~$ exit
138//
139// STDOUT: logout
140//
141// Stream :: close
142```
143
144### Send a raw HTTP request to port 80 on the server
145
146```js
147const { Client } = require('ssh2');
148
149const conn = new Client();
150conn.on('ready', () => {
151 console.log('Client :: ready');
152 conn.forwardOut('192.168.100.102', 8000, '127.0.0.1', 80, (err, stream) => {
153 if (err) throw err;
154 stream.on('close', () => {
155 console.log('TCP :: CLOSED');
156 conn.end();
157 }).on('data', (data) => {
158 console.log('TCP :: DATA: ' + data);
159 }).end([
160 'HEAD / HTTP/1.1',
161 'User-Agent: curl/7.27.0',
162 'Host: 127.0.0.1',
163 'Accept: */*',
164 'Connection: close',
165 '',
166 ''
167 ].join('\r\n'));
168 });
169}).connect({
170 host: '192.168.100.100',
171 port: 22,
172 username: 'frylock',
173 password: 'nodejsrules'
174});
175
176// example output:
177// Client :: ready
178// TCP :: DATA: HTTP/1.1 200 OK
179// Date: Thu, 15 Nov 2012 13:52:58 GMT
180// Server: Apache/2.2.22 (Ubuntu)
181// X-Powered-By: PHP/5.4.6-1ubuntu1
182// Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT
183// Content-Encoding: gzip
184// Vary: Accept-Encoding
185// Connection: close
186// Content-Type: text/html; charset=UTF-8
187//
188//
189// TCP :: CLOSED
190```
191
192### Forward local connections to port 8000 on the server to us
193
194```js
195const { Client } = require('ssh2');
196
197const conn = new Client();
198conn.on('ready', () => {
199 console.log('Client :: ready');
200 conn.forwardIn('127.0.0.1', 8000, (err) => {
201 if (err) throw err;
202 console.log('Listening for connections on server on port 8000!');
203 });
204}).on('tcp connection', (info, accept, reject) => {
205 console.log('TCP :: INCOMING CONNECTION:');
206 console.dir(info);
207 accept().on('close', () => {
208 console.log('TCP :: CLOSED');
209 }).on('data', (data) => {
210 console.log('TCP :: DATA: ' + data);
211 }).end([
212 'HTTP/1.1 404 Not Found',
213 'Date: Thu, 15 Nov 2012 02:07:58 GMT',
214 'Server: ForwardedConnection',
215 'Content-Length: 0',
216 'Connection: close',
217 '',
218 ''
219 ].join('\r\n'));
220}).connect({
221 host: '192.168.100.100',
222 port: 22,
223 username: 'frylock',
224 password: 'nodejsrules'
225});
226
227// example output:
228// Client :: ready
229// Listening for connections on server on port 8000!
230// (.... then from another terminal on the server: `curl -I http://127.0.0.1:8000`)
231// TCP :: INCOMING CONNECTION: { destIP: '127.0.0.1',
232// destPort: 8000,
233// srcIP: '127.0.0.1',
234// srcPort: 41969 }
235// TCP DATA: HEAD / HTTP/1.1
236// User-Agent: curl/7.27.0
237// Host: 127.0.0.1:8000
238// Accept: */*
239//
240//
241// TCP :: CLOSED
242```
243
244### Get a directory listing via SFTP
245
246```js
247const { Client } = require('ssh2');
248
249const conn = new Client();
250conn.on('ready', () => {
251 console.log('Client :: ready');
252 conn.sftp((err, sftp) => {
253 if (err) throw err;
254 sftp.readdir('foo', (err, list) => {
255 if (err) throw err;
256 console.dir(list);
257 conn.end();
258 });
259 });
260}).connect({
261 host: '192.168.100.100',
262 port: 22,
263 username: 'frylock',
264 password: 'nodejsrules'
265});
266
267// example output:
268// Client :: ready
269// [ { filename: 'test.txt',
270// longname: '-rw-r--r-- 1 frylock frylock 12 Nov 18 11:05 test.txt',
271// attrs:
272// { size: 12,
273// uid: 1000,
274// gid: 1000,
275// mode: 33188,
276// atime: 1353254750,
277// mtime: 1353254744 } },
278// { filename: 'mydir',
279// longname: 'drwxr-xr-x 2 frylock frylock 4096 Nov 18 15:03 mydir',
280// attrs:
281// { size: 1048576,
282// uid: 1000,
283// gid: 1000,
284// mode: 16877,
285// atime: 1353269007,
286// mtime: 1353269007 } } ]
287```
288
289### Connection hopping
290
291```js
292const { Client } = require('ssh2');
293
294const conn1 = new Client();
295const conn2 = new Client();
296
297// Checks uptime on 10.1.1.40 via 192.168.1.1
298
299conn1.on('ready', () => {
300 console.log('FIRST :: connection ready');
301 // Alternatively, you could use something like netcat or socat with exec()
302 // instead of forwardOut(), depending on what the server allows
303 conn1.forwardOut('127.0.0.1', 12345, '10.1.1.40', 22, (err, stream) => {
304 if (err) {
305 console.log('FIRST :: forwardOut error: ' + err);
306 return conn1.end();
307 }
308 conn2.connect({
309 sock: stream,
310 username: 'user2',
311 password: 'password2',
312 });
313 });
314}).connect({
315 host: '192.168.1.1',
316 username: 'user1',
317 password: 'password1',
318});
319
320conn2.on('ready', () => {
321 // This connection is the one to 10.1.1.40
322
323 console.log('SECOND :: connection ready');
324 conn2.exec('uptime', (err, stream) => {
325 if (err) {
326 console.log('SECOND :: exec error: ' + err);
327 return conn1.end();
328 }
329 stream.on('close', () => {
330 conn1.end(); // close parent (and this) connection
331 }).on('data', (data) => {
332 console.log(data.toString());
333 });
334 });
335});
336```
337
338### Forward remote X11 connections
339
340```js
341const { Socket } = require('net');
342
343const { Client } = require('ssh2');
344
345const conn = new Client();
346
347conn.on('x11', (info, accept, reject) => {
348 const xserversock = new net.Socket();
349 xserversock.on('connect', () => {
350 const xclientsock = accept();
351 xclientsock.pipe(xserversock).pipe(xclientsock);
352 });
353 // connects to localhost:0.0
354 xserversock.connect(6000, 'localhost');
355});
356
357conn.on('ready', () => {
358 conn.exec('xeyes', { x11: true }, (err, stream) => {
359 if (err) throw err;
360 let code = 0;
361 stream.on('close', () => {
362 if (code !== 0)
363 console.log('Do you have X11 forwarding enabled on your SSH server?');
364 conn.end();
365 }).on('exit', (exitcode) => {
366 code = exitcode;
367 });
368 });
369}).connect({
370 host: '192.168.1.1',
371 username: 'foo',
372 password: 'bar'
373});
374```
375
376### Dynamic (1:1) port forwarding using a SOCKSv5 proxy (using [socksv5](https://github.com/mscdex/socksv5))
377
378```js
379const socks = require('socksv5');
380const { Client } = require('ssh2');
381
382const sshConfig = {
383 host: '192.168.100.1',
384 port: 22,
385 username: 'nodejs',
386 password: 'rules'
387};
388
389socks.createServer((info, accept, deny) => {
390 // NOTE: you could just use one ssh2 client connection for all forwards, but
391 // you could run into server-imposed limits if you have too many forwards open
392 // at any given time
393 const conn = new Client();
394 conn.on('ready', () => {
395 conn.forwardOut(info.srcAddr,
396 info.srcPort,
397 info.dstAddr,
398 info.dstPort,
399 (err, stream) => {
400 if (err) {
401 conn.end();
402 return deny();
403 }
404
405 const clientSocket = accept(true);
406 if (clientSocket) {
407 stream.pipe(clientSocket).pipe(stream).on('close', () => {
408 conn.end();
409 });
410 } else {
411 conn.end();
412 }
413 });
414 }).on('error', (err) => {
415 deny();
416 }).connect(sshConfig);
417}).listen(1080, 'localhost', () => {
418 console.log('SOCKSv5 proxy server started on port 1080');
419}).useAuth(socks.auth.None());
420
421// test with cURL:
422// curl -i --socks5 localhost:1080 google.com
423```
424
425### Make HTTP(S) connections easily using a custom http(s).Agent
426
427```js
428const http = require('http');
429
430const { Client, HTTPAgent, HTTPSAgent } = require('ssh2');
431
432const sshConfig = {
433 host: '192.168.100.1',
434 port: 22,
435 username: 'nodejs',
436 password: 'rules'
437};
438
439// Use `HTTPSAgent` instead for an HTTPS request
440const agent = new HTTPAgent(sshConfig);
441http.get({
442 host: '192.168.200.1',
443 agent,
444 headers: { Connection: 'close' }
445}, (res) => {
446 console.log(res.statusCode);
447 console.dir(res.headers);
448 res.resume();
449});
450```
451
452
453### Invoke an arbitrary subsystem
454
455```js
456const { Client } = require('ssh2');
457
458const xmlhello = `
459 <?xml version="1.0" encoding="UTF-8"?>
460 <hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
461 <capabilities>
462 <capability>urn:ietf:params:netconf:base:1.0</capability>
463 </capabilities>
464 </hello>]]>]]>`;
465
466const conn = new Client();
467
468conn.on('ready', () => {
469 console.log('Client :: ready');
470 conn.subsys('netconf', (err, stream) => {
471 if (err) throw err;
472 stream.on('data', (data) => {
473 console.log(data);
474 }).write(xmlhello);
475 });
476}).connect({
477 host: '1.2.3.4',
478 port: 22,
479 username: 'blargh',
480 password: 'honk'
481});
482```
483
484## Server Examples
485
486### Password and public key authentication and non-interactive (exec) command execution
487
488```js
489const { timingSafeEqual } = require('crypto');
490const { readFileSync } = require('fs');
491const { inspect } = require('util');
492
493const { utils: { parseKey }, Server } = require('ssh2');
494
495const allowedUser = Buffer.from('foo');
496const allowedPassword = Buffer.from('bar');
497const allowedPubKey = parseKey(readFileSync('foo.pub'));
498
499function checkValue(input, allowed) {
500 const autoReject = (input.length !== allowed.length);
501 if (autoReject) {
502 // Prevent leaking length information by always making a comparison with the
503 // same input when lengths don't match what we expect ...
504 allowed = input;
505 }
506 const isMatch = timingSafeEqual(input, allowed);
507 return (!autoReject && isMatch);
508}
509
510new Server({
511 hostKeys: [readFileSync('host.key')]
512}, (client) => {
513 console.log('Client connected!');
514
515 client.on('authentication', (ctx) => {
516 let allowed = true;
517 if (!checkValue(Buffer.from(ctx.username), allowedUser))
518 allowed = false;
519
520 switch (ctx.method) {
521 case 'password':
522 if (!checkValue(Buffer.from(ctx.password), allowedPassword))
523 return ctx.reject();
524 break;
525 case 'publickey':
526 if (ctx.key.algo !== allowedPubKey.type
527 || !checkValue(ctx.key.data, allowedPubKey.getPublicSSH())
528 || (ctx.signature && allowedPubKey.verify(ctx.blob, ctx.signature) !== true)) {
529 return ctx.reject();
530 }
531 break;
532 default:
533 return ctx.reject();
534 }
535
536 if (allowed)
537 ctx.accept();
538 else
539 ctx.reject();
540 }).on('ready', () => {
541 console.log('Client authenticated!');
542
543 client.on('session', (accept, reject) => {
544 const session = accept();
545 session.once('exec', (accept, reject, info) => {
546 console.log('Client wants to execute: ' + inspect(info.command));
547 const stream = accept();
548 stream.stderr.write('Oh no, the dreaded errors!\n');
549 stream.write('Just kidding about the errors!\n');
550 stream.exit(0);
551 stream.end();
552 });
553 });
554 }).on('close', () => {
555 console.log('Client disconnected');
556 });
557}).listen(0, '127.0.0.1', function() {
558 console.log('Listening on port ' + this.address().port);
559});
560```
561
562### SFTP-only server
563
564```js
565const { timingSafeEqual } = require('crypto');
566const { readFileSync } = require('fs');
567const { inspect } = require('util');
568
569const {
570 Server,
571 sftp: {
572 OPEN_MODE,
573 STATUS_CODE,
574 },
575} = require('ssh2');
576
577const allowedUser = Buffer.from('foo');
578const allowedPassword = Buffer.from('bar');
579
580function checkValue(input, allowed) {
581 const autoReject = (input.length !== allowed.length);
582 if (autoReject) {
583 // Prevent leaking length information by always making a comparison with the
584 // same input when lengths don't match what we expect ...
585 allowed = input;
586 }
587 const isMatch = timingSafeEqual(input, allowed);
588 return (!autoReject && isMatch);
589}
590
591// This simple SFTP server implements file uploading where the contents get
592// ignored ...
593
594new ssh2.Server({
595 hostKeys: [readFileSync('host.key')]
596}, (client) => {
597 console.log('Client connected!');
598
599 client.on('authentication', (ctx) => {
600 let allowed = true;
601 if (!checkValue(Buffer.from(ctx.username), allowedUser))
602 allowed = false;
603
604 switch (ctx.method) {
605 case 'password':
606 if (!checkValue(Buffer.from(ctx.password), allowedPassword))
607 return ctx.reject();
608 break;
609 default:
610 return ctx.reject();
611 }
612
613 if (allowed)
614 ctx.accept();
615 else
616 ctx.reject();
617 }).on('ready', () => {
618 console.log('Client authenticated!');
619
620 client.on('session', (accept, reject) => {
621 const session = accept();
622 session.on('sftp', (accept, reject) => {
623 console.log('Client SFTP session');
624 const openFiles = new Map();
625 let handleCount = 0;
626 const sftp = accept();
627 sftp.on('OPEN', (reqid, filename, flags, attrs) => {
628 // Only allow opening /tmp/foo.txt for writing
629 if (filename !== '/tmp/foo.txt' || !(flags & OPEN_MODE.WRITE))
630 return sftp.status(reqid, STATUS_CODE.FAILURE);
631
632 // Create a fake handle to return to the client, this could easily
633 // be a real file descriptor number for example if actually opening
634 // a file on disk
635 const handle = Buffer.alloc(4);
636 openFiles.set(handleCount, true);
637 handle.writeUInt32BE(handleCount++, 0);
638
639 console.log('Opening file for write')
640 sftp.handle(reqid, handle);
641 }).on('WRITE', (reqid, handle, offset, data) => {
642 if (handle.length !== 4
643 || !openFiles.has(handle.readUInt32BE(0))) {
644 return sftp.status(reqid, STATUS_CODE.FAILURE);
645 }
646
647 // Fake the write operation
648 sftp.status(reqid, STATUS_CODE.OK);
649
650 console.log('Write to file at offset ${offset}: ${inspect(data)}');
651 }).on('CLOSE', (reqid, handle) => {
652 let fnum;
653 if (handle.length !== 4
654 || !openFiles.has(fnum = handle.readUInt32BE(0))) {
655 return sftp.status(reqid, STATUS_CODE.FAILURE);
656 }
657
658 console.log('Closing file');
659 openFiles.delete(fnum);
660
661 sftp.status(reqid, STATUS_CODE.OK);
662 });
663 });
664 });
665 }).on('close', () => {
666 console.log('Client disconnected');
667 });
668}).listen(0, '127.0.0.1', function() {
669 console.log('Listening on port ' + this.address().port);
670});
671```
672
673You can find more examples in the `examples` directory of this repository.
674
675## API
676
677`require('ssh2').Client` is the **_Client_** constructor.
678
679`require('ssh2').Server` is the **_Server_** constructor.
680
681`require('ssh2').utils` is an object containing some useful [utilities](#utilities).
682
683`require('ssh2').HTTPAgent` is an [`http.Agent`](https://nodejs.org/docs/latest/api/http.html#http_class_http_agent) constructor.
684
685`require('ssh2').HTTPSAgent` is an [`https.Agent`](https://nodejs.org/docs/latest/api/https.html#https_class_https_agent) constructor. Its API is the same as `HTTPAgent` except it's for HTTPS connections.
686
687### Agent-related
688
689`require('ssh2').AgentProtocol` is a Duplex stream [class](#agentprotocol) that aids in communicating over the OpenSSH agent protocol.
690
691`require('ssh2').BaseAgent` is a base [class](#baseagent) for creating custom authentication agents.
692
693`require('ssh2').createAgent` is a helper [function](#createagent) that creates a new agent instance using the same logic as the `agent` configuration option: if the platform is Windows and it's the value "pageant", it creates a `PageantAgent`, otherwise if it's not a path to a Windows pipe it creates a `CygwinAgent`. In all other cases, it creates an `OpenSSHAgent`.
694
695`require('ssh2').CygwinAgent` is an agent [class](#cygwinagent) implementation that communicates with agents in a Cygwin environment.
696
697`require('ssh2').OpenSSHAgent` is an agent [class](#opensshagent) implementation that communicates with OpenSSH agents over a UNIX socket.
698
699`require('ssh2').PageantAgent` is an agent [class](#pageantagent) implementation that communicates with Pageant agent processes.
700
701### Client
702
703#### Client events
704
705* **banner**(< _string_ >message, < _string_ >language) - A notice was sent by the server upon connection.
706
707* **change password**(< _string_ >prompt, < _function_ >done) - If using password-based user authentication, the server has requested that the user's password be changed. Call `done` with the new password.
708
709* **close**() - The socket was closed.
710
711* **end**() - The socket was disconnected.
712
713* **error**(< _Error_ >err) - An error occurred. A 'level' property indicates 'client-socket' for socket-level errors and 'client-ssh' for SSH disconnection messages. In the case of 'client-ssh' messages, there may be a 'description' property that provides more detail.
714
715* **handshake**(< _object_ >negotiated) - Emitted when a handshake has completed (either initial or rekey). `negotiated` contains the negotiated details of the handshake and is of the form:
716
717```js
718 // In this particular case `mac` is empty because there is no separate MAC
719 // because it's integrated into AES in GCM mode
720 { kex: 'ecdh-sha2-nistp256',
721 srvHostKey: 'rsa-sha2-512',
722 cs: { // Client to server algorithms
723 cipher: 'aes128-gcm',
724 mac: '',
725 compress: 'none',
726 lang: ''
727 },
728 sc: { // Server to client algorithms
729 cipher: 'aes128-gcm',
730 mac: '',
731 compress: 'none',
732 lang: ''
733 }
734 }
735```
736
737* **hostkeys**(< _array_ >keys) - Emitted when the server announces its available host keys. `keys` is the list of parsed (using [`parseKey()`](#utilities)) host public keys.
738
739* **keyboard-interactive**(< _string_ >name, < _string_ >instructions, < _string_ >instructionsLang, < _array_ >prompts, < _function_ >finish) - The server is asking for replies to the given `prompts` for keyboard-interactive user authentication. `name` is generally what you'd use as a window title (for GUI apps). `prompts` is an array of `{ prompt: 'Password: ', echo: false }` style objects (here `echo` indicates whether user input should be displayed on the screen). The answers for all prompts must be provided as an array of strings and passed to `finish` when you are ready to continue. Note: It's possible for the server to come back and ask more questions.
740
741* **ready**() - Authentication was successful.
742
743* **rekey**() - Emitted when a rekeying operation has completed (either client or server-initiated).
744
745* **tcp connection**(< _object_ >details, < _function_ >accept, < _function_ >reject) - An incoming forwarded TCP connection is being requested. Calling `accept` accepts the connection and returns a `Channel` object. Calling `reject` rejects the connection and no further action is needed. `details` contains:
746
747 * **destIP** - _string_ - The remote IP the connection was received on (given in earlier call to `forwardIn()`).
748
749 * **destPort** - _integer_ - The remote port the connection was received on (given in earlier call to `forwardIn()`).
750
751 * **srcIP** - _string_ - The originating IP of the connection.
752
753 * **srcPort** - _integer_ - The originating port of the connection.
754
755* **unix connection**(< _object_ >details, < _function_ >accept, < _function_ >reject) - An incoming forwarded UNIX socket connection is being requested. Calling `accept` accepts the connection and returns a `Channel` object. Calling `reject` rejects the connection and no further action is needed. `details` contains:
756
757 * **socketPath** - _string_ - The originating UNIX socket path of the connection.
758
759* **x11**(< _object_ >details, < _function_ >accept, < _function_ >reject) - An incoming X11 connection is being requested. Calling `accept` accepts the connection and returns a `Channel` object. Calling `reject` rejects the connection and no further action is needed. `details` contains:
760
761 * **srcIP** - _string_ - The originating IP of the connection.
762
763 * **srcPort** - _integer_ - The originating port of the connection.
764
765#### Client methods
766
767* **(constructor)**() - Creates and returns a new Client instance.
768
769* **connect**(< _object_ >config) - _(void)_ - Attempts a connection to a server using the information given in `config`:
770
771 * **agent** - _string_ - Path to ssh-agent's UNIX socket for ssh-agent-based user authentication. **Windows users: set to 'pageant' for authenticating with Pageant or (actual) path to a cygwin "UNIX socket."** **Default:** (none)
772
773 * **agentForward** - _boolean_ - Set to `true` to use OpenSSH agent forwarding (`auth-agent@openssh.com`) for the life of the connection. `agent` must also be set to use this feature. **Default:** `false`
774
775 * **algorithms** - _object_ - This option allows you to explicitly override the default transport layer algorithms used for the connection. The value for each category must either be an array of valid algorithm names to set an exact list (with the most preferable first) or an object containing `append`, `prepend`, and/or `remove` properties that each contain an _array_ of algorithm names or RegExps to match to adjust default lists for each category. Valid keys:
776
777 * **cipher** - _mixed_ - Ciphers.
778 * Default list (in order from most to least preferable):
779 * `chacha20-poly1305@openssh.com` (priority of chacha20-poly1305 may vary depending upon CPU and/or optional binding availability)
780 * `aes128-gcm`
781 * `aes128-gcm@openssh.com`
782 * `aes256-gcm`
783 * `aes256-gcm@openssh.com`
784 * `aes128-ctr`
785 * `aes192-ctr`
786 * `aes256-ctr`
787 * Other supported names:
788 * `3des-cbc`
789 * `aes256-cbc`
790 * `aes192-cbc`
791 * `aes128-cbc`
792 * `arcfour256`
793 * `arcfour128`
794 * `arcfour`
795 * `blowfish-cbc`
796 * `cast128-cbc`
797
798 * **compress** - _mixed_ - Compression algorithms.
799 * Default list (in order from most to least preferable):
800 * `none`
801 * `zlib@openssh.com`
802 * `zlib`
803 * Other supported names:
804
805 * **hmac** - _mixed_ - (H)MAC algorithms.
806 * Default list (in order from most to least preferable):
807 * `hmac-sha2-256-etm@openssh.com`
808 * `hmac-sha2-512-etm@openssh.com`
809 * `hmac-sha1-etm@openssh.com`
810 * `hmac-sha2-256`
811 * `hmac-sha2-512`
812 * `hmac-sha1`
813 * Other supported names:
814 * `hmac-md5`
815 * `hmac-sha2-256-96`
816 * `hmac-sha2-512-96`
817 * `hmac-ripemd160`
818 * `hmac-sha1-96`
819 * `hmac-md5-96`
820
821 * **kex** - _mixed_ - Key exchange algorithms.
822 * Default list (in order from most to least preferable):
823 * `curve25519-sha256` (node v14.0.0+)
824 * `curve25519-sha256@libssh.org` (node v14.0.0+)
825 * `ecdh-sha2-nistp256`
826 * `ecdh-sha2-nistp384`
827 * `ecdh-sha2-nistp521`
828 * `diffie-hellman-group-exchange-sha256`
829 * `diffie-hellman-group14-sha256`
830 * `diffie-hellman-group15-sha512`
831 * `diffie-hellman-group16-sha512`
832 * `diffie-hellman-group17-sha512`
833 * `diffie-hellman-group18-sha512`
834 * Other supported names:
835 * `diffie-hellman-group-exchange-sha1`
836 * `diffie-hellman-group14-sha1`
837 * `diffie-hellman-group1-sha1`
838
839 * **serverHostKey** - _mixed_ - Server host key formats.
840 * Default list (in order from most to least preferable):
841 * `ssh-ed25519` (node v12.0.0+)
842 * `ecdsa-sha2-nistp256`
843 * `ecdsa-sha2-nistp384`
844 * `ecdsa-sha2-nistp521`
845 * `rsa-sha2-512`
846 * `rsa-sha2-256`
847 * `ssh-rsa`
848 * Other supported names:
849 * `ssh-dss`
850
851 * **authHandler** - _mixed_ - Either an array of objects as described below or a function with parameters `(methodsLeft, partialSuccess, callback)` where `methodsLeft` and `partialSuccess` are `null` on the first authentication attempt, otherwise are an array and boolean respectively. Return or call `callback()` with either the name of the authentication method or an object containing the method name along with method-specific details to try next (return/pass `false` to signal no more methods to try). Valid method names are: `'none', 'password', 'publickey', 'agent', 'keyboard-interactive', 'hostbased'`. **Default:** function that follows a set method order: None -> Password -> Private Key -> Agent (-> keyboard-interactive if `tryKeyboard` is `true`) -> Hostbased
852
853 * When returning or calling `callback()` with an object, it can take one of the following forms:
854
855 ```js
856 {
857 type: 'none',
858 username: 'foo',
859 }
860 ```
861
862 ```js
863 {
864 type: 'password'
865 username: 'foo',
866 password: 'bar',
867 }
868 ```
869
870 ```js
871 {
872 type: 'publickey'
873 username: 'foo',
874 // Can be a string, Buffer, or parsed key containing a private key
875 key: ...,
876 // `passphrase` only required for encrypted keys
877 passphrase: ...,
878 }
879 ```
880
881 ```js
882 {
883 type: 'hostbased'
884 username: 'foo',
885 localHostname: 'baz',
886 localUsername: 'quux',
887 // Can be a string, Buffer, or parsed key containing a private key
888 key: ...,
889 // `passphrase` only required for encrypted keys
890 passphrase: ...,
891 }
892 ```
893
894 ```js
895 {
896 type: 'agent'
897 username: 'foo',
898 // Can be a string that is interpreted exactly like the `agent`
899 // connection config option or can be a custom agent
900 // object/instance that extends and implements `BaseAgent`
901 agent: ...,
902 }
903 ```
904
905 ```js
906 {
907 type: 'keyboard-interactive'
908 username: 'foo',
909 // This works exactly the same way as a 'keyboard-interactive'
910 // Client event handler
911 prompt: (name, instructions, instructionsLang, prompts, finish) => {
912 // ...
913 },
914 }
915 ```
916
917 * **debug** - _function_ - Set this to a function that receives a single string argument to get detailed (local) debug information. **Default:** (none)
918
919 * **forceIPv4** - _boolean_ - Only connect via resolved IPv4 address for `host`. **Default:** `false`
920
921 * **forceIPv6** - _boolean_ - Only connect via resolved IPv6 address for `host`. **Default:** `false`
922
923 * **host** - _string_ - Hostname or IP address of the server. **Default:** `'localhost'`
924
925 * **hostHash** - _string_ - Any valid hash algorithm supported by node. The host's key is hashed using this algorithm and passed to the **hostVerifier** function as a hex string. **Default:** (none)
926
927 * **hostVerifier** - _function_ - Function with parameters `(hashedKey[, callback])` where `hashedKey` is a string hex hash of the host's key for verification purposes. Return `true` to continue with the handshake or `false` to reject and disconnect, or call `callback()` with `true` or `false` if you need to perform asynchronous verification. **Default:** (auto-accept if `hostVerifier` is not set)
928
929 * **keepaliveCountMax** - _integer_ - How many consecutive, unanswered SSH-level keepalive packets that can be sent to the server before disconnection (similar to OpenSSH's ServerAliveCountMax config option). **Default:** `3`
930
931 * **keepaliveInterval** - _integer_ - How often (in milliseconds) to send SSH-level keepalive packets to the server (in a similar way as OpenSSH's ServerAliveInterval config option). Set to 0 to disable. **Default:** `0`
932
933 * **localAddress** - _string_ - IP address of the network interface to use to connect to the server. **Default:** (none -- determined by OS)
934
935 * **localHostname** - _string_ - Along with **localUsername** and **privateKey**, set this to a non-empty string for hostbased user authentication. **Default:** (none)
936
937 * **localPort** - _string_ - The local port number to connect from. **Default:** (none -- determined by OS)
938
939 * **localUsername** - _string_ - Along with **localHostname** and **privateKey**, set this to a non-empty string for hostbased user authentication. **Default:** (none)
940
941 * **passphrase** - _string_ - For an encrypted `privateKey`, this is the passphrase used to decrypt it. **Default:** (none)
942
943 * **password** - _string_ - Password for password-based user authentication. **Default:** (none)
944
945 * **port** - _integer_ - Port number of the server. **Default:** `22`
946
947 * **privateKey** - _mixed_ - _Buffer_ or _string_ that contains a private key for either key-based or hostbased user authentication (OpenSSH format). **Default:** (none)
948
949 * **readyTimeout** - _integer_ - How long (in milliseconds) to wait for the SSH handshake to complete. **Default:** `20000`
950
951 * **sock** - _ReadableStream_ - A _ReadableStream_ to use for communicating with the server instead of creating and using a new TCP connection (useful for connection hopping).
952
953 * **strictVendor** - _boolean_ - Performs a strict server vendor check before sending vendor-specific requests, etc. (e.g. check for OpenSSH server when using `openssh_noMoreSessions()`) **Default:** `true`
954
955 * **tryKeyboard** - _boolean_ - Try keyboard-interactive user authentication if primary user authentication method fails. If you set this to `true`, you need to handle the `keyboard-interactive` event. **Default:** `false`
956
957 * **username** - _string_ - Username for authentication. **Default:** (none)
958
959* **end**() - _(void)_ - Disconnects the socket.
960
961* **exec**(< _string_ >command[, < _object_ >options], < _function_ >callback) - _(void)_ - Executes `command` on the server. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. Valid `options` properties are:
962
963 * **env** - _object_ - An environment to use for the execution of the command.
964
965 * **pty** - _mixed_ - Set to `true` to allocate a pseudo-tty with defaults, or an object containing specific pseudo-tty settings (see 'Pseudo-TTY settings'). Setting up a pseudo-tty can be useful when working with remote processes that expect input from an actual terminal (e.g. sudo's password prompt).
966
967 * **x11** - _mixed_ - Set to `true` to use defaults below, set to a number to specify a specific screen number, or an object with the following valid properties:
968
969 * **cookie** - _mixed_ - The authentication cookie. Can be a hex _string_ or a _Buffer_ containing the raw cookie value (which will be converted to a hex string). **Default:** (random 16 byte value)
970
971 * **protocol** - _string_ - The authentication protocol name. **Default:** `'MIT-MAGIC-COOKIE-1'`
972
973 * **screen** - _number_ - Screen number to use **Default:** `0`
974
975 * **single** - _boolean_ - Allow just a single connection? **Default:** `false`
976
977* **forwardIn**(< _string_ >remoteAddr, < _integer_ >remotePort, < _function_ >callback) - _(void)_ - Bind to `remoteAddr` on `remotePort` on the server and forward incoming TCP connections. `callback` has 2 parameters: < _Error_ >err, < _integer_ >port (`port` is the assigned port number if `remotePort` was 0). Here are some special values for `remoteAddr` and their associated binding behaviors:
978
979 * '' - Connections are to be accepted on all protocol families supported by the server.
980
981 * '0.0.0.0' - Listen on all IPv4 addresses.
982
983 * '::' - Listen on all IPv6 addresses.
984
985 * 'localhost' - Listen on all protocol families supported by the server on loopback addresses only.
986
987 * '127.0.0.1' and '::1' - Listen on the loopback interfaces for IPv4 and IPv6, respectively.
988
989* **forwardOut**(< _string_ >srcIP, < _integer_ >srcPort, < _string_ >dstIP, < _integer_ >dstPort, < _function_ >callback) - _(void)_ - Open a connection with `srcIP` and `srcPort` as the originating address and port and `dstIP` and `dstPort` as the remote destination address and port. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream.
990
991* **openssh_forwardInStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - OpenSSH extension that binds to a UNIX domain socket at `socketPath` on the server and forwards incoming connections. `callback` has 1 parameter: < _Error_ >err.
992
993* **openssh_forwardOutStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - OpenSSH extension that opens a connection to a UNIX domain socket at `socketPath` on the server. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream.
994
995* **openssh_noMoreSessions**(< _function_ >callback) - _(void)_ - OpenSSH extension that sends a request to reject any new sessions (e.g. exec, shell, sftp, subsys) for this connection. `callback` has 1 parameter: < _Error_ >err.
996
997* **openssh_unforwardInStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - OpenSSH extension that unbinds from a UNIX domain socket at `socketPath` on the server and stops forwarding incoming connections. `callback` has 1 parameter: < _Error_ >err.
998
999* **rekey**([< _function_ >callback]) - _(void)_ - Initiates a rekey with the server. If `callback` is supplied, it is added as a one-time handler for the `rekey` event.
1000
1001* **sftp**(< _function_ >callback) - _(void)_ - Starts an SFTP session. `callback` has 2 parameters: < _Error_ >err, < _SFTP_ >sftp. For methods available on `sftp`, see the [`SFTP` client documentation](https://github.com/mscdex/ssh2/blob/master/SFTP.md).
1002
1003* **shell**([[< _mixed_ >window,] < _object_ >options]< _function_ >callback) - _(void)_ - Starts an interactive shell session on the server, with an optional `window` object containing pseudo-tty settings (see 'Pseudo-TTY settings'). If `window === false`, then no pseudo-tty is allocated. `options` supports the `x11` and `env` options as described in `exec()`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream.
1004
1005* **subsys**(< _string_ >subsystem, < _function_ >callback) - _(void)_ - Invokes `subsystem` on the server. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream.
1006
1007* **unforwardIn**(< _string_ >remoteAddr, < _integer_ >remotePort, < _function_ >callback) - _(void)_ - Unbind from `remoteAddr` on `remotePort` on the server and stop forwarding incoming TCP connections. Until `callback` is called, more connections may still come in. `callback` has 1 parameter: < _Error_ >err.
1008
1009### Server
1010
1011#### Server events
1012
1013* **connection**(< _Connection_ >client, < _object_ >info) - A new client has connected. `info` contains the following properties:
1014
1015 * **family** - _string_ - The `remoteFamily` of the connection.
1016
1017 * **header** - _object_ - Information about the client's header:
1018
1019 * **identRaw** - _string_ - The raw client identification string.
1020
1021 * **versions** - _object_ - Various version information:
1022
1023 * **protocol** - _string_ - The SSH protocol version (always `1.99` or `2.0`).
1024
1025 * **software** - _string_ - The software name and version of the client.
1026
1027 * **comments** - _string_ - Any text that comes after the software name/version.
1028
1029 Example: the identification string `SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2` would be parsed as:
1030
1031```js
1032 { identRaw: 'SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2',
1033 version: {
1034 protocol: '2.0',
1035 software: 'OpenSSH_6.6.1p1'
1036 },
1037 comments: 'Ubuntu-2ubuntu2' }
1038```
1039
1040 * **ip** - _string_ - The `remoteAddress` of the connection.
1041
1042 * **port** - _integer_ - The `remotePort` of the connection.
1043
1044#### Server methods
1045
1046* **(constructor)**(< _object_ >config[, < _function_ >connectionListener]) - Creates and returns a new Server instance. Server instances also have the same methods/properties/events as [`net.Server`](http://nodejs.org/docs/latest/api/net.html#net_class_net_server). `connectionListener` if supplied, is added as a `connection` listener. Valid `config` properties:
1047
1048 * **algorithms** - _object_ - This option allows you to explicitly override the default transport layer algorithms used for incoming client connections. Each value must be an array of valid algorithms for that category. The order of the algorithms in the arrays are important, with the most favorable being first. For a list of valid and default algorithm names, please review the documentation for the version of `ssh2` used by this module. Valid keys:
1049
1050 * **cipher** - _array_ - Ciphers.
1051
1052 * **compress** - _array_ - Compression algorithms.
1053
1054 * **hmac** - _array_ - (H)MAC algorithms.
1055
1056 * **kex** - _array_ - Key exchange algorithms.
1057
1058 * **serverHostKey** - _array_ - Server host key formats.
1059
1060 * **banner** - _string_ - A message that is sent to clients once, right before authentication begins. **Default:** (none)
1061
1062 * **debug** - _function_ - Set this to a function that receives a single string argument to get detailed (local) debug information. **Default:** (none)
1063
1064 * **greeting** - _string_ - A message that is sent to clients immediately upon connection, before handshaking begins. **Note:** Most clients usually ignore this. **Default:** (none)
1065
1066 * **highWaterMark** - _integer_ - This is the `highWaterMark` to use for the parser stream. **Default:** `32 * 1024`
1067
1068 * **hostKeys** - _array_ - An array of either Buffers/strings that contain host private keys or objects in the format of `{ key: <Buffer/string>, passphrase: <string> }` for encrypted private keys. (**Required**) **Default:** (none)
1069
1070 * **ident** - _string_ - A custom server software name/version identifier. **Default:** `'ssh2js' + moduleVersion + 'srv'`
1071
1072* **injectSocket**(< _DuplexStream_ >socket) - Injects a bidirectional stream as though it were a TCP socket connection. Additionally, `socket` should include `net.Socket`-like properties to ensure the best compatibility (e.g. `socket.remoteAddress`, `socket.remotePort`, `socket.remoteFamily`).
1073
1074#### Connection events
1075
1076* **authentication**(< _AuthContext_ >ctx) - The client has requested authentication. `ctx.username` contains the client username, `ctx.method` contains the requested authentication method, and `ctx.accept()` and `ctx.reject([< Array >authMethodsLeft[, < Boolean >isPartialSuccess]])` are used to accept or reject the authentication request respectively. `abort` is emitted if the client aborts the authentication request. Other properties/methods available on `ctx` depends on the `ctx.method` of authentication the client has requested:
1077
1078 * `hostbased`:
1079
1080 * **blob** - _Buffer_ - This contains the data to be verified that is passed to (along with the signature) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities).
1081
1082 * **key** - _object_ - Contains information about the public key sent by the client:
1083
1084 * **algo** - _string_ - The name of the key algorithm (e.g. `ssh-rsa`).
1085
1086 * **data** - _Buffer_ - The actual key data.
1087
1088 * **localHostname** - _string_ - The local hostname provided by the client.
1089
1090 * **localUsername** - _string_ - The local username provided by the client.
1091
1092 * **signature** - _Buffer_ - This contains a signature to be verified that is passed to (along with the blob) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities).
1093
1094 * `keyboard-interactive`:
1095
1096 * **prompt**(< _array_ >prompts[, < _string_ >title[, < _string_ >instructions]], < _function_ >callback) - _(void)_ - Send prompts to the client. `prompts` is an array of `{ prompt: 'Prompt text', echo: true }` objects (`prompt` being the prompt text and `echo` indicating whether the client's response to the prompt should be echoed to their display). `callback` is called with `(responses)`, where `responses` is an array of string responses matching up to the `prompts`.
1097
1098 * **submethods** - _array_ - A list of preferred authentication "sub-methods" sent by the client. This may be used to determine what (if any) prompts to send to the client.
1099
1100 * `password`:
1101
1102 * **password** - _string_ - This is the password sent by the client.
1103
1104 * **requestChange**(< _string_ >prompt, < _function_ >callback) - _(void)_ - Sends a password change request to the client. `callback` is called with `(newPassword)`, where `newPassword` is the new password supplied by the client. You may accept, reject, or prompt for another password change after `callback` is called.
1105
1106 * `publickey`:
1107
1108 * **blob** - _mixed_ - If the value is `undefined`, the client is only checking the validity of the `key`. If the value is a _Buffer_, then this contains the data to be verified that is passed to (along with the signature) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities).
1109
1110 * **key** - _object_ - Contains information about the public key sent by the client:
1111
1112 * **algo** - _string_ - The name of the key algorithm (e.g. `ssh-rsa`).
1113
1114 * **data** - _Buffer_ - The actual key data.
1115
1116 * **signature** - _mixed_ - If the value is `undefined`, the client is only checking the validity of the `key`. If the value is a _Buffer_, then this contains a signature to be verified that is passed to (along with the blob) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities).
1117
1118* **close**() - The client socket was closed.
1119
1120* **end**() - The client socket disconnected.
1121
1122* **error**(< _Error_ >err) - An error occurred.
1123
1124* **handshake**(< _object_ >negotiated) - Emitted when a handshake has completed (either initial or rekey). `negotiated` contains the negotiated details of the handshake and is of the form:
1125
1126```js
1127 // In this particular case `mac` is empty because there is no separate MAC
1128 // because it's integrated into AES in GCM mode
1129 { kex: 'ecdh-sha2-nistp256',
1130 srvHostKey: 'rsa-sha2-512',
1131 cs: { // Client to server algorithms
1132 cipher: 'aes128-gcm',
1133 mac: '',
1134 compress: 'none',
1135 lang: ''
1136 },
1137 sc: { // Server to client algorithms
1138 cipher: 'aes128-gcm',
1139 mac: '',
1140 compress: 'none',
1141 lang: ''
1142 }
1143 }
1144```
1145
1146* **openssh.streamlocal**(< _function_ >accept, < _function_ >reject, < _object_ >info) - Emitted when the client has requested a connection to a UNIX domain socket. `accept()` returns a new _Channel_ instance representing the connection. `info` contains:
1147
1148 * **socketPath** - _string_ - Destination socket path of outgoing connection.
1149
1150* **ready**() - Emitted when the client has been successfully authenticated.
1151
1152* **rekey**() - Emitted when a rekeying operation has completed (either client or server-initiated).
1153
1154* **request**(< _mixed_ >accept, < _mixed_ >reject, < _string_ >name, < _object_ >info) - Emitted when the client has sent a global request for `name` (e.g. `tcpip-forward` or `cancel-tcpip-forward`). `accept` and `reject` are functions if the client requested a response. If `bindPort === 0`, you should pass the chosen port to `accept()` so that the client will know what port was bound. `info` contains additional details about the request:
1155
1156 * `cancel-tcpip-forward` and `tcpip-forward`:
1157
1158 * **bindAddr** - _string_ - The IP address to start/stop binding to.
1159
1160 * **bindPort** - _integer_ - The port to start/stop binding to.
1161
1162 * `cancel-streamlocal-forward@openssh.com` and `streamlocal-forward@openssh.com`:
1163
1164 * **socketPath** - _string_ - The socket path to start/stop binding to.
1165
1166* **session**(< _function_ >accept, < _function_ >reject) - Emitted when the client has requested a new session. Sessions are used to start interactive shells, execute commands, request X11 forwarding, etc. `accept()` returns a new _Session_ instance.
1167
1168* **tcpip**(< _function_ >accept, < _function_ >reject, < _object_ >info) - Emitted when the client has requested an outbound (TCP) connection. `accept()` returns a new _Channel_ instance representing the connection. `info` contains:
1169
1170 * **destIP** - _string_ - Destination IP address of outgoing connection.
1171
1172 * **destPort** - _string_ - Destination port of outgoing connection.
1173
1174 * **srcIP** - _string_ - Source IP address of outgoing connection.
1175
1176 * **srcPort** - _string_ - Source port of outgoing connection.
1177
1178#### Connection methods
1179
1180* **end**() - _(void)_ - Closes the client connection.
1181
1182* **forwardOut**(< _string_ >boundAddr, < _integer_ >boundPort, < _string_ >remoteAddr, < _integer_ >remotePort, < _function_ >callback) - _(void)_ - Alert the client of an incoming TCP connection on `boundAddr` on port `boundPort` from `remoteAddr` on port `remotePort`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream.
1183
1184* **openssh_forwardOutStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - Alert the client of an incoming UNIX domain socket connection on `socketPath`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream.
1185
1186* **rekey**([< _function_ >callback]) - _(void)_ - Initiates a rekey with the client. If `callback` is supplied, it is added as a one-time handler for the `rekey` event.
1187
1188* **x11**(< _string_ >originAddr, < _integer_ >originPort, < _function_ >callback) - _(void)_ - Alert the client of an incoming X11 client connection from `originAddr` on port `originPort`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream.
1189
1190#### Session events
1191
1192* **auth-agent**(< _mixed_ >accept, < _mixed_ >reject) - The client has requested incoming ssh-agent requests be forwarded to them. `accept` and `reject` are functions if the client requested a response.
1193
1194* **close**() - The session was closed.
1195
1196* **env**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client requested an environment variable to be set for this session. `accept` and `reject` are functions if the client requested a response. `info` has these properties:
1197
1198 * **key** - _string_ - The environment variable's name.
1199
1200 * **value** - _string_ - The environment variable's value.
1201
1202* **exec**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client has requested execution of a command string. `accept` and `reject` are functions if the client requested a response. `accept()` returns a _Channel_ for the command execution. `info` has these properties:
1203
1204 * **command** - _string_ - The command line to be executed.
1205
1206* **pty**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client requested allocation of a pseudo-TTY for this session. `accept` and `reject` are functions if the client requested a response. `info` has these properties:
1207
1208 * **cols** - _integer_ - The number of columns for the pseudo-TTY.
1209
1210 * **height** - _integer_ - The height of the pseudo-TTY in pixels.
1211
1212 * **modes** - _object_ - Contains the requested terminal modes of the pseudo-TTY keyed on the mode name with the value being the mode argument. (See the table at the end for valid names).
1213
1214 * **rows** - _integer_ - The number of rows for the pseudo-TTY.
1215
1216 * **width** - _integer_ - The width of the pseudo-TTY in pixels.
1217
1218* **sftp**(< _mixed_ >accept, < _mixed_ >reject) - The client has requested the SFTP subsystem. `accept` and `reject` are functions if the client requested a response. `accept()` returns an _SFTP_ instance in server mode (see the [`SFTP` documentation](https://github.com/mscdex/ssh2/blob/master/SFTP.md) for details). `info` has these properties:
1219
1220* **shell**(< _mixed_ >accept, < _mixed_ >reject) - The client has requested an interactive shell. `accept` and `reject` are functions if the client requested a response. `accept()` returns a _Channel_ for the interactive shell.
1221
1222* **signal**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client has sent a signal. `accept` and `reject` are functions if the client requested a response. `info` has these properties:
1223
1224 * **name** - _string_ - The signal name (e.g. `SIGUSR1`).
1225
1226* **subsystem**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client has requested an arbitrary subsystem. `accept` and `reject` are functions if the client requested a response. `accept()` returns a _Channel_ for the subsystem. `info` has these properties:
1227
1228 * **name** - _string_ - The name of the subsystem.
1229
1230* **window-change**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client reported a change in window dimensions during this session. `accept` and `reject` are functions if the client requested a response. `info` has these properties:
1231
1232 * **cols** - _integer_ - The new number of columns for the client window.
1233
1234 * **height** - _integer_ - The new height of the client window in pixels.
1235
1236 * **rows** - _integer_ - The new number of rows for the client window.
1237
1238 * **width** - _integer_ - The new width of the client window in pixels.
1239
1240* **x11**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client requested X11 forwarding. `accept` and `reject` are functions if the client requested a response. `info` has these properties:
1241
1242 * **cookie** - _string_ - The X11 authentication cookie encoded in hexadecimal.
1243
1244 * **protocol** - _string_ - The name of the X11 authentication method used (e.g. `MIT-MAGIC-COOKIE-1`).
1245
1246 * **screen** - _integer_ - The screen number to forward X11 connections for.
1247
1248 * **single** - _boolean_ - `true` if only a single connection should be forwarded.
1249
1250### Channel
1251
1252This is a normal **streams2** Duplex Stream (used both by clients and servers), with the following changes:
1253
1254* A boolean property `allowHalfOpen` exists and behaves similarly to the property of the same name for `net.Socket`. When the stream's end() is called, if `allowHalfOpen` is `true`, only EOF will be sent (the server can still send data if they have not already sent EOF). The default value for this property is `true`.
1255
1256* A `close` event is emitted once the channel is completely closed on both the client and server.
1257
1258* Client-specific:
1259
1260 * For exec():
1261
1262 * An `exit` event *may* (the SSH2 spec says it is optional) be emitted when the process finishes. If the process finished normally, the process's return value is passed to the `exit` callback. If the process was interrupted by a signal, the following are passed to the `exit` callback: null, < _string_ >signalName, < _boolean_ >didCoreDump, < _string_ >description.
1263
1264 * If there was an `exit` event, the `close` event will be passed the same arguments for convenience.
1265
1266 * A `stderr` property contains a Readable stream that represents output from stderr.
1267
1268 * For exec() and shell():
1269
1270 * The readable side represents stdout and the writable side represents stdin.
1271
1272 * **setWindow**(< _integer_ >rows, < _integer_ >cols, < _integer_ >height, < _integer_ >width) - _(void)_ - Lets the server know that the local terminal window has been resized. The meaning of these arguments are described in the 'Pseudo-TTY settings' section.
1273
1274 * **signal**(< _string_ >signalName) - _(void)_ - Sends a POSIX signal to the current process on the server. Valid signal names are: 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'KILL', 'PIPE', 'QUIT', 'SEGV', 'TERM', 'USR1', and 'USR2'. Some server implementations may ignore this request if they do not support signals. Note: If you are trying to send SIGINT and you find `signal()` doesn't work, try writing `'\x03'` to the Channel stream instead.
1275
1276
1277* Server-specific:
1278
1279 * For exec-enabled channel instances there is an additional method available that may be called right before you close the channel. It has two different signatures:
1280
1281 * **exit**(< _integer_ >exitCode) - _(void)_ - Sends an exit status code to the client.
1282
1283 * **exit**(< _string_ >signalName[, < _boolean_ >coreDumped[, < _string_ >errorMsg]]) - _(void)_ - Sends an exit status code to the client.
1284
1285 * For exec and shell-enabled channel instances, `channel.stderr` is a writable stream.
1286
1287### Pseudo-TTY settings
1288
1289* **cols** - < _integer_ > - Number of columns. **Default:** `80`
1290
1291* **height** - < _integer_ > - Height in pixels. **Default:** `480`
1292
1293* **modes** - < _object_ > - An object containing [Terminal Modes](#terminal-modes) as keys, with each value set to each mode argument. **Default:** `null`
1294
1295* **rows** - < _integer_ > - Number of rows. **Default:** `24`
1296
1297* **term** - < _string_ > - The value to use for $TERM. **Default:** `'vt100'`
1298
1299* **width** - < _integer_ > - Width in pixels. **Default:** `640`
1300
1301`rows` and `cols` override `width` and `height` when `rows` and `cols` are non-zero.
1302
1303Pixel dimensions refer to the drawable area of the window.
1304
1305Zero dimension parameters are ignored.
1306
1307### Terminal modes
1308
1309Name | Description
1310-------------- | ------------
1311CS7 | 7 bit mode.
1312CS8 | 8 bit mode.
1313ECHOCTL | Echo control characters as ^(Char).
1314ECHO | Enable echoing.
1315ECHOE | Visually erase chars.
1316ECHOKE | Visual erase for line kill.
1317ECHOK | Kill character discards current line.
1318ECHONL | Echo NL even if ECHO is off.
1319ICANON | Canonicalize input lines.
1320ICRNL | Map CR to NL on input.
1321IEXTEN | Enable extensions.
1322IGNCR | Ignore CR on input.
1323IGNPAR | The ignore parity flag. The parameter SHOULD be 0 if this flag is FALSE, and 1 if it is TRUE.
1324IMAXBEL | Ring bell on input queue full.
1325INLCR | Map NL into CR on input.
1326INPCK | Enable checking of parity errors.
1327ISIG | Enable signals INTR, QUIT, [D]SUSP.
1328ISTRIP | Strip 8th bit off characters.
1329IUCLC | Translate uppercase characters to lowercase.
1330IXANY | Any char will restart after stop.
1331IXOFF | Enable input flow control.
1332IXON | Enable output flow control.
1333NOFLSH | Don't flush after interrupt.
1334OCRNL | Translate carriage return to newline (output).
1335OLCUC | Convert lowercase to uppercase.
1336ONLCR | Map NL to CR-NL.
1337ONLRET | Newline performs a carriage return (output).
1338ONOCR | Translate newline to carriage return-newline (output).
1339OPOST | Enable output processing.
1340PARENB | Parity enable.
1341PARMRK | Mark parity and framing errors.
1342PARODD | Odd parity, else even.
1343PENDIN | Retype pending input.
1344TOSTOP | Stop background jobs from output.
1345TTY_OP_ISPEED | Specifies the input baud rate in bits per second.
1346TTY_OP_OSPEED | Specifies the output baud rate in bits per second.
1347VDISCARD | Toggles the flushing of terminal output.
1348VDSUSP | Another suspend character.
1349VEOF | End-of-file character (sends EOF from the terminal).
1350VEOL2 | Additional end-of-line character.
1351VEOL | End-of-line character in addition to carriage return and/or linefeed.
1352VERASE | Erase the character to left of the cursor.
1353VFLUSH | Character to flush output.
1354VINTR | Interrupt character; 255 if none. Similarly for the other characters. Not all of these characters are supported on all systems.
1355VKILL | Kill the current input line.
1356VLNEXT | Enter the next character typed literally, even if it is a special character
1357VQUIT | The quit character (sends SIGQUIT signal on POSIX systems).
1358VREPRINT | Reprints the current input line.
1359VSTART | Continues paused output (normally control-Q).
1360VSTATUS | Prints system status line (load, command, pid, etc).
1361VSTOP | Pauses output (normally control-S).
1362VSUSP | Suspends the current program.
1363VSWTCH | Switch to a different shell layer.
1364VWERASE | Erases a word left of cursor.
1365XCASE | Enable input and output of uppercase characters by preceding their lowercase equivalents with "\".
1366
1367### HTTPAgent
1368
1369#### HTTPAgent methods
1370
1371* **(constructor)**(< _object_ >sshConfig[, < _object_ >agentConfig]) - Creates and returns a new `http.Agent` instance used to tunnel an HTTP connection over SSH. `sshConfig` is what is passed to `client.connect()` and `agentOptions` is passed to the `http.Agent` constructor.
1372
1373### HTTPSAgent
1374
1375#### HTTPSAgent methods
1376
1377* **(constructor)**(< _object_ >sshConfig[, < _object_ >agentConfig]) - Creates and returns a new `https.Agent` instance used to tunnel an HTTP connection over SSH. `sshConfig` is what is passed to `client.connect()` and `agentOptions` is passed to the `https.Agent` constructor.
1378
1379### Utilities
1380
1381* **parseKey**(< _mixed_ >keyData[, < _string_ >passphrase]) - _mixed_ - Parses a private/public key in OpenSSH, RFC4716, or PPK format. For encrypted private keys, the key will be decrypted with the given `passphrase`. `keyData` can be a _Buffer_ or _string_ value containing the key contents. The returned value will be an array of objects (currently in the case of modern OpenSSH keys) or an object with these properties and methods:
1382
1383 * **comment** - _string_ - The comment for the key
1384
1385 * **equals**(< _mixed_ >otherKey) - _boolean_ - This returns `true` if `otherKey` (a parsed or parseable key) is the same as this key. This method does not compare the keys' comments
1386
1387 * **getPrivatePEM**() - _string_ - This returns the PEM version of a private key
1388
1389 * **getPublicPEM**() - _string_ - This returns the PEM version of a public key (for either public key or derived from a private key)
1390
1391 * **getPublicSSH**() - _string_ - This returns the SSH version of a public key (for either public key or derived from a private key)
1392
1393 * **isPrivateKey**() - _boolean_ - This returns `true` if the key is a private key or not
1394
1395 * **sign**(< _mixed_ >data) - _mixed_ - This signs the given `data` using this key and returns a _Buffer_ containing the signature on success. On failure, an _Error_ will be returned. `data` can be anything accepted by node's [`sign.update()`](https://nodejs.org/docs/latest/api/crypto.html#crypto_sign_update_data_inputencoding).
1396
1397 * **type** - _string_ - The full key type (e.g. `'ssh-rsa'`)
1398
1399 * **verify**(< _mixed_ >data, < _Buffer_ >signature) - _mixed_ - This verifies a `signature` of the given `data` using this key and returns `true` if the signature could be verified. On failure, either `false` will be returned or an _Error_ will be returned upon a more critical failure. `data` can be anything accepted by node's [`verify.update()`](https://nodejs.org/docs/latest/api/crypto.html#crypto_verify_update_data_inputencoding).
1400
1401* **sftp.OPEN_MODE** - [`OPEN_MODE`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-data-structures)
1402
1403* **sftp.STATUS_CODE** - [`STATUS_CODE`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-data-structures)
1404
1405* **sftp.flagsToString** - [`flagsToString()`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-methods)
1406
1407* **sftp.stringToFlags** - [`stringToFlags()`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-methods)
1408
1409### AgentProtocol
1410
1411#### AgentProtocol events
1412
1413* **identities**(< _opaque_ >request) - **(Server mode only)** The client has requested a list of public keys stored in the agent. Use `failureReply()` or `getIdentitiesReply()` to reply appropriately.
1414
1415* **sign**(< _opaque_ >request, < _mixed_ >pubKey, < _Buffer_ >data, < _object_ >options) - **(Server mode only)** The client has requested `data` to be signed using the key identified by `pubKey`. Use `failureReply()` or `signReply()` to reply appropriately. `options` may contain any of:
1416
1417 * **hash** - _string_ - The explicitly desired hash to use when computing the signature. Currently if set, this may be either `'sha256'` or `'sha512'` for RSA keys.
1418
1419#### AgentProtocol methods
1420
1421* **(constructor)**(< _boolean_ >isClient) - Creates and returns a new AgentProtocol instance. `isClient` determines whether the instance operates in client or server mode.
1422
1423* **failureReply**(< _opaque_ >request) - _(void)_ - **(Server mode only)** Replies to the given `request` with a failure response.
1424
1425* **getIdentities**(< _function_ >callback) - _(void)_ - **(Client mode only)** Requests a list of public keys from the agent. `callback` is passed `(err, keys)` where `keys` is a possible array of public keys for authentication.
1426
1427* **getIdentitiesReply**(< _opaque_ >request, < _array_ >keys) - _(void)_ - **(Server mode only)** Responds to a identities list `request` with the given array of keys in `keys`.
1428
1429* **sign**(< _mixed_ >pubKey, < _Buffer_ >data, < _object_ >options, < _function_ >callback) - _(void)_ - **(Client mode only)** Requests that the agent sign `data` using the key identified by `pubKey`. `pubKey` can be any parsed (using `utils.parseKey()`) or parseable key value. `callback` is passed `(err, signature)` where `signature` is a possible _Buffer_ containing the signature for the `data`. `options` may contain any of:
1430
1431 * **hash** - _string_ - The explicitly desired hash to use when computing the signature. Currently if set, this may be either `'sha256'` or `'sha512'` for RSA keys.
1432
1433* **signReply**(< _opaque_ >request, < _Buffer_ >signature) - _(void)_ - **(Server mode only)** Responds to a sign `request` with the given signature in `signature`.
1434
1435### BaseAgent
1436
1437In order to create a custom agent, your class *must*:
1438
1439 * Extend `BaseAgent`
1440 * Call `super()` in its constructor
1441 * Implement *at least* the following methods:
1442
1443* **getIdentities**(< _function_ >callback) - _(void)_ - Passes `(err, keys)` to `callback` where `keys` is a possible array of public keys for authentication.
1444
1445* **sign**(< _mixed_ >pubKey, < _Buffer_ >data, < _object_ >options, < _function_ >callback) - _(void)_ - Signs `data` using the key identified by `pubKey`. `pubKey` can be any parsed (using `utils.parseKey()`) or parseable key value. `callback` should be passed `(err, signature)` where `signature` is a possible _Buffer_ containing the signature for the `data`. `options` may contain any of:
1446
1447 * **hash** - _string_ - The explicitly desired hash to use when computing the signature. Currently if set, this may be either `'sha256'` or `'sha512'` for RSA keys.
1448
1449Additionally your class may implement the following method in order to support agent forwarding on the client:
1450
1451* **getStream**(< _function_ >callback) - _(void)_ - Passes `(err, stream)` to `callback` where `stream` is a possible Duplex stream to be used to communicate with your agent. You will probably want to utilize `AgentProtocol` as agent forwarding is an OpenSSH feature, so the `stream` needs to be able to transmit/receive OpenSSH agent protocol packets.
1452
1453### createAgent
1454
1455* **createAgent**(< _string_ >agentValue) - _(Agent)_ - Creates and returns a new agent instance using the same logic as the `Client`'s `agent` configuration option: if the platform is Windows and it's the value "pageant", it creates a `PageantAgent`, otherwise if it's not a path to a Windows pipe it creates a `CygwinAgent`. In all other cases, it creates an `OpenSSHAgent`.
1456
1457### CygwinAgent
1458
1459#### CygwinAgent methods
1460
1461* **(constructor)**(< _string_ >socketPath) - Communicates with an agent listening at `socketPath` in a Cygwin environment.
1462
1463### OpenSSHAgent
1464
1465#### OpenSSHAgent methods
1466
1467* **(constructor)**(< _string_ >socketPath) - Communicates with an OpenSSH agent listening on the UNIX socket at `socketPath`.
1468
1469### PageantAgent
1470
1471#### PageantAgent methods
1472
1473* **(constructor)**() - Creates a new agent instance for communicating with a running Pageant agent process.