5

I'm looking for a way to connect to my remote server using ssh binding inside my java application. I enter the command like below inside my terminal to connect my server:

ssh -D 1234 username@w.x.y.z

then I can configure my browser socks ip & port to:

socks ip: 127.0.0.1
socks port: 1234

& use my server to browse inside internet

now please help me to do this in my java application.

currently I use a library called JSCH in my program but I couldn't get my application to work. Do you have any Idea or sample code or whatever for this problem ?

(notice that both SOCKS v4 & v5 should be supported inside the java library)

Mehdi
  • 3,795
  • 3
  • 36
  • 65

4 Answers4

2

You would get multiple options

-http://mina.apache.org/sshd-project/documentation.html Trusted Apache project with good support in form of user community,docs & examples I think this is what you were asking for. https://svn.apache.org/repos/asf/mina/sshd/trunk/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java

-http://www.jcraft.com/jsch/ Bad documentation but has been in existence for a long time.Sample code is pretty good.

http://code.google.com/p/ganymed-ssh-2/

Another lib with just sufficent documnetation.

Rohitdev
  • 866
  • 6
  • 15
1

Per https://www.bytefold.com/java-ssh-tunnel-with-dynamic-port-forwarding/ you can use Apache Mina to accomplish this:

Dependencies

    <dependency>
        <groupId>org.apache.mina</groupId>
        <artifactId>mina-core</artifactId>
        <version>3.0.0-M2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.sshd/sshd-core -->
    <dependency>
        <groupId>org.apache.sshd</groupId>
        <artifactId>sshd-core</artifactId>
        <version>2.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.sshd</groupId>
        <artifactId>sshd-putty</artifactId>
        <version>2.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.sshd</groupId>
        <artifactId>sshd-common</artifactId>
        <version>2.1.0</version>
    </dependency>

Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.auth.hostbased.HostKeyIdentityProvider;
import org.apache.sshd.client.keyverifier.AcceptAllServerKeyVerifier;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.config.keys.loader.pem.PEMResourceParserUtils;
import org.apache.sshd.common.config.keys.loader.putty.PuttyKeyUtils;
import org.apache.sshd.common.forward.PortForwardingEventListener;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.util.net.SshdSocketAddress;
import org.apache.sshd.server.channel.PuttyRequestHandler;
import org.apache.sshd.server.forward.AcceptAllForwardingFilter;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
/**
 * This class
 * 
 * @author Ankit Katiyar
 *
 */
public class AmazonTest {
    private static String BASTION_SERVER_PASSWORD = "P@ssword1";
    private static final String BASTION_SERVER_USER = "ec2-user";
    private static final String BASTION_SEREVR_HOST = "ec2-18-191-207-91.us-east-2.compute.amazonaws.com";
    private static final String URL_TO_ACCESS = "http://www.google.com";
    public static void main(String[] args) {
        try {
            
            
            Collection<KeyPair> keys = null;
            // OPtional loading keys from a PEM file
            //keys=PEMResourceParserUtils.getPEMResourceParserByAlgorithm("RSA").loadKeyPairs(ClassLoader.getSystemResource("local-ps-test.pem").toURI().toURL(), null);
            
            // Optional: Using Putty key for login 
             keys=PuttyKeyUtils.DEFAULT_INSTANCE.loadKeyPairs(ClassLoader.getSystemResource("local-ps-private-key.ppk").toURI().toURL(), null);
             
            SshClient client = SshClient.setUpDefaultClient();
            client.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
            client.setServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE);
            client.start();
            // using the client for multiple sessions...
            try (ClientSession session = client.connect(BASTION_SERVER_USER, BASTION_SEREVR_HOST, 22).verify()
                    .getSession()) {
                // IF you use password to login provide here
                // session.addPasswordIdentity(BASTION_SERVER_PASSWORD); // for password-based
                // authentication
                
                session.addPublicKeyIdentity(keys.iterator().next());
                // authentication
                // Note: can add BOTH password AND public key identities - depends on the
                // client/server security setup
                session.auth().verify(10000);
                // start using the session to run commands, do SCP/SFTP, create local/remote
                // port forwarding, etc...
                session.addPortForwardingEventListener(new PortForwardingEventListener() {
                    @Override
                    public void establishedDynamicTunnel(Session session, SshdSocketAddress local,
                            SshdSocketAddress boundAddress, Throwable reason) throws IOException {
                        // TODO Auto-generated method stub
                        PortForwardingEventListener.super.establishedDynamicTunnel(session, local, boundAddress, reason);
                        System.out.println("Dynamic Forword Tunnel is Ready");
                    }
                });
                SshdSocketAddress sshdSocketAddress = session
                        .startDynamicPortForwarding(new SshdSocketAddress("localhost", 8000));
                System.out.println("Host: " + sshdSocketAddress.getHostName());
                System.out.println("Port: " + sshdSocketAddress.getPort());
                // Create a Proxy object to work with
                Proxy proxy = new Proxy(Proxy.Type.SOCKS,
                        new InetSocketAddress(sshdSocketAddress.getHostName(), sshdSocketAddress.getPort()));
                /**
                 * Now you can use this proxy instance into any URL until this SSH session is active. 
                 */
                
                // TEST one URL
                HttpURLConnection connection = (HttpURLConnection) new URL(URL_TO_ACCESS).openConnection(proxy);
                System.out.println("Proxy work:" + connection.getURL());
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                System.out.println("================== Data From URL ==================\n");
                String inputLine;
                while ((inputLine = in.readLine()) != null)
                    System.out.println(inputLine);
                in.close();
                System.out.println("================== Data From URL ==================\n");
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

His project can be found at https://github.com/ankitkatiyar91/java-framework-examples/tree/master/java-tunneling

The dependencies might be out of date and the API might have changed but this should get you started. I got this working with the latest version of Apache Mina (2.1.4) within 30 minutes. Don't be thrown off by his use of version 3.0.0-M2 of mina-core. This version is actually older than version 2.1.4.

Gili
  • 86,244
  • 97
  • 390
  • 689
0

I had hacked such a program in scala using jsch as a sample program,

https://github.com/ymnk/dpfwds
ymnk
  • 1,145
  • 7
  • 7
-1

It makes sense to read documentation sometimes. There's a sample on JSch home page that does exactly what you need.

Eugene Mayevski 'Callback
  • 45,135
  • 8
  • 71
  • 121
  • This library should have something like this : setPortForwardingD if you read the documentation sometimes you will see that JSCH has something like setPortForwardingL & setPortForwardingR which are for Local & Remote port forwarding but that does not support Dynamic Port Forwarding – Mehdi Apr 06 '13 at 08:58
  • @Mehdi so you need a library capable for dynamic port forwarding? You are welcome to check our SecureBlackbox ( http://www.eldos.com/sbb/java-ssh.php ) . It supports dynamic port forwarding. – Eugene Mayevski 'Callback Apr 06 '13 at 09:30
  • As a checked SSHBlackBox jar file library I just found Local & Remote Forwarding for this as well ! – Mehdi Apr 06 '13 at 18:49
  • @Mehdi I am not sure that I understood your message correctly - have you found the functionality you need? As I said, what you are looking for IS supported. So if you didn't find it, please use technical support channels on EldoS site (http://www.eldos.com/support/) for assistance. – Eugene Mayevski 'Callback Apr 06 '13 at 18:54
  • I have read the complete features of java version of SSHBlackBox plus I watch very carefully to all forwarding classes inside the API they were something like this TElForwarding... which I don't remember exactly but It did not involve any Dynamic Port Forwarding ... Thanks man I will find a way for it, currently I have checked more than 10 java SSH library but none of them support this feature ! – Mehdi Apr 06 '13 at 19:14
  • here is exactly what I'm looking for: Java Library for SSH Dynamic Port Forwarding – Mehdi Apr 06 '13 at 19:16
  • @Mehdi Dynamic forwarding is enabled using TElSSHLocalPortForwarding.UseDynamicForwarding property . There's also a sample project in Samples\SSHBlackbox\Client\SimpleForwarding\Local folder. For more details please do contact our technical support. – Eugene Mayevski 'Callback Apr 06 '13 at 19:25
  • Thanks I'll check it out morrow & I'll tell you the result ;) – Mehdi Apr 06 '13 at 19:31
  • 1
    We decided to implement this function in our java application by running the linux command from inside our app. anyways thank you for your suggestion ! – Mehdi Apr 14 '13 at 14:57
  • @Mehdi May I humbly suggest you accept an answer and award a bounty in order to give credit where credit is due. – anttix May 12 '14 at 19:08