View Javadoc
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  
12  import static org.apache.sshd.core.CoreModuleProperties.PASSWORD_PROMPTS;
13  
14  import org.apache.sshd.client.auth.keyboard.UserInteraction;
15  import org.apache.sshd.client.auth.password.UserAuthPassword;
16  import org.apache.sshd.client.session.ClientSession;
17  
18  /**
19   * A password authentication handler that uses the {@link JGitUserInteraction}
20   * to ask the user for the password. It also respects the
21   * {@code NumberOfPasswordPrompts} ssh config.
22   */
23  public class JGitPasswordAuthentication extends UserAuthPassword {
24  
25  	private int maxAttempts;
26  
27  	private int attempts;
28  
29  	@Override
30  	public void init(ClientSession session, String service) throws Exception {
31  		super.init(session, service);
32  		maxAttempts = Math.max(1,
33  				PASSWORD_PROMPTS.getRequired(session).intValue());
34  		attempts = 0;
35  	}
36  
37  	@Override
38  	protected boolean sendAuthDataRequest(ClientSession session, String service)
39  			throws Exception {
40  		if (++attempts > maxAttempts) {
41  			return false;
42  		}
43  		UserInteraction interaction = session.getUserInteraction();
44  		if (!interaction.isInteractionAllowed(session)) {
45  			return false;
46  		}
47  		String password = getPassword(session, interaction);
48  		if (password == null) {
49  			throw new AuthenticationCanceledException();
50  		}
51  		// sendPassword takes a buffer as first argument, but actually doesn't
52  		// use it and creates its own buffer...
53  		sendPassword(null, session, password, password);
54  		return true;
55  	}
56  
57  	private String getPassword(ClientSession session,
58  			UserInteraction interaction) {
59  		String[] results = interaction.interactive(session, null, null, "", //$NON-NLS-1$
60  				new String[] { SshdText.get().passwordPrompt },
61  				new boolean[] { false });
62  		return (results == null || results.length == 0) ? null : results[0];
63  	}
64  }