agebrock / tunnel-ssh

Easy ssh tunneling
MIT License
356 stars 96 forks source link

About using this module to test the connection process #103

Open TakamiChie opened 1 year ago

TakamiChie commented 1 year ago

I am currently using this module to create an application that connects to the dstHost shown below.

flowchart LR
    A["localHost"] -->|Tunneling| B["host"]
    B -->|Tunneling| C["dstHost"]

I wanted to write test code to simulate communication at the dstHost, so I wrote the following code:

const { createTunnel } = require('tunnel-ssh');
const { Server } = require('ssh2');
const { readFileSync } = require('fs');
const net = require("net");

require("dotenv").config();
const tunnelOptions = {
  autoClose:false
};
const serverOptions = {
  host: process.env.SRC_HOST,  port: process.env.SRC_PORT
};
const sshOptions = {
  host: process.env.HOST, port: process.env.PORT,
  username: process.env.UNAME, password: process.env.PASSWORD
}
const forwardOptions = {
  srcAddr: process.env.HOST, srcPort: process.env.PORT,
  dstAddr: process.env.TO_HOST, dstPort: process.env.TO_PORT
}

const f = async () => {
  const proxy = net.createServer((client) => {
    const serverConnection = net.createConnection({host: forwardOptions.dstAddr, port: forwardOptions.dstPort});
    client.pipe(serverConnection);
  });
  const server = new Server({ hostKeys: [readFileSync('./id_rsa')] },  (client) => {
    console.log('Client connected!');

    client.on('authentication', (ctx) => {
      // authentication code
    }).on('ready', () => {
      // authenticated code
    }).on('close', () => {
      // closing code
    });
  });
  proxy.listen({host: sshOptions.host, port: sshOptions.port});
  server.listen({host: forwardOptions.dstAddr, port: forwardOptions.dstPort});

  const result = await createTunnel(tunnelOptions, serverOptions, sshOptions, forwardOptions);
  console.log("Finished!");
  result[0].close();
}
f();

However, when I execute the above code, the log "Finished" is not displayed and the error "Error: Timed out while waiting for handshake" occurs.

How can I emulate SSH communication without causing errors?


tunnel-ssh:4.0.5 node: v19.6.0

agebrock commented 1 year ago

Hi there, this is not really ssh-tunnel related and more a question you should ask in the ssh2 project. However I like your approach and had a quick look, I will investigate a bit further, if this would be a nice way to test the project.

I advice you to have a look into the following post : https://github.com/mscdex/ssh2/issues/698

There is an working example for an SSH2 server with port forwarding support.

it would be nice to get your feedback once you are done emulating.

Thx for the issue.