How to use the ssh2.Server function in ssh2

To help you get started, we’ve selected a few ssh2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ngnjs / NGN / test / 04-sshtunnel.js View on Github external
test('SSH Tunneling', function (t) {
  require('../')
//  NGN.Log.disable()

  t.ok(typeof NGN.Tunnel === 'function', 'NGN.Tunnel is available.')

  // 1. Create a mock TCP server
  let server = createServer()

  // 2. Create a mock SSH server
  let pubKey = utils.genPublicKey(utils.parseKey(fs.readFileSync(path.join(__dirname, '/files/ssh-client-private.key'))))
  let sshserver = new ssh2.Server({
    hostKeys: [fs.readFileSync(path.join(__dirname, '/files/ssh-host-private.key'))]
  }, function (client) {
    t.pass('SSH client connected.')

    client.on('authentication', function (ctx) {
      if (ctx.method === 'password' && ctx.username === 'foo' && ctx.password === 'bar') {
        ctx.accept()
      } else if (ctx.method === 'publickey' && ctx.key.algo === pubKey.fulltype && buffersEqual(ctx.key.data, pubKey.public)) {
        if (ctx.signature) {
          let verifier = crypto.createVerify(ctx.sigAlgo)
          verifier.update(ctx.blob)
          if (verifier.verify(pubKey.publicOrig, ctx.signature, 'binary')) {
            ctx.accept()
          } else {
            ctx.reject()
          }
github NuSkooler / enigma-bbs / core / servers / login / ssh.js View on Github external
debug : (sshDebugLine) => {
                if(true === config.loginServers.ssh.traceConnections) {
                    Log.trace(`SSH: ${sshDebugLine}`);
                }
            },
            algorithms : config.loginServers.ssh.algorithms,
        };

        //
        //  This is a terrible hack, and we should not have to do it;
        //  However, as of this writing, NetRunner and SyncTERM both
        //  fail to respond to OpenSSH keep-alive pings (keepalive@openssh.com)
        //
        ssh2.Server.KEEPALIVE_INTERVAL = 0;

        this.server = ssh2.Server(serverConf);
        this.server.on('connection', (conn, info) => {
            Log.info(info, 'New SSH connection');
            this.handleNewClient(new SSHClient(conn), conn._sock, ModuleInfo);
        });

        return cb(null);
    }
github mscdex / ssh2 / examples / server-chat.js View on Github external
var output = user.output;
    if (source === user)
      output.add(sourceMsg);
    else
      output.add(formatMessage(name, output) + msg);
  }
}

function localMessage(msg, source) {
  var output = source.output;
  output.add(formatMessage(msg, output));
}

function noop(v) {}

new Server({
  hostKeys: [fs.readFileSync('host.key')],
}, function(client) {
  var stream;
  var name;

  client.on('authentication', function(ctx) {
    var nick = ctx.username;
    var prompt = PROMPT_NAME;
    var lowered;
    // Try to use username as nickname
    if (nick.length > 0 && nick.length <= MAX_NAME_LEN) {
      lowered = nick.toLowerCase();
      var ok = true;
      for (var i = 0; i < users.length; ++i) {
        if (users[i].name.toLowerCase() === lowered) {
          ok = false;
github nuxt / fabula / test / server.js View on Github external
exports.launchTestSSHServer = async function() {
  const privateKey = resolve(__dirname, 'fixtures', 'keys', 'ssh.private')
  const hostKeys = [{
    key: fs.readFileSync(privateKey),
    passphrase
  }]
  const server = new ssh2.Server({ hostKeys }, (client) => {
    client.on('authentication', authenticateSession)
    client.on('session', (acceptSession) => {
      acceptSession().once('exec', async (acceptExec, _, execInfo) => {
        const stream = acceptExec()
        const argv = parseArgv(execInfo.command.trim())
        if (argv[0] === 'bin.js') {
          const result = await bin(false, argv)
          if (result.stdout) {
            stream.write(result.stdout)
          }
          if (result.stderr) {
            stream.stderr.write(result.stderr)
          }
          stream.exit(result.code)
          stream.end()
        } else {
github spatie / laravel-server-monitor / tests / server / server.js View on Github external
const createServer = () => new Promise((resolve) => {
    const input = new Input();

    new ssh2.Server(
        { hostKeys },
        client => startSession(client, input).then(() => resolve(input))
    ).listen(65000, '127.0.0.1', function () {
        console.log('Listening on port ' + this.address().port);
    });
});
github silexlabs / unifile / test / unifile-sftp.js View on Github external
beforeEach('Instanciation', function(done) {
		let reading = false;
		srv = new Server({hostKeys: [privateKey]}, (client) => {
			client.on('authentication', (ctx) => {
				if(ctx.method === 'password' && ctx.username === session.user
								&& ctx.password === session.password)
					ctx.accept();
				else ctx.reject();
			})
			.on('ready', () => {
				client.on('session', (accept, reject) => {
					const session = accept();
					session.on('sftp', (accept, reject) => {
						const sftpStream = accept();
						sftpStream.on('OPEN', (reqid, filename, flags, attrs) => {
							sftpStream.handle(reqid, new Buffer(filename));
						})
						.on('STAT', (reqid, path) => {
							Fs.statPromised(path)
github altitude / login-with-ssh / lib / server.js View on Github external
export default function server() {

	const server = new ssh2.Server({
		privateKey: fs.readFileSync(process.env.KEY),
		debug: true,
	});

	server.on('connection', connection);

	server.listen(process.env.PORT, process.env.BIND, function() {
		console.log(`listening on ${process.env.BIND}:${process.env.PORT}`);
	});

	return server;
}
github mscdex / ssh2 / examples / sftp-server-download-only.js View on Github external
var crypto = require('crypto');
var constants = require('constants');
var fs = require('fs');

var ssh2 = require('ssh2');
var OPEN_MODE = ssh2.SFTP_OPEN_MODE;
var STATUS_CODE = ssh2.SFTP_STATUS_CODE;

var allowedUser = Buffer.from('foo');
var allowedPassword = Buffer.from('bar');

new ssh2.Server({
  hostKeys: [fs.readFileSync('host.key')]
}, function(client) {
  console.log('Client connected!');

  client.on('authentication', function(ctx) {
    var user = Buffer.from(ctx.username);
    if (user.length !== allowedUser.length
        || !crypto.timingSafeEqual(user, allowedUser)) {
      return ctx.reject(['password']);
    }

    switch (ctx.method) {
      case 'password':
        var password = Buffer.from(ctx.password);
        if (password.length !== allowedPassword.length
            || !crypto.timingSafeEqual(password, allowedPassword)) {
github tkambler / sftp-server / lib / components / server / index.js View on Github external
.then(() => {

                    this.clientManager = new ClientManager(this);

                    this.server = new ssh2.Server({
                        'hostKeys': config.get('sftp:hostKeys'),
                        'algorithms': config.get('sftp:algorithms')
                    });

                    this.server.on('connection', (client, info) => {
                        log.info('Incoming connection', info);
                        client.info = info;
                        this.clientManager.track(client);
                    });

                    this.rest = api(this);

                    this.server.listen(config.get('sftp:port'), config.get('sftp:address'), function() {
                        const address = this.address();
                        log.info('SFTP server is listening', {
                            'address': address.address,
github tkambler / sftp-server / lib / server.js View on Github external
.then(() => {

                this.clientManager = new ClientManager(this);

                const options = {
                    'hostKeys': this.hostKeys,
                    'algorithms': this.algorithms
                };

                debug('Server options', options);

                this.server = new ssh2.Server(options, (client) => {
                    this.clientManager.track(client);
                });

                debug('Starting server', {
                    'port': this.port,
                    'address': this.address
                });

                this.rest = require('./rest')(this);

                this.server.listen(this.port, this.address, function() {
                    const address = this.address();
                    debug('SFTP Server is listening', {
                        'address': address.address,
                        'port': address.port
                    });