Java Apache sshd tunnel

2019-05-20 22:58发布

问题:

I want to create java application, that will be my custom sshd server. Clients should be able to create tunnels to this server.

Now I have this working example:

import org.apache.sshd.SshServer;
import org.apache.sshd.common.ForwardingFilter;
import org.apache.sshd.common.Session;
import org.apache.sshd.common.SshdSocketAddress;
import org.apache.sshd.server.PasswordAuthenticator;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.session.ServerSession;

import java.io.IOException;


public class Test {

public static void main(String[] args) throws IOException {
    // create default server
    SshServer server = SshServer.setUpDefaultServer();
    server.setPasswordAuthenticator(new PasswordAuthenticator() {
        @Override
        public boolean authenticate(String username, String password, ServerSession session) {
            return true; // auth everyone
        }
    });

    server.setPort(2222);

    // allow forwarding
    server.setTcpipForwardingFilter(new ForwardingFilter() {
        @Override
        public boolean canForwardAgent(Session session) {
            return true;
        }

        @Override
        public boolean canForwardX11(Session session) {
            return true;
        }

        @Override
        public boolean canListen(SshdSocketAddress address, Session session) {
            return true;
        }

        @Override
        public boolean canConnect(SshdSocketAddress address, Session session) {
            return true;
        }
    });

    // random hostkey provider
    server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey"));
    server.start(); // start server
}
}

At this moment, I have minimal sshd server. When running, one can build tunnel to it:

ssh user@host -p 2222 -R port:host:port -N

The problem is, user can't create tunnel to the same port twice. First connection is successful, but after tunnel disconnect & reconnect server says, that port is already in use.

Second problem is that connection is unavailable through external IP.

For example, server is 192.168.1.10. Client builds tunnel to server and forwards port 2020. Now, nmap -p 2020 localhost will say, that port is opened, but nmap -p 2020 192.168.1.10 will say, that port is closed.

What I'm trying to ask is how to force sshd server to reuse closed ports, that were used previously, and how to make it announce opened port on the external IP.

标签: java apache sshd