Search in sources :

Example 36 with Connection

use of com.trilead.ssh2.Connection in project wildfly by wildfly.

the class AsyncFutureInterceptorFactory method create.

@Override
public Interceptor create(final InterceptorFactoryContext context) {
    final SessionBeanComponent component = (SessionBeanComponent) context.getContextData().get(Component.class);
    if (component.isSecurityDomainKnown()) {
        return new Interceptor() {

            @Override
            public Object processInvocation(final InterceptorContext context) throws Exception {
                if (!context.isBlockingCaller()) {
                    return context.proceed();
                }
                final InterceptorContext asyncInterceptorContext = context.clone();
                asyncInterceptorContext.putPrivateData(InvocationType.class, InvocationType.ASYNC);
                final CancellationFlag flag = new CancellationFlag();
                final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class);
                final StartupCountdown.Frame frame = StartupCountdown.current();
                final SecurityIdentity currentIdentity = securityDomain == null ? null : securityDomain.getCurrentSecurityIdentity();
                final Connection remoteConnection = getConnection();
                Callable<Object> invocationTask = () -> {
                    setConnection(remoteConnection);
                    StartupCountdown.restore(frame);
                    try {
                        return asyncInterceptorContext.proceed();
                    } finally {
                        StartupCountdown.restore(null);
                        clearConnection();
                    }
                };
                final AsyncInvocationTask task = new AsyncInvocationTask(flag) {

                    @Override
                    protected Object runInvocation() throws Exception {
                        if (currentIdentity != null) {
                            return currentIdentity.runAs(invocationTask);
                        } else {
                            return invocationTask.call();
                        }
                    }
                };
                asyncInterceptorContext.putPrivateData(CancellationFlag.class, flag);
                asyncInterceptorContext.setBlockingCaller(false);
                return execute(component, task);
            }
        };
    } else {
        return new Interceptor() {

            @Override
            public Object processInvocation(final InterceptorContext context) throws Exception {
                if (!context.isBlockingCaller()) {
                    return context.proceed();
                }
                final InterceptorContext asyncInterceptorContext = context.clone();
                asyncInterceptorContext.putPrivateData(InvocationType.class, InvocationType.ASYNC);
                final CancellationFlag flag = new CancellationFlag();
                final SecurityContext securityContext;
                if (WildFlySecurityManager.isChecking()) {
                    securityContext = AccessController.doPrivileged(new PrivilegedAction<SecurityContext>() {

                        @Override
                        public SecurityContext run() {
                            return SecurityContextAssociation.getSecurityContext();
                        }
                    });
                } else {
                    securityContext = SecurityContextAssociation.getSecurityContext();
                }
                // clone the original security context so that changes to the original security context in a separate (caller/unrelated) thread doesn't affect
                // the security context associated with the async invocation thread
                final SecurityContext clonedSecurityContext;
                if (securityContext instanceof JBossSecurityContext) {
                    clonedSecurityContext = (SecurityContext) ((JBossSecurityContext) securityContext).clone();
                } else {
                    // we can't do anything if it isn't a JBossSecurityContext so just use the original one
                    clonedSecurityContext = securityContext;
                }
                final Connection remoteConnection = getConnection();
                final StartupCountdown.Frame frame = StartupCountdown.current();
                final AsyncInvocationTask task = new AsyncInvocationTask(flag) {

                    @Override
                    protected Object runInvocation() throws Exception {
                        setSecurityContextOnAssociation(clonedSecurityContext);
                        setConnection(remoteConnection);
                        StartupCountdown.restore(frame);
                        try {
                            return asyncInterceptorContext.proceed();
                        } finally {
                            StartupCountdown.restore(null);
                            try {
                                clearSecurityContextOnAssociation();
                            } finally {
                                clearConnection();
                            }
                        }
                    }
                };
                asyncInterceptorContext.putPrivateData(CancellationFlag.class, flag);
                asyncInterceptorContext.setBlockingCaller(false);
                return execute(component, task);
            }
        };
    }
}
Also used : Connection(org.jboss.remoting3.Connection) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain) SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) PrivilegedAction(java.security.PrivilegedAction) SessionBeanComponent(org.jboss.as.ejb3.component.session.SessionBeanComponent) InterceptorContext(org.jboss.invocation.InterceptorContext) SecurityContext(org.jboss.security.SecurityContext) JBossSecurityContext(org.jboss.security.plugins.JBossSecurityContext) JBossSecurityContext(org.jboss.security.plugins.JBossSecurityContext) SessionBeanComponent(org.jboss.as.ejb3.component.session.SessionBeanComponent) Component(org.jboss.as.ee.component.Component) Interceptor(org.jboss.invocation.Interceptor) StartupCountdown(org.jboss.as.ee.component.deployers.StartupCountdown)

Example 37 with Connection

use of com.trilead.ssh2.Connection in project intellij-community by JetBrains.

the class SshConnectionUtils method openConnection.

// we need project here since it could occur that the same repository/proxy would be used from different projects with different credentials
// though it is unlikely
public static Connection openConnection(final ConnectionSettings connectionSettings, final SshAuthentication authentication) throws AuthenticationException, IOException {
    final int port = connectionSettings.getPort() == -1 ? SSH_DEFAULT_PORT : connectionSettings.getPort();
    final Connection connection = new Connection(connectionSettings.getHostName(), port);
    final ProxyData proxy = SshProxyFactory.createAndRegister(connectionSettings);
    if (proxy != null) {
        connection.setProxyData(proxy);
    }
    connection.connect(null, connectionSettings.getConnectionTimeout(), connectionSettings.getConnectionTimeout());
    authentication.authenticate(connection);
    //HTTPProxyException
    return connection;
}
Also used : ProxyData(com.trilead.ssh2.ProxyData) Connection(com.trilead.ssh2.Connection)

Example 38 with Connection

use of com.trilead.ssh2.Connection in project intellij-community by JetBrains.

the class Session method requestX11Forwarding.

/**
	 * Request X11 forwarding for the current session.
	 * <p>
	 * You have to supply the name and port of your X-server.
	 * <p>
	 * This method may only be called before a program or shell is started in
	 * this session.
	 * 
	 * @param hostname the hostname of the real (target) X11 server (e.g., 127.0.0.1)
	 * @param port the port of the real (target) X11 server (e.g., 6010)
	 * @param cookie if non-null, then present this cookie to the real X11 server
	 * @param singleConnection if true, then the server is instructed to only forward one single
	 *        connection, no more connections shall be forwarded after first, or after the session
	 *        channel has been closed
	 * @throws IOException
	 */
public void requestX11Forwarding(String hostname, int port, byte[] cookie, boolean singleConnection) throws IOException {
    if (hostname == null)
        throw new IllegalArgumentException("hostname argument may not be null");
    synchronized (this) {
        /* The following is just a nicer error, we would catch it anyway later in the channel code */
        if (flag_closed)
            throw new IOException("This session is closed.");
        if (flag_x11_requested)
            throw new IOException("X11 forwarding was already requested.");
        if (flag_execution_started)
            throw new IOException("Cannot request X11 forwarding at this stage anymore, a remote execution has already started.");
        flag_x11_requested = true;
    }
    /* X11ServerData - used to store data about the target X11 server */
    X11ServerData x11data = new X11ServerData();
    x11data.hostname = hostname;
    x11data.port = port;
    x11data.x11_magic_cookie = cookie;
    /* if non-null, then present this cookie to the real X11 server */
    /* Generate fake cookie - this one is used between remote clients and our proxy */
    byte[] fakeCookie = new byte[16];
    String hexEncodedFakeCookie;
    while (true) {
        rnd.nextBytes(fakeCookie);
        /* Generate also hex representation of fake cookie */
        StringBuffer tmp = new StringBuffer(32);
        for (int i = 0; i < fakeCookie.length; i++) {
            String digit2 = Integer.toHexString(fakeCookie[i] & 0xff);
            tmp.append((digit2.length() == 2) ? digit2 : "0" + digit2);
        }
        hexEncodedFakeCookie = tmp.toString();
        if (cm.checkX11Cookie(hexEncodedFakeCookie) == null)
            break;
    }
    /* Ask for X11 forwarding */
    cm.requestX11(cn, singleConnection, "MIT-MAGIC-COOKIE-1", hexEncodedFakeCookie, 0);
    synchronized (this) {
        if (flag_closed == false) {
            this.x11FakeCookie = hexEncodedFakeCookie;
            cm.registerX11Cookie(hexEncodedFakeCookie, x11data);
        }
    }
/* Now it is safe to start remote X11 programs */
}
Also used : X11ServerData(com.trilead.ssh2.channel.X11ServerData) IOException(java.io.IOException)

Example 39 with Connection

use of com.trilead.ssh2.Connection in project intellij-community by JetBrains.

the class BasicWithHTTPProxy method main.

public static void main(String[] args) {
    String hostname = "my-ssh-server";
    String username = "joe";
    String password = "joespass";
    String proxyHost = "192.168.1.1";
    // default port used by squid
    int proxyPort = 3128;
    try {
        /* Create a connection instance */
        Connection conn = new Connection(hostname);
        /* We want to connect through a HTTP proxy */
        conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort));
        // if the proxy requires basic authentication:
        // conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort, "username", "secret"));
        /* Now connect (through the proxy) */
        conn.connect();
        /* Authenticate.
			 * If you get an IOException saying something like
			 * "Authentication method password not supported by the server at this stage."
			 * then please check the FAQ.
			 */
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        /* Create a session */
        Session sess = conn.openSession();
        sess.execCommand("uname -a && date && uptime && who");
        System.out.println("Here is some information about the remote host:");
        /* 
			 * This basic example does not handle stderr, which is sometimes dangerous
			 * (please read the FAQ).
			 */
        InputStream stdout = new StreamGobbler(sess.getStdout());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
        /* Show exit status, if available (otherwise "null") */
        System.out.println("ExitCode: " + sess.getExitStatus());
        /* Close this session */
        sess.close();
        /* Close the connection */
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(2);
    }
}
Also used : StreamGobbler(com.trilead.ssh2.StreamGobbler) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) HTTPProxyData(com.trilead.ssh2.HTTPProxyData) Session(com.trilead.ssh2.Session)

Example 40 with Connection

use of com.trilead.ssh2.Connection in project intellij-community by JetBrains.

the class PortForwarding method main.

public static void main(String[] args) {
    String hostname = "127.0.0.1";
    String username = "joe";
    // or "~/.ssh/id_dsa"
    File keyfile = new File("~/.ssh/id_rsa");
    // will be ignored if not needed
    String keyfilePass = "joespass";
    try {
        /* Create a connection instance */
        Connection conn = new Connection(hostname);
        /* Now connect */
        conn.connect();
        /* Authenticate */
        boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        /* ===== OK, now let's establish some local port forwardings ===== */
        /* Example Port Forwarding: -L 8080:www.icann.org:80 (OpenSSH notation)
			 * 
			 * This works by allocating a socket to listen on 8080 on the local interface (127.0.0.1).
			 * Whenever a connection is made to this port (127.0.0.1:8080), the connection is forwarded
			 * over the secure channel, and a connection is made to www.icann.org:80 from the remote
			 * machine (i.e., the ssh server).
			 * 
			 * (the above text is based partially on the OpenSSH man page)
			 */
        /* You can create as many of them as you want */
        LocalPortForwarder lpf1 = conn.createLocalPortForwarder(8080, "www.icann.org", 80);
        /* Now simply point your webbrowser to 127.0.0.1:8080 */
        /* (on the host where you execute this program)                         */
        /* ===== OK, now let's establish some remote port forwardings ===== */
        /* Example Port Forwarding: -R 127.0.0.1:8080:www.ripe.net:80 (OpenSSH notation)
			 * 
			 * Specifies that the port 127.0.0.1:8080 on the remote server is to be forwarded to the
			 * given host and port on the local side.  This works by allocating a socket to listen to port
			 * 8080 on the remote side (the ssh server), and whenever a connection is made to this port, the
			 * connection is forwarded over the secure channel, and a connection is made to
			 * www.ripe.net:80 by the Trilead SSH-2 library.
			 * 
			 * (the above text is based partially on the OpenSSH man page)
			 */
        /* You can create as many of them as you want */
        conn.requestRemotePortForwarding("127.0.0.1", 8080, "www.ripe.net", 80);
        /* Now, on the ssh server, if you connect to 127.0.0.1:8080, then the connection is forwarded
			 * through the secure tunnel to the library, which in turn will forward the connection
			 * to www.ripe.net:80. */
        /* Sleep a bit... (30 seconds) */
        sleepSomeTime(30000);
        /* Stop accepting remote connections that are being forwarded to www.ripe.net:80 */
        conn.cancelRemotePortForwarding(8080);
        /* Sleep a bit... (20 seconds) */
        sleepSomeTime(20000);
        /* Stop accepting connections on 127.0.0.1:8080 that are being forwarded to www.icann.org:80 */
        lpf1.close();
        /* Close the connection */
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(2);
    }
}
Also used : LocalPortForwarder(com.trilead.ssh2.LocalPortForwarder) Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException) File(java.io.File)

Aggregations

Connection (com.trilead.ssh2.Connection)36 Session (com.trilead.ssh2.Session)34 IOException (java.io.IOException)31 InputStream (java.io.InputStream)22 SCPClient (com.trilead.ssh2.SCPClient)15 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)14 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 ConfigurationException (javax.naming.ConfigurationException)6 Connection (org.jboss.remoting3.Connection)6 StreamGobbler (com.trilead.ssh2.StreamGobbler)5 File (java.io.File)4 Principal (java.security.Principal)4 HashMap (java.util.HashMap)4 Connection (okhttp3.Connection)4 SecurityIdentity (org.wildfly.security.auth.server.SecurityIdentity)4 BufferedReader (java.io.BufferedReader)3 InputStreamReader (java.io.InputStreamReader)3 Charset (java.nio.charset.Charset)3 TimeoutException (java.util.concurrent.TimeoutException)3