com.jcraft.jsch.ProxyHTTP Java Examples

The following examples show how to use com.jcraft.jsch.ProxyHTTP. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SFTPEnvironmentTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
private void initializeFully(SFTPEnvironment env) {
    env.withUsername(UUID.randomUUID().toString());
    env.withConnectTimeout(1000);
    env.withProxy(new ProxyHTTP("localhost"));
    env.withUserInfo(new SimpleUserInfo(UUID.randomUUID().toString().toCharArray()));
    env.withPassword(UUID.randomUUID().toString().toCharArray());
    env.withConfig(System.getProperties());
    env.withSocketFactory(new TestSocketFactory());
    env.withTimeout(1000);
    env.withClientVersion("SSH-2");
    env.withHostKeyAlias("alias");
    env.withServerAliveInterval(500);
    env.withServerAliveCountMax(5);
    env.withIdentityRepository(new TestIdentityRepository());
    env.withIdentity(IdentityTest.fromFiles());
    env.withHostKeyRepository(new TestHostKeyRepository());
    env.withKnownHosts(new File("known_hosts"));
    env.withAgentForwarding(false);
    env.withFilenameEncoding("UTF-8");
    env.withDefaultDirectory("/");
    env.withClientConnectionCount(5);
    env.withFileSystemExceptionFactory(DefaultFileSystemExceptionFactory.INSTANCE);
}
 
Example #2
Source File: PropertyBasedSshSessionFactoryTest.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void proxySettingsIsUsed() {
	JGitEnvironmentProperties sshProperties = new JGitEnvironmentProperties();
	sshProperties.setPrivateKey(PRIVATE_KEY);
	Map<ProxyHostProperties.ProxyForScheme, ProxyHostProperties> map = new HashMap<>();
	ProxyHostProperties proxyHostProperties = new ProxyHostProperties();
	proxyHostProperties.setUsername("user");
	proxyHostProperties.setPassword("password");
	map.put(ProxyHostProperties.ProxyForScheme.HTTP, proxyHostProperties);

	sshProperties.setProxy(map);
	setupSessionFactory(sshProperties);

	this.factory.configure(this.hc, this.session);
	ArgumentCaptor<ProxyHTTP> captor = ArgumentCaptor.forClass(ProxyHTTP.class);

	verify(this.session).setProxy(captor.capture());
	assertThat(captor.getValue()).isNotNull();
	verify(this.proxyMock).setUserPasswd("user", "password");
}
 
Example #3
Source File: SFTPEnvironmentSetterTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
static Stream<Arguments> testSetter() {
    Arguments[] arguments = {
            arguments("withUsername", "username", UUID.randomUUID().toString()),
            arguments("withConnectTimeout", "connectTimeout", 1000),
            arguments("withProxy", "proxy", new ProxyHTTP("localhost")),
            arguments("withUserInfo", "userInfo", new SimpleUserInfo(UUID.randomUUID().toString().toCharArray())),
            arguments("withPassword", "password", UUID.randomUUID().toString().toCharArray()),
            arguments("withConfig", "config", System.getProperties()),
            arguments("withSocketFactory", "socketFactory", new TestSocketFactory()),
            arguments("withTimeout", "timeOut", 1000),
            arguments("withClientVersion", "clientVersion", "SSH-2"),
            arguments("withHostKeyAlias", "hostKeyAlias", "alias"),
            arguments("withServerAliveInterval", "serverAliveInterval", 500),
            arguments("withServerAliveCountMax", "serverAliveCountMax", 5),
            arguments("withIdentityRepository", "identityRepository", new TestIdentityRepository()),
            arguments("withIdentities", "identities", Collections.singletonList(IdentityTest.fromFiles())),
            arguments("withHostKeyRepository", "hostKeyRepository", new TestHostKeyRepository()),
            arguments("withKnownHosts", "knownHosts", new File("known_hosts")),
            arguments("withAgentForwarding", "agentForwarding", false),
            arguments("withFilenameEncoding", "filenameEncoding", "UTF-8"),
            arguments("withDefaultDirectory", "defaultDir", "/"),
            arguments("withClientConnectionCount", "clientConnectionCount", 5),
            arguments("withClientConnectionWaitTimeout", "clientConnectionWaitTimeout", 1000L),
            arguments("withFileSystemExceptionFactory", "fileSystemExceptionFactory", DefaultFileSystemExceptionFactory.INSTANCE),
            arguments("withActualTotalSpaceCalculation", "calculateActualTotalSpace", false),
    };
    return Arrays.stream(arguments);
}
 
Example #4
Source File: PooledSFTPConnection.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Proxy[] getProxies() {
	String proxyString = authority.getProxyString();
	if (!StringUtils.isEmpty(proxyString)) {
		java.net.Proxy proxy = FileUtils.getProxy(authority.getProxyString());
		if ((proxy != null) && (proxy.type() != Type.DIRECT)) {
			URI proxyUri = URI.create(proxyString);
			String hostName = proxyUri.getHost();
			int port = proxyUri.getPort();
			String userInfo = proxyUri.getUserInfo();
			org.jetel.util.protocols.UserInfo proxyCredentials = null;
			if (userInfo != null) {
				proxyCredentials = new org.jetel.util.protocols.UserInfo(userInfo);
			}
			switch (proxy.type()) {
			case HTTP:
				ProxyHTTP proxyHttp = (port >= 0) ? new ProxyHTTP(hostName, port) : new ProxyHTTP(hostName);
				if (proxyCredentials != null) {
					proxyHttp.setUserPasswd(proxyCredentials.getUser(), proxyCredentials.getPassword());
				}
				return new Proxy[] {proxyHttp};
			case SOCKS:
				ProxySOCKS4 proxySocks4 = (port >= 0) ? new ProxySOCKS4(hostName, port) : new ProxySOCKS4(hostName);
				ProxySOCKS5 proxySocks5 = (port >= 0) ? new ProxySOCKS5(hostName, port) : new ProxySOCKS5(hostName);
				if (proxyCredentials != null) {
					proxySocks4.setUserPasswd(proxyCredentials.getUser(), proxyCredentials.getPassword());
					proxySocks5.setUserPasswd(proxyCredentials.getUser(), proxyCredentials.getPassword());
				}
				return new Proxy[] {proxySocks5, proxySocks4};
			case DIRECT:
				return new Proxy[1];
			}
		}
	}
	
	return new Proxy[1];
}
 
Example #5
Source File: HMSshSession.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param host host for the session.
 * @param user the user.
 * @param pwd the password.
 * @throws Exception
 */
public HMSshSession( String host, int port, String user, String pwd ) throws Exception {
    session = jsch.getSession(user, host, port);
    UserInfo ui = new HMUserInfo(pwd);
    session.setUserInfo(ui);
    session.setPassword(ui.getPassword().getBytes());
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);

    try {
        String doProxy = SshUtilities.getPreference(HM_PREF_PROXYCHECK, "false");
        if (Boolean.parseBoolean(doProxy)) {
            String proxyHost = SshUtilities.getPreference(HM_PREF_PROXYHOST, "");
            String proxyPort = SshUtilities.getPreference(HM_PREF_PROXYPORT, "");
            String proxyUser = SshUtilities.getPreference(HM_PREF_PROXYUSER, "");
            String proxyPwd = SshUtilities.getPreference(HM_PREF_PROXYPWD, "");

            int proxPort = Integer.parseInt(proxyPort);
            ProxyHTTP proxyHTTP = new ProxyHTTP(proxyHost, proxPort);
            if (proxyUser.length() > 0 && proxyPwd.length() > 0) {
                proxyHTTP.setUserPasswd(proxyUser, proxyPwd);
            }
            session.setProxy(proxyHTTP);
        }
    } catch (Exception e) {
        Logger.INSTANCE.insertError("HMSshSession", "Error setting proxy", e);
    }

    session.connect(3000);
}
 
Example #6
Source File: PropertyBasedSshSessionFactory.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(Host hc, Session session) {
	JGitEnvironmentProperties sshProperties = this.sshKeysByHostname
			.get(hc.getHostName());
	String hostKeyAlgorithm = sshProperties.getHostKeyAlgorithm();
	if (hostKeyAlgorithm != null) {
		session.setConfig(SERVER_HOST_KEY, hostKeyAlgorithm);
	}
	if (sshProperties.getHostKey() == null
			|| !sshProperties.isStrictHostKeyChecking()) {
		session.setConfig(STRICT_HOST_KEY_CHECKING, NO_OPTION);
	}
	else {
		session.setConfig(STRICT_HOST_KEY_CHECKING, YES_OPTION);
	}
	String preferredAuthentications = sshProperties.getPreferredAuthentications();
	if (preferredAuthentications != null) {
		session.setConfig(PREFERRED_AUTHENTICATIONS, preferredAuthentications);
	}

	ProxyHostProperties proxyHostProperties = sshProperties.getProxy()
			.get(ProxyHostProperties.ProxyForScheme.HTTP);
	if (proxyHostProperties != null) {
		ProxyHTTP proxy = createProxy(proxyHostProperties);
		proxy.setUserPasswd(proxyHostProperties.getUsername(),
				proxyHostProperties.getPassword());
		session.setProxy(proxy);
	}
}
 
Example #7
Source File: PropertyBasedSshSessionFactoryTest.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
private void setupSessionFactory(JGitEnvironmentProperties sshKey) {
	Map<String, JGitEnvironmentProperties> sshKeysByHostname = new HashMap<>();
	sshKeysByHostname.put(SshUriPropertyProcessor.getHostname(sshKey.getUri()),
			sshKey);
	this.factory = new PropertyBasedSshSessionFactory(sshKeysByHostname, this.jSch) {

		@Override
		protected ProxyHTTP createProxy(ProxyHostProperties proxyHostProperties) {
			return proxyMock;
		}
	};
	when(this.hc.getHostName())
			.thenReturn(SshUriPropertyProcessor.getHostname(sshKey.getUri()));
	when(this.jSch.getHostKeyRepository()).thenReturn(this.hostKeyRepository);
}
 
Example #8
Source File: ProxyUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public static ProxyHTTP getHTTPProxy(String proxyHost, String proxyPort, String proxyUsername, String proxyPassword) {
    if (!StringUtilities.isEmpty(proxyHost)) {
        int portForProxy = getPortValue(proxyPort, Constants.DEFAULT_PROXY_PORT);
        return createHTTPProxy(proxyHost, portForProxy, proxyUsername, proxyPassword);
    } else {
        return null;
    }
}
 
Example #9
Source File: ProxyUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public static ProxyHTTP createHTTPProxy(String proxyHost, int proxyPort, String proxyUsername, String proxyPassword){
    ProxyConnectionDetails proxyConnectionDetails = new ProxyConnectionDetails(proxyHost, proxyPort, proxyUsername, proxyPassword);
    ProxyHTTP proxyHTTP = new ProxyHTTP(proxyConnectionDetails.getProxyHost(), proxyConnectionDetails.getProxyPort());
    String username = (StringUtilities.isEmpty(proxyUsername) ? null : proxyUsername);
    String password = (StringUtilities.isEmpty(proxyPassword) ? null : proxyPassword);
    proxyHTTP.setUserPasswd(username, password);
    return proxyHTTP;
}
 
Example #10
Source File: JGitSshSessionFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private com.jcraft.jsch.Proxy createProxy (String proxyHost, int proxyPort) {
    return USE_PROXY_TUNNELING
            ? new ProxyHTTP(proxyHost, proxyPort)
            : new ProxySOCKS5(proxyHost, proxyPort);
}
 
Example #11
Source File: SftpFsHelper.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/**
 * Opens up a connection to specified host using the username. Connects to the source using a private key without
 * prompting for a password. This method does not support connecting to a source using a password, only by private
 * key
 * @throws org.apache.gobblin.source.extractor.filebased.FileBasedHelperException
 */
@Override
public void connect() throws FileBasedHelperException {

  String privateKey = PasswordManager.getInstance(this.state)
      .readPassword(this.state.getProp(ConfigurationKeys.SOURCE_CONN_PRIVATE_KEY));
  String password = PasswordManager.getInstance(this.state)
      .readPassword(this.state.getProp(ConfigurationKeys.SOURCE_CONN_PASSWORD));
  String knownHosts = this.state.getProp(ConfigurationKeys.SOURCE_CONN_KNOWN_HOSTS);

  String userName = this.state.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME);
  String hostName = this.state.getProp(ConfigurationKeys.SOURCE_CONN_HOST_NAME);
  int port = this.state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_PORT, ConfigurationKeys.SOURCE_CONN_DEFAULT_PORT);

  String proxyHost = this.state.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL);
  int proxyPort = this.state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT, -1);

  JSch.setLogger(new JSchLogger());
  JSch jsch = new JSch();

  log.info("Attempting to connect to source via SFTP with" + " privateKey: " + privateKey + " knownHosts: "
      + knownHosts + " userName: " + userName + " hostName: " + hostName + " port: " + port + " proxyHost: "
      + proxyHost + " proxyPort: " + proxyPort);

  try {

    if (!Strings.isNullOrEmpty(privateKey)) {
      List<IdentityStrategy> identityStrategies = ImmutableList.of(new LocalFileIdentityStrategy(),
          new DistributedCacheIdentityStrategy(), new HDFSIdentityStrategy());

      for (IdentityStrategy identityStrategy : identityStrategies) {
        if (identityStrategy.setIdentity(privateKey, jsch)) {
          break;
        }
      }
    }

    this.session = jsch.getSession(userName, hostName, port);
    this.session.setConfig("PreferredAuthentications", "publickey,password");

    if (Strings.isNullOrEmpty(knownHosts)) {
      log.info("Known hosts path is not set, StrictHostKeyChecking will be turned off");
      this.session.setConfig("StrictHostKeyChecking", "no");
    } else {
      jsch.setKnownHosts(knownHosts);
    }

    if (!Strings.isNullOrEmpty(password)) {
      this.session.setPassword(password);
    }

    if (proxyHost != null && proxyPort >= 0) {
      this.session.setProxy(new ProxyHTTP(proxyHost, proxyPort));
    }

    UserInfo ui = new MyUserInfo();
    this.session.setUserInfo(ui);
    this.session.setDaemonThread(true);
    this.session.connect();

    log.info("Finished connecting to source");
  } catch (JSchException e) {
    if (this.session != null) {
      this.session.disconnect();
    }
    log.error(e.getMessage(), e);
    throw new FileBasedHelperException("Cannot connect to SFTP source", e);
  }
}
 
Example #12
Source File: PropertyBasedSshSessionFactory.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
protected ProxyHTTP createProxy(ProxyHostProperties proxyHostProperties) {
	return new ProxyHTTP(proxyHostProperties.getHost(),
			proxyHostProperties.getPort());
}
 
Example #13
Source File: ScoreSSHShellCommand.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
public Map<String, String> execute(SSHShellInputs sshShellInputs) {
    Map<String, String> returnResult = new HashMap<>();
    SSHService service = null;
    boolean providerAdded = addSecurityProvider();
    String sessionId = "";

    try {
        if (StringUtilities.isEmpty(sshShellInputs.getCommand())) {
            throw new RuntimeException(COMMAND_IS_NOT_SPECIFIED_MESSAGE);
        }
        if (sshShellInputs.getArguments() != null) {
            sshShellInputs.setCommand(sshShellInputs.getCommand() + " " + sshShellInputs.getArguments());
        }

        int portNumber = StringUtils.toInt(sshShellInputs.getPort(), Constants.DEFAULT_PORT);
        String knownHostsPolicy = StringUtils.toNotEmptyString(sshShellInputs.getKnownHostsPolicy(), Constants.DEFAULT_KNOWN_HOSTS_POLICY);
        Path knownHostsPath = StringUtils.toPath(sshShellInputs.getKnownHostsPath(), Constants.DEFAULT_KNOWN_HOSTS_PATH);

        sessionId = "sshSession:" + sshShellInputs.getHost() + "-" + portNumber + "-" + sshShellInputs.getUsername();

        // configure ssh parameters
        ConnectionDetails connection = new ConnectionDetails(sshShellInputs.getHost(), portNumber, sshShellInputs.getUsername(), sshShellInputs.getPassword());
        IdentityKey identityKey = IdentityKeyUtils.getIdentityKey(sshShellInputs.getPrivateKeyFile(), sshShellInputs.getPrivateKeyData(), sshShellInputs.getPassword());
        KnownHostsFile knownHostsFile = new KnownHostsFile(knownHostsPath, knownHostsPolicy);

        // get the cached SSH session
        service = getSshServiceFromCache(sshShellInputs, sessionId);
        boolean saveSSHSession = false;
        if (service == null || !service.isConnected()) {
            saveSSHSession = true;
            ProxyHTTP proxyHTTP = ProxyUtils.getHTTPProxy(sshShellInputs.getProxyHost(), sshShellInputs.getProxyPort(), sshShellInputs.getProxyUsername(), sshShellInputs.getProxyPassword());
            service = new SSHServiceImpl(connection, identityKey, knownHostsFile, sshShellInputs.getConnectTimeout(), sshShellInputs.isAllowExpectCommands(), proxyHTTP, sshShellInputs.getAllowedCiphers());
        }

        runSSHCommand(sshShellInputs, returnResult, service, sessionId, saveSSHSession);
    } catch (Exception e) {
        if (service != null) {
            cleanupService(sshShellInputs, service, sessionId);
        }
        populateResult(returnResult, e);
    } finally {
        if (providerAdded) {
            removeSecurityProvider();
        }
    }
    return returnResult;
}
 
Example #14
Source File: SshConnectionImpl.java    From gerrit-events with MIT License 4 votes vote down vote up
/**
 * Connects the connection.
 * @throws IOException if the unfortunate happens.
 */
@Override
public synchronized void connect() throws IOException {
    logger.debug("connecting...");
    Authentication auth = authentication;
    if (updater != null) {
        Authentication updatedAuth = updater.updateAuthentication(authentication);
        if (updatedAuth != null && auth != updatedAuth) {
            auth = updatedAuth;
        }
    }
    try {
        client = new JSch();
        if (auth.getPrivateKeyPhrase() == null) {
            client.addIdentity(auth.getPrivateKeyFile().getAbsolutePath(),
                    auth.getPrivateKeyFilePassword());
        } else {
            client.addIdentity(auth.getUsername(), auth.getPrivateKeyPhrase(), null,
                    auth.getPrivateKeyFilePassword().getBytes("UTF-8"));
        }
        client.setHostKeyRepository(new BlindHostKeyRepository());
        connectSession = client.getSession(auth.getUsername(), host, port);
        connectSession.setConfig("PreferredAuthentications", "publickey");
        if (proxy != null && !proxy.isEmpty()) {
            String[] splitted = proxy.split(":");
            if (splitted.length > 2 && splitted[1].length() >= PROTO_HOST_DELIM_LENGTH) {
                String pproto = splitted[0];
                String phost = splitted[1].substring(2);
                int pport = Integer.parseInt(splitted[2]);
                if (pproto.equals("socks5") || pproto.equals("http")) {
                    if (pproto.equals("socks5")) {
                         connectSession.setProxy(new ProxySOCKS5(phost, pport));
                    } else {
                         connectSession.setProxy(new ProxyHTTP(phost, pport));
                    }
                } else {
                    throw new MalformedURLException("Only http and socks5 protocols are supported");
                }
            } else {
                throw new MalformedURLException(proxy);
            }
        }
        connectSession.connect(this.connectionTimeout);
        logger.debug("Connected: {}", connectSession.isConnected());
        connectSession.setServerAliveInterval(ALIVE_INTERVAL);
    } catch (JSchException ex) {
        throw new SshException(ex);
    }
}
 
Example #15
Source File: SftpClientFactory.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
private static ProxyHTTP createProxyHTTP(final String proxyHost, final int proxyPort) {
    return proxyPort == 0 ? new ProxyHTTP(proxyHost) : new ProxyHTTP(proxyHost, proxyPort);
}