You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JGitPasswordAuthentication.java 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.internal.transport.sshd;
  11. import java.util.concurrent.CancellationException;
  12. import org.apache.sshd.client.ClientAuthenticationManager;
  13. import org.apache.sshd.client.auth.keyboard.UserInteraction;
  14. import org.apache.sshd.client.auth.password.UserAuthPassword;
  15. import org.apache.sshd.client.session.ClientSession;
  16. /**
  17. * A password authentication handler that uses the {@link JGitUserInteraction}
  18. * to ask the user for the password. It also respects the
  19. * {@code NumberOfPasswordPrompts} ssh config.
  20. */
  21. public class JGitPasswordAuthentication extends UserAuthPassword {
  22. private int maxAttempts;
  23. private int attempts;
  24. @Override
  25. public void init(ClientSession session, String service) throws Exception {
  26. super.init(session, service);
  27. maxAttempts = Math.max(1,
  28. session.getIntProperty(
  29. ClientAuthenticationManager.PASSWORD_PROMPTS,
  30. ClientAuthenticationManager.DEFAULT_PASSWORD_PROMPTS));
  31. attempts = 0;
  32. }
  33. @Override
  34. protected boolean sendAuthDataRequest(ClientSession session, String service)
  35. throws Exception {
  36. if (++attempts > maxAttempts) {
  37. return false;
  38. }
  39. UserInteraction interaction = session.getUserInteraction();
  40. if (!interaction.isInteractionAllowed(session)) {
  41. return false;
  42. }
  43. String password = getPassword(session, interaction);
  44. if (password == null) {
  45. throw new CancellationException();
  46. }
  47. // sendPassword takes a buffer as first argument, but actually doesn't
  48. // use it and creates its own buffer...
  49. sendPassword(null, session, password, password);
  50. return true;
  51. }
  52. private String getPassword(ClientSession session,
  53. UserInteraction interaction) {
  54. String[] results = interaction.interactive(session, null, null, "", //$NON-NLS-1$
  55. new String[] { SshdText.get().passwordPrompt },
  56. new boolean[] { false });
  57. return (results == null || results.length == 0) ? null : results[0];
  58. }
  59. }