예제 #1
0
 /**
  * FIXME Comment this
  *
  * @param session
  * @param cmd
  * @return return code of the process.
  * @throws JSchException if there's an underlying problem exposed in SSH
  * @throws IOException if there's a problem attaching streams.
  * @throws TimeoutException if we exceeded our timeout
  */
 private int executeCommand(Session session, String cmd)
     throws JSchException, IOException, TimeoutException {
   final ChannelExec channel;
   session.setTimeout((int) maxwait);
   /* execute the command */
   channel = (ChannelExec) session.openChannel("exec");
   channel.setCommand(cmd);
   attachStreams(channel);
   project.log("executing command: " + cmd, Project.MSG_VERBOSE);
   channel.connect();
   try {
     waitFor(channel);
   } finally {
     streamHandler.stop();
     closeStreams(channel);
   }
   return channel.getExitStatus();
 }
예제 #2
0
  protected Session createSession(final RemoteFileConfiguration configuration)
      throws JSchException {
    final JSch jsch = new JSch();
    JSch.setLogger(new JSchLogger());

    SftpConfiguration sftpConfig = (SftpConfiguration) configuration;

    if (isNotEmpty(sftpConfig.getCiphers())) {
      LOG.debug("Using ciphers: {}", sftpConfig.getCiphers());
      Hashtable<String, String> ciphers = new Hashtable<String, String>();
      ciphers.put("cipher.s2c", sftpConfig.getCiphers());
      ciphers.put("cipher.c2s", sftpConfig.getCiphers());
      JSch.setConfig(ciphers);
    }

    if (isNotEmpty(sftpConfig.getPrivateKeyFile())) {
      LOG.debug("Using private keyfile: {}", sftpConfig.getPrivateKeyFile());
      if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
        jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyPassphrase());
      } else {
        jsch.addIdentity(sftpConfig.getPrivateKeyFile());
      }
    }

    if (sftpConfig.getPrivateKey() != null) {
      LOG.debug("Using private key information from byte array");
      byte[] passphrase = null;
      if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
        try {
          passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
          throw new JSchException("Cannot transform passphrase to byte[]", e);
        }
      }
      jsch.addIdentity("ID", sftpConfig.getPrivateKey(), null, passphrase);
    }

    if (sftpConfig.getPrivateKeyUri() != null) {
      LOG.debug("Using private key uri : {}", sftpConfig.getPrivateKeyUri());
      byte[] passphrase = null;
      if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
        try {
          passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
          throw new JSchException("Cannot transform passphrase to byte[]", e);
        }
      }
      try {
        InputStream is =
            ResourceHelper.resolveMandatoryResourceAsInputStream(
                endpoint.getCamelContext().getClassResolver(), sftpConfig.getPrivateKeyUri());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOHelper.copyAndCloseInput(is, bos);
        jsch.addIdentity("ID", bos.toByteArray(), null, passphrase);
      } catch (IOException e) {
        throw new JSchException("Cannot read resource: " + sftpConfig.getPrivateKeyUri(), e);
      }
    }

    if (sftpConfig.getKeyPair() != null) {
      LOG.debug("Using private key information from key pair");
      KeyPair keyPair = sftpConfig.getKeyPair();
      if (keyPair.getPrivate() != null && keyPair.getPublic() != null) {
        if (keyPair.getPrivate() instanceof RSAPrivateKey
            && keyPair.getPublic() instanceof RSAPublicKey) {
          jsch.addIdentity(new RSAKeyPairIdentity("ID", keyPair), null);
        } else if (keyPair.getPrivate() instanceof DSAPrivateKey
            && keyPair.getPublic() instanceof DSAPublicKey) {
          jsch.addIdentity(new DSAKeyPairIdentity("ID", keyPair), null);
        } else {
          LOG.warn("Only RSA and DSA key pairs are supported");
        }
      } else {
        LOG.warn("PrivateKey and PublicKey in the KeyPair must be filled");
      }
    }

    if (isNotEmpty(sftpConfig.getKnownHostsFile())) {
      LOG.debug("Using knownhosts file: {}", sftpConfig.getKnownHostsFile());
      jsch.setKnownHosts(sftpConfig.getKnownHostsFile());
    }

    if (isNotEmpty(sftpConfig.getKnownHostsUri())) {
      LOG.debug("Using knownhosts uri: {}", sftpConfig.getKnownHostsUri());
      try {
        InputStream is =
            ResourceHelper.resolveMandatoryResourceAsInputStream(
                endpoint.getCamelContext().getClassResolver(), sftpConfig.getKnownHostsUri());
        jsch.setKnownHosts(is);
      } catch (IOException e) {
        throw new JSchException("Cannot read resource: " + sftpConfig.getKnownHostsUri(), e);
      }
    }

    if (sftpConfig.getKnownHosts() != null) {
      LOG.debug("Using knownhosts information from byte array");
      jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));
    }

    final Session session =
        jsch.getSession(
            configuration.getUsername(), configuration.getHost(), configuration.getPort());

    if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {
      LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking());
      session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking());
    }

    session.setServerAliveInterval(sftpConfig.getServerAliveInterval());
    session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());

    // compression
    if (sftpConfig.getCompression() > 0) {
      LOG.debug("Using compression: {}", sftpConfig.getCompression());
      session.setConfig("compression.s2c", "[email protected],zlib,none");
      session.setConfig("compression.c2s", "[email protected],zlib,none");
      session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression()));
    }

    // set the PreferredAuthentications
    if (sftpConfig.getPreferredAuthentications() != null) {
      LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications());
      session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications());
    }

    // set user information
    session.setUserInfo(
        new ExtendedUserInfo() {
          public String getPassphrase() {
            return null;
          }

          public String getPassword() {
            return configuration.getPassword();
          }

          public boolean promptPassword(String s) {
            return true;
          }

          public boolean promptPassphrase(String s) {
            return true;
          }

          public boolean promptYesNo(String s) {
            LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no.");
            // Return 'false' indicating modification of the hosts file is disabled.
            return false;
          }

          public void showMessage(String s) {
            LOG.trace("Message received from Server: " + s);
          }

          public String[] promptKeyboardInteractive(
              String destination,
              String name,
              String instruction,
              String[] prompt,
              boolean[] echo) {
            // must return an empty array if password is null
            if (configuration.getPassword() == null) {
              return new String[0];
            } else {
              return new String[] {configuration.getPassword()};
            }
          }
        });

    // set the SO_TIMEOUT for the time after the connect phase
    if (configuration.getSoTimeout() > 0) {
      session.setTimeout(configuration.getSoTimeout());
    }

    // set proxy if configured
    if (proxy != null) {
      session.setProxy(proxy);
    }

    return session;
  }
예제 #3
0
  public void openConnectionInternal() throws AuthenticationException {
    if (authenticationInfo == null) {
      authenticationInfo = new AuthenticationInfo();
    }

    if (!interactive) {
      uIKeyboardInteractive = null;
      setInteractiveUserInfo(new NullInteractiveUserInfo());
    }

    JSch sch = new JSch();

    File privateKey;
    try {
      privateKey = ScpHelper.getPrivateKey(authenticationInfo);
    } catch (FileNotFoundException e) {
      throw new AuthenticationException(e.getMessage());
    }

    try {
      Connector connector = ConnectorFactory.getDefault().createConnector();
      if (connector != null) {
        IdentityRepository repo = new RemoteIdentityRepository(connector);
        sch.setIdentityRepository(repo);
      }
    } catch (AgentProxyException e) {
      fireSessionDebug("Unable to connect to agent: " + e.toString());
    }

    if (privateKey != null && privateKey.exists()) {
      fireSessionDebug("Using private key: " + privateKey);
      try {
        sch.addIdentity(privateKey.getAbsolutePath(), authenticationInfo.getPassphrase());
      } catch (JSchException e) {
        throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e);
      }
    }

    String host = getRepository().getHost();
    int port =
        repository.getPort() == WagonConstants.UNKNOWN_PORT
            ? ScpHelper.DEFAULT_SSH_PORT
            : repository.getPort();
    try {
      String userName = authenticationInfo.getUserName();
      if (userName == null) {
        userName = System.getProperty("user.name");
      }
      session = sch.getSession(userName, host, port);
      session.setTimeout(getTimeout());
    } catch (JSchException e) {
      throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e);
    }

    Proxy proxy = null;
    ProxyInfo proxyInfo = getProxyInfo(ProxyInfo.PROXY_SOCKS5, getRepository().getHost());
    if (proxyInfo != null && proxyInfo.getHost() != null) {
      proxy = new ProxySOCKS5(proxyInfo.getHost(), proxyInfo.getPort());
      ((ProxySOCKS5) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword());
    } else {
      proxyInfo = getProxyInfo(ProxyInfo.PROXY_HTTP, getRepository().getHost());
      if (proxyInfo != null && proxyInfo.getHost() != null) {
        proxy = new ProxyHTTP(proxyInfo.getHost(), proxyInfo.getPort());
        ((ProxyHTTP) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword());
      } else {
        // Backwards compatibility
        proxyInfo = getProxyInfo(getRepository().getProtocol(), getRepository().getHost());
        if (proxyInfo != null && proxyInfo.getHost() != null) {
          // if port == 1080 we will use SOCKS5 Proxy, otherwise will use HTTP Proxy
          if (proxyInfo.getPort() == SOCKS5_PROXY_PORT) {
            proxy = new ProxySOCKS5(proxyInfo.getHost(), proxyInfo.getPort());
            ((ProxySOCKS5) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword());
          } else {
            proxy = new ProxyHTTP(proxyInfo.getHost(), proxyInfo.getPort());
            ((ProxyHTTP) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword());
          }
        }
      }
    }
    session.setProxy(proxy);

    // username and password will be given via UserInfo interface.
    UserInfo ui = new WagonUserInfo(authenticationInfo, getInteractiveUserInfo());

    if (uIKeyboardInteractive != null) {
      ui = new UserInfoUIKeyboardInteractiveProxy(ui, uIKeyboardInteractive);
    }

    Properties config = new Properties();
    if (getKnownHostsProvider() != null) {
      try {
        String contents = getKnownHostsProvider().getContents();
        if (contents != null) {
          sch.setKnownHosts(new StringInputStream(contents));
        }
      } catch (JSchException e) {
        // continue without known_hosts
      }
      config.setProperty("StrictHostKeyChecking", getKnownHostsProvider().getHostKeyChecking());
    }

    if (authenticationInfo.getPassword() != null) {
      config.setProperty(
          "PreferredAuthentications", "gssapi-with-mic,publickey,password,keyboard-interactive");
    }

    config.setProperty("BatchMode", interactive ? "no" : "yes");

    session.setConfig(config);

    session.setUserInfo(ui);

    StringWriter stringWriter = new StringWriter();
    try {
      session.connect();

      if (getKnownHostsProvider() != null) {
        PrintWriter w = new PrintWriter(stringWriter);

        HostKeyRepository hkr = sch.getHostKeyRepository();
        HostKey[] keys = hkr.getHostKey();

        for (int i = 0; keys != null && i < keys.length; i++) {
          HostKey key = keys[i];
          w.println(key.getHost() + " " + key.getType() + " " + key.getKey());
        }
      }
    } catch (JSchException e) {
      if (e.getMessage().startsWith("UnknownHostKey:")
          || e.getMessage().startsWith("reject HostKey:")) {
        throw new UnknownHostException(host, e);
      } else if (e.getMessage().contains("HostKey has been changed")) {
        throw new KnownHostChangedException(host, e);
      } else {
        throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e);
      }
    }

    try {
      getKnownHostsProvider().storeKnownHosts(stringWriter.toString());
    } catch (IOException e) {
      closeConnection();

      throw new AuthenticationException(
          "Connection aborted - failed to write to known_hosts. Reason: " + e.getMessage(), e);
    }
  }
예제 #4
-1
 @Override
 public Session create() throws Exception {
   JSch jsch = new JSch();
   session =
       jsch.getSession(
           loginCredentials.getUser(),
           hostAndPort.getHostText(),
           hostAndPort.getPortOrDefault(22));
   if (sessionTimeout != 0) session.setTimeout(sessionTimeout);
   if (loginCredentials.getPrivateKey() == null) {
     session.setPassword(loginCredentials.getPassword());
   } else {
     byte[] privateKey = loginCredentials.getPrivateKey().getBytes();
     if (CredentialUtils.isPrivateKeyEncrypted(privateKey)) {
       throw new IllegalArgumentException(
           "JschSshClientModule does not support private keys that require a passphrase");
     }
     jsch.addIdentity(
         loginCredentials.getUser(),
         Arrays.copyOf(privateKey, privateKey.length),
         null,
         emptyPassPhrase);
   }
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect(connectTimeout);
   return session;
 }
예제 #5
-1
 private void newSession() throws JSchException {
   JSch jsch = new JSch();
   session = null;
   try {
     session = jsch.getSession(username, host, port);
     if (timeout != 0) session.setTimeout(timeout);
     logger.debug("%s@%s:%d: Session created.", username, host, port);
     if (password != null) {
       session.setPassword(password);
     } else {
       // jsch wipes out your private key
       jsch.addIdentity(
           username, Arrays.copyOf(privateKey, privateKey.length), null, emptyPassPhrase);
     }
   } catch (JSchException e) {
     throw new SshException(
         String.format("%s@%s:%d: Error creating session.", username, host, port), e);
   }
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect();
   logger.debug("%s@%s:%d: Session connected.", username, host, port);
 }