Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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()
}
'use strict'
const LOCAL_PORT = parseInt(process.env.LOCAL_SSH_PORT || 47911, 10) - 3
const REMOTE_PORT = parseInt(process.env.LOCAL_SSH_PORT || 47911, 10) - 5
const test = require('tape')
const fs = require('fs')
const path = require('path')
const net = require('net')
const crypto = require('crypto')
const ssh2 = require('ssh2')
const utils = ssh2.utils
const buffersEqual = require('buffer-equal-constant-time')
const createServer = function () {
return net.createServer(function (c) { // 'connection' listener
console.log('remote client connected')
c.on('data', function (d) {
console.log('DATA', d)
})
c.on('end', function () {
console.log('remote client disconnected')
})
c.on('close', function () {
console.log('mock TCP server closed.')
})
c.write('hello\r\n')
// c.pipe(c)
function runTunnel(pmsPort, remoteOpts) {
// Create a SSH client
const conn = new Client();
const config = {
remoteHost: remoteOpts.subdomain || '',
remotePort: 80,
localHost: 'localhost',
localPort: pmsPort
}
conn
.on('error', err => {
if (err)
console.error(err)
console.log('Serveo - Got error from tunnel, restarting connection in 5 seconds')
setTimeout(() => {
runTunnel(pmsPort, remoteOpts)
}, 5000)
handleSsh = async () => {
// Clear the messages so they don't display in our interactive session
this.setState({ messages: null, removeOptions: true })
// Set some variables for later
const serverConfig = this.state.config.server
const { SWIFF_CUSTOM_KEY } = this.state.localEnv
// Get the users key we'll be using to connect with
const user = await resolveUsername()
// Check if the key file exists
const privateKey = !isEmpty(SWIFF_CUSTOM_KEY)
? SWIFF_CUSTOM_KEY
: `/Users/${user}/.ssh/id_rsa`
// Create an interactive shell session
// https://github.com/mscdex/ssh2#start-an-interactive-shell-session
let gs = null
const conn = new ssh2()
conn.on('ready', () => {
conn.shell((err, stream) => {
if (err) throw err
// Build the commands to run once we're logged in
const initialCommands = [
`cd ${serverConfig.appPath}`,
'clear',
'll',
`echo "\n💁 You're now connected with: ${serverConfig.user}@${serverConfig.host}\nWorking directory: ${serverConfig.appPath}\n"`,
].join(' && ')
// Run the commands
stream.write(`${initialCommands}\n`)
stream
.on('close', () => {
console.log(
colourHighlight(
User.findOne({username: ctx.username}, function(err, doc){
if (doc) {
if (ctx.method === 'publickey'
&& ctx.username!=undefined
&& doc.publicKey
&& doc.publicKey.length !== 0) {
console.log(' ** trying key auth');
//load publickey by username
if(doc.publicKey && doc.publicKey.length) {
var publicKey = utils.genPublicKey(utils.parseKey(doc.publicKey));
var successfulKeyAuth = ctx.key.algo === publicKey.fulltype
&& buffersEqual(ctx.key.data, publicKey.public);
if (successfulKeyAuth) {
// user logged in via key, serve interface
console.log('[ok] key auth');
userMeta.next = 'auth';
userMeta.user = doc;
ctx.accept();
} else {
console.log('[no] key auth');
return ctx.reject();
}
} else {
super();
var self = this;
//self = this;
this.controllerConnected = false;
this.soloConnected = false;
this.versions = {
sololink_version: " – ",
gimbal_version: " – ",
ak_version: " – ",
shotmanager_version: " – ",
pixhawk_version: " – ",
controller_version: " – ",
ssid: " – ",
password: " – "
}
this.controller_connection = new Client();
this.solo_connection = new Client();
// Controller connection config
this.controller_connection_params = {
host: '10.1.1.1',
port: 22,
username: 'root',
password: 'TjSDBkAu',
readyTimeout: 2000,
keepaliveInterval: 2000
}
this.controller_connection.on('ready', function(er) {
if(er){
Logger.log("Connection ready but error with controller");
return new Promise((resolve, reject) => {
let privateKey;
try {
privateKey = fs.readFileSync(private_key_path);
} catch (err) {
throw new Error(
`Can't find private SSH key in ${chalk.yellow(private_key_path)}. ` +
`Make sure you're running this script via Bash.`
);
}
const c = new Client();
c.on('ready', () => {
spinner.succeed(`Connected to ${chalk.yellow(host)}`);
resolve(c);
}).connect({
host,
username: user,
privateKey,
passphrase: this.sshPassword,
});
}).catch((err) => {
// ssh2 reports wrong password as "InvalidAsn1Error"
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);
}
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;
sshAuthentication(key: ?string, passphrase: ?string, skipAgent: boolean = false): Promise {
const conn = new SSH2();
return new Promise((resolve, reject) => {
const sshConfig = this.composeSshAuthObject(key, skipAgent);
if (!sshConfig) reject();
conn
.on('error', (err) => {
logger.debug('SSH: connection on error event');
Analytics.addBreadCrumb('ssh', 'connection on error event');
if (this.hasAgentSocket() && err.message === AUTH_FAILED_MESSAGE) {
logger.debug('SSH: retry in case ssh-agent failed');
Analytics.addBreadCrumb('ssh', 'retry in case ssh-agent failed');
// retry in case ssh-agent failed
if (err.message === PASSPHRASE_MESSAGE) {
logger.debug('SSH: Encrypted private key detected, but no passphrase given');
Analytics.addBreadCrumb('ssh', 'Encrypted private key detected, but no passphrase given');
if (cachedPassphrase) {
logger.debug('SSH: trying to use cached passphrase');