JGitPasswordAuthentication.java

  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 static org.apache.sshd.core.CoreModuleProperties.PASSWORD_PROMPTS;

  12. import org.apache.sshd.client.auth.keyboard.UserInteraction;
  13. import org.apache.sshd.client.auth.password.UserAuthPassword;
  14. import org.apache.sshd.client.session.ClientSession;

  15. /**
  16.  * A password authentication handler that uses the {@link JGitUserInteraction}
  17.  * to ask the user for the password. It also respects the
  18.  * {@code NumberOfPasswordPrompts} ssh config.
  19.  */
  20. public class JGitPasswordAuthentication extends UserAuthPassword {

  21.     private int maxAttempts;

  22.     private int attempts;

  23.     @Override
  24.     public void init(ClientSession session, String service) throws Exception {
  25.         super.init(session, service);
  26.         maxAttempts = Math.max(1,
  27.                 PASSWORD_PROMPTS.getRequired(session).intValue());
  28.         attempts = 0;
  29.     }

  30.     @Override
  31.     protected boolean sendAuthDataRequest(ClientSession session, String service)
  32.             throws Exception {
  33.         if (++attempts > maxAttempts) {
  34.             return false;
  35.         }
  36.         UserInteraction interaction = session.getUserInteraction();
  37.         if (!interaction.isInteractionAllowed(session)) {
  38.             return false;
  39.         }
  40.         String password = getPassword(session, interaction);
  41.         if (password == null) {
  42.             throw new AuthenticationCanceledException();
  43.         }
  44.         // sendPassword takes a buffer as first argument, but actually doesn't
  45.         // use it and creates its own buffer...
  46.         sendPassword(null, session, password, password);
  47.         return true;
  48.     }

  49.     private String getPassword(ClientSession session,
  50.             UserInteraction interaction) {
  51.         String[] results = interaction.interactive(session, null, null, "", //$NON-NLS-1$
  52.                 new String[] { SshdText.get().passwordPrompt },
  53.                 new boolean[] { false });
  54.         return (results == null || results.length == 0) ? null : results[0];
  55.     }
  56. }