Esempio n. 1
0
 @Override
 @OnWebSocketConnect
 public void onConnect(Session session) {
   super.onConnect(session);
   this.session.setIdleTimeout(TimeUnit.MINUTES.toMillis(1));
   Connector con = null;
   try {
     ConnectorFactory cf = ConnectorFactory.getDefault();
     con = cf.createConnector();
   } catch (AgentProxyException e) {
     System.out.println(e);
   }
   IdentityRepository irepo = null;
   if (con != null) {
     RemoteIdentityRepository rrepo = new RemoteIdentityRepository(con);
     if (rrepo.getIdentities() != null && rrepo.getIdentities().size() > 0) {
       irepo = rrepo;
       jsch.setIdentityRepository(irepo);
     }
   }
   if (irepo == null) {
     String home = System.getProperty("user.home");
     String sshDir = home + File.separator + ".ssh" + File.separator;
     String[] defaultKeys =
         new String[] {
           sshDir + "id_ecdsa",
           sshDir + "id_id_ed25519",
           sshDir + "id_rsa",
           sshDir + "id_dsa",
           sshDir + "identity"
         };
     for (String nextKey : defaultKeys) {
       try {
         jsch.addIdentity(nextKey);
         log.fine("Key '" + nextKey + "'  added");
       } catch (JSchException e) {
         log.log(Level.FINE, "Key '" + nextKey + "'  not valid", e);
       }
     }
   }
   Map<String, List<String>> parameterMap = session.getUpgradeRequest().getParameterMap();
   String host = getStringParameter(parameterMap, "host", null);
   String connectHost = hostLookupService.getResolvableHostname(host);
   String user = getStringParameter(parameterMap, "user", null);
   if ("@admin".equals(user)) {
     user = hostLookupService.getAdminUserFor(host);
   }
   Resize resize = new Resize();
   resize.cols = getIntParameter(parameterMap, "cols", 80);
   resize.rows = getIntParameter(parameterMap, "rows", 24);
   try {
     java.util.Properties config = new java.util.Properties();
     config.put("StrictHostKeyChecking", "no");
     jschSession = jsch.getSession(user, connectHost, hostLookupService.getSshPort(host));
     jschSession.setConfig(config);
     jschSession.connect(60000);
     shell = (ChannelShell) jschSession.openChannel("shell");
     shell.setAgentForwarding(true);
     shell.setPtyType("vt102");
     shell.connect();
     shell.setPtySize(resize.cols, resize.rows, resize.getPixelWidth(), resize.getPixelHeight());
   } catch (JSchException e) {
     close(1, "Failed to create ssh session", e);
   }
   Runnable run;
   try {
     run =
         new RawSentOutputTask(
             session, new BufferedInputStream(shell.getInputStream(), BUFFER_LEN));
     Thread thread = new Thread(run);
     thread.start();
   } catch (IOException e) {
     close(2, "IOException while getting data from ssh", e);
   }
   try {
     inputToShell = new PrintStream(shell.getOutputStream(), true, "UTF-8");
   } catch (IOException e) {
     close(3, "IOException while creating write stream to ssh", e);
   }
 }
  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);
    }
  }