Пример #1
0
 /**
  * Try public key
  *
  * @param c a ssh connection
  * @param keyPath a path to key
  * @return true if authentication is successful
  */
 private boolean tryPublicKey(final Connection c, final String keyPath) {
   try {
     final File file = new File(keyPath);
     if (file.exists()) {
       // if encrypted ask user for passphrase
       String passphrase = null;
       char[] text = FileUtil.loadFileText(file);
       if (isEncryptedKey(text)) {
         // need to ask passphrase from user
         int i;
         for (i = myHost.getNumberOfPasswordPrompts(); i > 0; i--) {
           passphrase =
               myXmlRpcClient.askPassphrase(
                   myHandlerNo, getUserHostString(), keyPath, myLastError);
           if (passphrase == null) {
             // if no passphrase was entered, just return false and try something other
             return false;
           } else {
             try {
               PEMDecoder.decode(text, passphrase);
               myLastError = "";
             } catch (IOException e) {
               // decoding failed
               myLastError = GitBundle.message("sshmain.invalidpassphrase", keyPath);
               continue;
             }
             break;
           }
         }
         if (i == 0) {
           myLastError =
               GitBundle.message(
                   "sshmain.too.mush.passphrase.guesses",
                   keyPath,
                   myHost.getNumberOfPasswordPrompts());
           return false;
         }
       }
       // try authentication
       if (c.authenticateWithPublicKey(myHost.getUser(), text, passphrase)) {
         myLastError = "";
         return true;
       } else {
         if (passphrase != null) {
           // mark as failed authentication only if passphrase were asked
           myLastError = GitBundle.message("sshmain.pk.authenitication.failed", keyPath);
         } else {
           myLastError = "";
         }
       }
     }
     return false;
   } catch (Exception e) {
     return false;
   }
 }
Пример #2
0
  private void authenticate() {

    try {
      if (connection.authenticateWithNone(profile.getUser())) {
        Log.d(TAG, "Authenticate with none");
        return;
      }
    } catch (Exception e) {
      Log.d(TAG, "Host does not support 'none' authentication.");
    }

    try {
      if (connection.isAuthMethodAvailable(profile.getUser(), AUTH_PUBLICKEY)) {
        File f = new File(profile.getKeyPath());
        if (f.exists()) if (profile.getPassword().equals("")) profile.setPassword(null);
        if (connection.authenticateWithPublicKey(profile.getUser(), f, profile.getPassword())) {
          Log.d(TAG, "Authenticate with public key");
          return;
        }
      }
    } catch (Exception e) {
      Log.d(TAG, "Host does not support 'Public key' authentication.");
    }

    try {
      if (connection.isAuthMethodAvailable(profile.getUser(), AUTH_PASSWORD)) {
        if (connection.authenticateWithPassword(profile.getUser(), profile.getPassword())) {
          Log.d(TAG, "Authenticate with password");
          return;
        }
      }
    } catch (IllegalStateException e) {
      Log.e(TAG, "Connection went away while we were trying to authenticate", e);
    } catch (Exception e) {
      Log.e(TAG, "Problem during handleAuthentication()", e);
    }

    // TODO: Need verification

    try {
      if (connection.isAuthMethodAvailable(profile.getUser(), AUTH_KEYBOARDINTERACTIVE)) {
        if (connection.authenticateWithKeyboardInteractive(profile.getUser(), this)) return;
      }
    } catch (Exception e) {
      Log.d(TAG, "Host does not support 'Keyboard-Interactive' authentication.");
    }
  }
Пример #3
0
  public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);

    try {

      // Get real variable value
      String realServerName = environmentSubstitute(serverName);
      int realServerPort = Const.toInt(environmentSubstitute(serverPort), 22);
      String realUserName = environmentSubstitute(userName);
      String realServerPassword =
          Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password));
      // Proxy Host
      String realProxyHost = environmentSubstitute(httpproxyhost);
      int realProxyPort = Const.toInt(environmentSubstitute(httpproxyport), 22);
      String realproxyUserName = environmentSubstitute(httpproxyusername);
      String realProxyPassword =
          Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(httpProxyPassword));
      // Key file
      String realKeyFilename = environmentSubstitute(keyFilename);
      String relKeyFilepass = environmentSubstitute(keyFilePass);
      // Source files
      String realLocalDirectory = environmentSubstitute(localDirectory);
      String realwildcard = environmentSubstitute(wildcard);
      // Remote destination
      String realftpDirectory = environmentSubstitute(ftpDirectory);
      // Destination folder (Move to)
      String realDestinationFolder = environmentSubstitute(destinationfolder);

      try {
        // Remote source
        realftpDirectory = FTPUtils.normalizePath(realftpDirectory);
        // Destination folder (Move to)
        realDestinationFolder = FTPUtils.normalizePath(realDestinationFolder);
      } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.CanNotNormalizePath", e.getMessage()));
        result.setNrErrors(1);
        return result;
      }

      // Check for mandatory fields
      boolean mandatoryok = true;
      if (Const.isEmpty(realServerName)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.ServernameMissing"));
      }
      if (usehttpproxy) {
        if (Const.isEmpty(realProxyHost)) {
          mandatoryok = false;
          logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.HttpProxyhostMissing"));
        }
      }
      if (publicpublickey) {
        if (Const.isEmpty(realKeyFilename)) {
          mandatoryok = false;
          logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.KeyFileMissing"));
        } else {
          // Let's check if folder exists...
          if (!KettleVFS.fileExists(realKeyFilename, this)) {
            mandatoryok = false;
            logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.KeyFileNotExist"));
          }
        }
      }

      if (Const.isEmpty(realLocalDirectory)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.LocalFolderMissing"));
      }
      if (afterFtpPut.equals("move_file")) {
        if (Const.isEmpty(realDestinationFolder)) {
          mandatoryok = false;
          logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DestinatFolderMissing"));
        } else {
          FileObject folder = null;
          try {
            folder = KettleVFS.getFileObject(realDestinationFolder, this);
            // Let's check if folder exists...
            if (!folder.exists()) {
              // Do we need to create it?
              if (createDestinationFolder) {
                folder.createFolder();
              } else {
                logError(
                    BaseMessages.getString(
                        PKG, "JobSSH2PUT.Log.DestinatFolderNotExist", realDestinationFolder));
              }
            }
          } catch (Exception e) {
            throw new KettleException(e);
          } finally {
            if (folder != null) {
              try {
                folder.close();
                folder = null;
              } catch (Exception e) {
                /* Ignore */
              }
            }
          }
        }
      }

      if (mandatoryok) {
        Connection conn = null;
        SFTPv3Client client = null;
        boolean good = true;

        int nbfilestoput = 0;
        int nbput = 0;
        int nbrerror = 0;

        try {
          // Create a connection instance
          conn =
              getConnection(
                  realServerName,
                  realServerPort,
                  realProxyHost,
                  realProxyPort,
                  realproxyUserName,
                  realProxyPassword);

          if (timeout > 0) {
            // Use timeout
            // Cache Host Key
            if (cachehostkey) {
              conn.connect(new SimpleVerifier(database), 0, timeout * 1000);
            } else {
              conn.connect(null, 0, timeout * 1000);
            }

          } else {
            // Cache Host Key
            if (cachehostkey) {
              conn.connect(new SimpleVerifier(database));
            } else {
              conn.connect();
            }
          }

          // Authenticate

          boolean isAuthenticated = false;
          if (publicpublickey) {
            String keyContent =
                KettleVFS.getTextFileContent(realKeyFilename, this, Const.XML_ENCODING);
            isAuthenticated =
                conn.authenticateWithPublicKey(
                    realUserName, keyContent.toCharArray(), relKeyFilepass);
          } else {
            isAuthenticated = conn.authenticateWithPassword(realUserName, realServerPassword);
          }

          // LET'S CHECK AUTHENTICATION ...
          if (isAuthenticated == false) {
            logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.AuthenticationFailed"));
          } else {
            if (log.isBasic()) {
              logBasic(
                  BaseMessages.getString(PKG, "JobSSH2PUT.Log.Connected", serverName, userName));
            }

            client = new SFTPv3Client(conn);

            if (log.isDetailed()) {
              logDetailed(
                  BaseMessages.getString(
                      PKG, "JobSSH2PUT.Log.ProtocolVersion", "" + client.getProtocolVersion()));
            }

            // Check if remote directory exists
            if (!Const.isEmpty(realftpDirectory)) {
              if (!sshDirectoryExists(client, realftpDirectory)) {
                good = false;
                if (createRemoteFolder) {
                  good = CreateRemoteFolder(client, realftpDirectory);
                  if (good) {
                    logBasic(BaseMessages.getString(PKG, "JobSSH2PUT.Log.RemoteDirectoryCreated"));
                  }

                } else {
                  logError(
                      BaseMessages.getString(
                          PKG, "JobSSH2PUT.Log.RemoteDirectoryNotExist", realftpDirectory));
                }
              } else if (log.isDetailed()) {
                logDetailed(
                    BaseMessages.getString(
                        PKG, "JobSSH2PUT.Log.RemoteDirectoryExist", realftpDirectory));
              }
            }

            if (good) {
              // Get files list from local folder (source)
              List<FileObject> myFileList = getFiles(realLocalDirectory);

              // Prepare Pattern for wildcard
              Pattern pattern = null;
              if (!Const.isEmpty(realwildcard)) {
                pattern = Pattern.compile(realwildcard);
              }

              // Let's put files now ...
              // Get the files in the list
              for (int i = 0; i < myFileList.size() && !parentJob.isStopped(); i++) {
                FileObject myFile = myFileList.get(i);
                String localFilename = myFile.toString();
                String remoteFilename = myFile.getName().getBaseName();

                boolean getIt = true;

                // First see if the file matches the regular expression!
                if (pattern != null) {
                  Matcher matcher = pattern.matcher(remoteFilename);
                  getIt = matcher.matches();
                }

                // do we have a target directory?
                if (!Const.isEmpty(realftpDirectory)) {
                  remoteFilename = realftpDirectory + FTPUtils.FILE_SEPARATOR + remoteFilename;
                }

                if (onlyGettingNewFiles) {
                  // We get only new files
                  // ie not exist on the remote server
                  getIt = !sshFileExists(client, remoteFilename);
                }

                if (getIt) {
                  nbfilestoput++;

                  boolean putok = putFile(myFile, remoteFilename, client);
                  if (!putok) {
                    nbrerror++;
                    logError(
                        BaseMessages.getString(
                            PKG, "JobSSH2PUT.Log.Error.CanNotPutFile", localFilename));
                  } else {
                    nbput++;
                  }

                  if (putok && !afterFtpPut.equals("do_nothing")) {
                    deleteOrMoveFiles(myFile, realDestinationFolder);
                  }
                }
              }
              /** ****************************** RESULT ******************* */
              if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.JobEntryEnd1"));
                logDetailed(
                    BaseMessages.getString(
                        PKG, "JobSSH2PUT.Log.Result.TotalFiles", "" + nbfilestoput));
                logDetailed(
                    BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.TotalFilesPut", "" + nbput));
                logDetailed(
                    BaseMessages.getString(
                        PKG, "JobSSH2PUT.Log.Result.TotalFilesError", "" + nbrerror));
                logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.JobEntryEnd2"));
              }
              if (nbrerror == 0) {
                result.setResult(true);
                /** ****************************** RESULT ******************* */
              }
            }
          }

        } catch (Exception e) {
          result.setNrErrors(nbrerror);
          logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Error.ErrorFTP", e.getMessage()));
        } finally {
          if (conn != null) {
            conn.close();
          }
          if (client != null) {
            client.close();
          }
        }
      }
    } catch (Exception e) {
      result.setResult(false);
      result.setNrErrors(1L);
      logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Error.UnexpectedError"), e);
    }

    return result;
  }
  /**
   * Connects to the given {@link Computer} via SSH and installs Java/Jenkins agent if necessary.
   */
  @Override
  public void launch(SlaveComputer _computer, TaskListener listener) {

    Computer computer = (Computer) _computer;
    PrintStream logger = listener.getLogger();

    Date startDate = new Date();
    logger.println("Start time: " + getUtcDate(startDate));

    final Connection conn;
    Connection cleanupConn = null;
    boolean successful = false;

    try {
      conn = connectToSsh(computer, logger);
      cleanupConn = conn;
      logger.println("Authenticating as " + computer.getRemoteAdmin());
      if (!conn.authenticateWithPublicKey(
          computer.getRemoteAdmin(), computer.getNode().getPrivateKey().toCharArray(), "")) {
        logger.println("Authentication failed");
        throw new Exception("Authentication failed");
      }

      final SCPClient scp = conn.createSCPClient();

      if (!runInitScript(computer, logger, conn, scp)) {
        return;
      }

      if (!installJava(logger, conn)) {
        return;
      }

      logger.println("Copying slave.jar");
      scp.put(Jenkins.getInstance().getJnlpJars("slave.jar").readFully(), "slave.jar", "/tmp");
      String jvmOpts = Util.fixNull(computer.getNode().getJvmOpts());
      String launchString = "java " + jvmOpts + " -jar /tmp/slave.jar";
      logger.println("Launching slave agent: " + launchString);
      final Session sess = conn.openSession();
      sess.execCommand(launchString);
      computer.setChannel(
          sess.getStdout(),
          sess.getStdin(),
          logger,
          new Channel.Listener() {
            @Override
            public void onClosed(Channel channel, IOException cause) {
              sess.close();
              conn.close();
            }
          });

      successful = true;
    } catch (Exception e) {
      LOGGER.log(Level.WARNING, e.getMessage(), e);
      try {
        Jenkins.getInstance().removeNode(computer.getNode());
      } catch (Exception ee) {
        ee.printStackTrace(logger);
      }
      e.printStackTrace(logger);
    } finally {
      Date endDate = new Date();
      logger.println("Done setting up at: " + getUtcDate(endDate));
      logger.println(
          "Done in "
              + TimeUnit2.MILLISECONDS.toSeconds(endDate.getTime() - startDate.getTime())
              + " seconds");
      if (cleanupConn != null && !successful) {
        cleanupConn.close();
      }
    }
  }
Пример #5
0
  public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);

    if (log.isRowLevel()) {
      logRowlevel(BaseMessages.getString(PKG, "JobSSH2GET.Log.GettingFieldsValue"));
    }

    // Get real variable value
    String realServerName = environmentSubstitute(serverName);
    int realServerPort = Const.toInt(environmentSubstitute(serverPort), 22);
    String realUserName = environmentSubstitute(userName);
    String realServerPassword =
        Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password));
    // Proxy Host
    String realProxyHost = environmentSubstitute(httpProxyHost);
    int realProxyPort = Const.toInt(environmentSubstitute(httpproxyport), 22);
    String realproxyUserName = environmentSubstitute(httpproxyusername);
    String realProxyPassword =
        Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(httpProxyPassword));
    // Key file
    String realKeyFilename = environmentSubstitute(keyFilename);
    String relKeyFilepass = environmentSubstitute(keyFilePass);
    // target files
    String realLocalDirectory = environmentSubstitute(localDirectory);
    String realwildcard = environmentSubstitute(wildcard);
    // Remote source
    String realftpDirectory = environmentSubstitute(ftpDirectory);
    // Destination folder (Move to)
    String realDestinationFolder = environmentSubstitute(destinationfolder);

    try {
      // Remote source
      realftpDirectory = FTPUtils.normalizePath(realftpDirectory);
      // Destination folder (Move to)
      realDestinationFolder = FTPUtils.normalizePath(realDestinationFolder);
    } catch (Exception e) {
      logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.CanNotNormalizePath", e.getMessage()));
      result.setNrErrors(1);
      return result;
    }

    // Check for mandatory fields
    if (log.isRowLevel()) {
      logRowlevel(BaseMessages.getString(PKG, "JobSSH2GET.Log.CheckingMandatoryFields"));
    }

    boolean mandatoryok = true;
    if (Const.isEmpty(realServerName)) {
      mandatoryok = false;
      logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.ServernameMissing"));
    }
    if (usehttpproxy) {
      if (Const.isEmpty(realProxyHost)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.HttpProxyhostMissing"));
      }
    }
    if (publicpublickey) {
      if (Const.isEmpty(realKeyFilename)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.KeyFileMissing"));
      } else {
        // Let's check if key file exists...
        if (!new File(realKeyFilename).exists()) {
          mandatoryok = false;
          logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.KeyFileNotExist"));
        }
      }
    }

    if (Const.isEmpty(realLocalDirectory)) {
      mandatoryok = false;
      logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.LocalFolderMissing"));
    } else {
      // Check if target folder exists...
      if (!new File(realLocalDirectory).exists()) {

        if (createtargetfolder) {
          // Create Target folder
          if (!CreateFolder(realLocalDirectory)) {
            mandatoryok = false;
          }

        } else {
          mandatoryok = false;
          logError(
              BaseMessages.getString(
                  PKG, "JobSSH2GET.Log.LocalFolderNotExists", realLocalDirectory));
        }
      } else {
        if (!new File(realLocalDirectory).isDirectory()) {
          mandatoryok = false;
          logError(
              BaseMessages.getString(
                  PKG, "JobSSH2GET.Log.LocalFolderNotFolder", realLocalDirectory));
        }
      }
    }
    if (afterFtpPut.equals("move_file")) {
      if (Const.isEmpty(realDestinationFolder)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.DestinatFolderMissing"));
      }
    }

    if (mandatoryok) {

      Connection conn = null;
      SFTPv3Client client = null;
      boolean good = true;

      try {
        // Create a connection instance
        conn =
            getConnection(
                realServerName,
                realServerPort,
                realProxyHost,
                realProxyPort,
                realproxyUserName,
                realProxyPassword);
        if (log.isDetailed()) {
          logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.ConnectionInstanceCreated"));
        }
        if (timeout > 0) {
          // Use timeout
          // Cache Host Key
          if (cachehostkey) {
            conn.connect(new SimpleVerifier(database), 0, timeout * 1000);
          } else {
            conn.connect(null, 0, timeout * 1000);
          }

        } else {
          // Cache Host Key
          if (cachehostkey) {
            conn.connect(new SimpleVerifier(database));
          } else {
            conn.connect();
          }
        }

        // Authenticate

        boolean isAuthenticated = false;
        if (publicpublickey) {
          isAuthenticated =
              conn.authenticateWithPublicKey(
                  realUserName, new File(realKeyFilename), relKeyFilepass);
        } else {
          isAuthenticated = conn.authenticateWithPassword(realUserName, realServerPassword);
        }

        // LET'S CHECK AUTHENTICATION ...
        if (isAuthenticated == false) {
          logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.AuthenticationFailed"));
        } else {
          if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "JobSSH2GET.Log.Connected", serverName, userName));
          }

          client = new SFTPv3Client(conn);

          if (log.isDetailed()) {
            logDetailed(
                BaseMessages.getString(
                    PKG, "JobSSH2GET.Log.ProtocolVersion", "" + client.getProtocolVersion()));
          }

          // Check if ftp (source) directory exists
          if (!Const.isEmpty(realftpDirectory)) {
            if (!sshDirectoryExists(client, realftpDirectory)) {
              good = false;
              logError(
                  BaseMessages.getString(
                      PKG, "JobSSH2GET.Log.RemoteDirectoryNotExist", realftpDirectory));
            } else if (log.isDetailed()) {
              logDetailed(
                  BaseMessages.getString(
                      PKG, "JobSSH2GET.Log.RemoteDirectoryExist", realftpDirectory));
            }
          }

          if (realDestinationFolder != null) {
            // Check now destination folder
            if (!sshDirectoryExists(client, realDestinationFolder)) {
              if (createdestinationfolder) {
                if (!CreateRemoteFolder(client, realDestinationFolder)) {
                  good = false;
                }
              } else {
                good = false;
                logError(
                    BaseMessages.getString(
                        PKG, "JobSSH2GET.Log.DestinatFolderNotExist", realDestinationFolder));
              }
            }
          }

          if (good) {
            Pattern pattern = null;
            if (!Const.isEmpty(realwildcard)) {
              pattern = Pattern.compile(realwildcard);
            }

            if (includeSubFolders) {
              if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.RecursiveModeOn"));
              }
              copyRecursive(realftpDirectory, realLocalDirectory, client, pattern, parentJob);
            } else {
              if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.RecursiveModeOff"));
              }
              GetFiles(realftpDirectory, realLocalDirectory, client, pattern, parentJob);
            }

            /** ****************************** RESULT ******************* */
            if (log.isDetailed()) {
              logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.JobEntryEnd1"));
              logDetailed(
                  BaseMessages.getString(
                      PKG, "JobSSH2GET.Log.Result.TotalFiles", "" + nbfilestoget));
              logDetailed(
                  BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.TotalFilesPut", "" + nbgot));
              logDetailed(
                  BaseMessages.getString(
                      PKG, "JobSSH2GET.Log.Result.TotalFilesError", "" + nbrerror));
              logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.JobEntryEnd2"));
            }
            if (nbrerror == 0) {
              result.setResult(true);
              /** ****************************** RESULT ******************* */
            }
          }
        }

      } catch (Exception e) {
        result.setNrErrors(nbrerror);
        logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.Error.ErrorFTP", e.getMessage()));
      } finally {
        if (conn != null) {
          conn.close();
        }
        if (client != null) {
          client.close();
        }
      }
    }

    return result;
  }