private File getPrivateKey()

in git-common/src/main/java/jetbrains/buildServer/buildTriggers/vcs/git/command/GitCommandLine.java [316:378]


  private File getPrivateKey(@NotNull AuthSettings authSettings) throws VcsException {
    File privateKey = null;
    final boolean useSshAskPass = myCtx.isUseSshAskPass();
    try {
      switch (authSettings.getAuthMethod()) {
        case TEAMCITY_SSH_KEY:
          privateKey = getUploadedPrivateKey(authSettings);
          break;
        case PRIVATE_KEY_FILE:
          final String keyPath = authSettings.getPrivateKeyFilePath();
          if (StringUtil.isEmpty(keyPath)) {
            throw new VcsException("Authentication method is \"" + AuthenticationMethod.PRIVATE_KEY_FILE.uiName() + "\", but no private key path provided");
          }

          final File finalPrivateKey = createTmpKeyFile();
          addPostAction(() -> FileUtil.delete(finalPrivateKey));
          privateKey = finalPrivateKey;

          writeSshPrivateKeyToFile(Files.readAllBytes(Paths.get(keyPath)), privateKey);
          break;
        case PRIVATE_KEY_DEFAULT:
          // we do not decrypt default ssh keys
          return null;
        default:
          return null;
      }

      final String passphrase = authSettings.getPassphrase();
      if (useSshAskPass) {
        withAskPassScript(passphrase, askPassPath -> {
          addEnvParam("SSH_ASKPASS", askPassPath);
          addEnvParam("SSH_ASKPASS_REQUIRE", "force");
          addEnvParam("DISPLAY", ":0.0");
        });
      } else {
        final KeyPair keyPair = KeyPair.load(new JSch(), privateKey.getAbsolutePath());
        OutputStream out = null;
        try {
          out = new BufferedOutputStream(new FileOutputStream(privateKey));
          if (keyPair.isEncrypted() && !keyPair.decrypt(passphrase)) {
            throw new VcsException("Wrong SSH key passphrase");
          }
          keyPair.writePrivateKey(out, null);
        } finally {
          FileUtil.close(out);
        }
      }

      //set permissions to 600, without that ssh client rejects the key on *nix
      privateKey.setReadable(false, false);
      privateKey.setReadable(true, true);
      privateKey.setWritable(false, false);
      privateKey.setWritable(true, true);

      return privateKey;
    } catch (Exception e) {
      if (privateKey != null)
        FileUtil.delete(privateKey);
      if (e instanceof VcsException)
        throw (VcsException) e;
      throw new VcsException(e);
    }
  }