N3da
N3da

Reputation: 4673

How to use jsch with ProxyCommands for portforwarding

I want to ssh to a machine which is behind a proxy and do a portforwarding after that in my java program. (To be able to ssh to the box I should have ssh'ed to the proxy machine first). I usually do that by having the following entries in my ~/.ssh/config file:

ProxyCommand ssh proxyhost.com -t nc %h %p
IdentityFile /home/username/username_dsa_key

And then I run the following to do portforwarding to map hostmachine.com:54321 to my localhost:12345:

ssh -A -L12345:localhost:54321 hostmachine.com

Now I want to do these with Jsch library but I can't figure out how to connect to the second host after opening the channel on the session:

        String proxyHost = "proxyhost.com";
        String host = "hostmachine.com";
        int lport = 12345;
        String rhost = "localhost";
        int rport = 54321;

        JSch jsch=new JSch();
        jsch.setKnownHosts("/home/{user}/.ssh/known_hosts");
        jsch.addIdentity("/home/{user}/.ssh/{user}_dsa_key",passphrase);

        Session session1 = jsch.getSession(user,proxyHost,22);
        session1.connect(3000);
        System.out.println(session1.isConnected());
        Channel channel = session1.openChannel("shell");

        ////// Now what? :)


        channel.disconnect();
        session1.disconnect();

Any idea?

p.s: I have read the samples in www.jcraft.com/jsch/examples/ but they didn't help in this case unfortunately.

Thanks!

Upvotes: 2

Views: 6382

Answers (3)

Benedikt Waldvogel
Benedikt Waldvogel

Reputation: 12906

I’ve written an abstraction above JSch that is able to "emulate" ProxyCommand configurations: https://github.com/cronn/ssh-proxy

Upvotes: 0

MocaccinoFan
MocaccinoFan

Reputation: 39

This can help you. You have notice Key verification are set "no", so it's an security issue (MITM attack) if your network isn't secure.

 public static void sesionA(){
     try {
        sessionA = jSch.getSession(username, hostA);  
        Properties config = new Properties(); 
        config.put("StrictHostKeyChecking", "no");
        sessionA.setConfig(config);
        sessionA.setPassword(passwordA);
        sessionA.connect();


        if(sessionA.isConnected()) {
            System.out.println("Connected host A!");
            forwardedPort = 2222;
            sessionA.setPortForwardingL(forwardedPort, hostB, 22);      
        }

    } catch (JSchException e) {
        e.printStackTrace();
    }
 }

 public static void sesionB(){


    try {
        sessionB = jSch.getSession(username, "localhost", forwardedPort);

        Properties config = new Properties(); 
        config.put("StrictHostKeyChecking", "no");
        sessionB.setConfig(config);
        sessionB.setPassword(passwordB);
        sessionB.connect();

          if(sessionB.isConnected()) {
             System.out.println("Connected host B!");

             Channel channel = sessionB.openChannel("exec");

You also can use JSCH offical examples and do the following to avoid prompt messages about keys and other stuff:

 UserInfo ui = new MyUserInfo(){
    public void showMessage(String message){
      JOptionPane.showMessageDialog(null, message);
    }

    @SuppressWarnings("unused")
    public boolean promptYesNo(String message){
        Object[] options={ "yes", "no" };
        int foo = 0;
        return foo==0;     // promptYesNo library method. Return 0 to avoid message
      }  

  };

You have to think about MITM attack, use this code if you're sure about you're network. If you don't verify keys, an expert script-kid can stole you credencials.

Upvotes: 0

ymnk
ymnk

Reputation: 1155

I'll suggest you to try

http://www.jcraft.com/jsch/examples/JumpHosts.java.html

, but if it is important to use the native "ssh" command, you will find the class ProxyCommand in the comment of Session.java of jsch-0.1.50,

/*
// setProxyCommand("ssh -l user2 host2 -o 'ProxyCommand ssh user1@host1 nc host2 22' nc %h %p")
public void setProxyCommand(String command){
  setProxy(new ProxyCommand(command));
}

class ProxyCommand implements Proxy {
  String command;
  Process p = null;
  InputStream in = null;
  OutputStream out = null;
  ProxyCommand(String command){
    this.command = command;
  }
  public void connect(SocketFactory socket_factory, String host, int port, int timeout) throws Exception {
    String _command = command.replace("%h", host);
    _command = _command.replace("%p", new Integer(port).toString());
    p = Runtime.getRuntime().exec(_command);
    in = p.getInputStream();
    out = p.getOutputStream();
  }
  public Socket getSocket() { return null; }
  public InputStream getInputStream() { return in; }
  public OutputStream getOutputStream() { return out; }
  public void close() {
    try{
      if(p!=null){
        p.getErrorStream().close();
        p.getOutputStream().close();
        p.getInputStream().close();
        p.destroy();
        p=null;
      }
    }
    catch(IOException e){
    }
  }
}
*/

Upvotes: 3

Related Questions