JGitPasswordAuthentication.java

  1. /*
  2.  * Copyright (C) 2018, 2022 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.password.UserAuthPassword;
  13. import org.apache.sshd.client.session.ClientSession;

  14. /**
  15.  * A password authentication handler that respects the
  16.  * {@code NumberOfPasswordPrompts} ssh config.
  17.  */
  18. public class JGitPasswordAuthentication extends UserAuthPassword {

  19.     private int maxAttempts;

  20.     private int attempts;

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

  28.     @Override
  29.     protected String resolveAttemptedPassword(ClientSession session,
  30.             String service) throws Exception {
  31.         if (++attempts > maxAttempts) {
  32.             return null;
  33.         }
  34.         return super.resolveAttemptedPassword(session, service);
  35.     }
  36. }