View Javadoc
1   /*
2    * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.internal.transport.sshd;
44  
45  import java.net.InetSocketAddress;
46  import java.util.ArrayList;
47  import java.util.List;
48  import java.util.Map;
49  import java.util.concurrent.ConcurrentHashMap;
50  
51  import org.apache.sshd.client.auth.keyboard.UserInteraction;
52  import org.apache.sshd.client.session.ClientSession;
53  import org.apache.sshd.common.session.Session;
54  import org.apache.sshd.common.session.SessionListener;
55  import org.eclipse.jgit.transport.CredentialItem;
56  import org.eclipse.jgit.transport.CredentialsProvider;
57  import org.eclipse.jgit.transport.SshConstants;
58  import org.eclipse.jgit.transport.URIish;
59  
60  /**
61   * A {@link UserInteraction} callback implementation based on a
62   * {@link CredentialsProvider}.
63   */
64  public class JGitUserInteraction implements UserInteraction {
65  
66  	private final CredentialsProvider provider;
67  
68  	/**
69  	 * We need to reset the JGit credentials provider if we have repeated
70  	 * attempts.
71  	 */
72  	private final Map<Session, SessionListener> ongoing = new ConcurrentHashMap<>();
73  
74  	/**
75  	 * Creates a new {@link JGitUserInteraction} for interactive password input
76  	 * based on the given {@link CredentialsProvider}.
77  	 *
78  	 * @param provider
79  	 *            to use
80  	 */
81  	public JGitUserInteraction(CredentialsProvider provider) {
82  		this.provider = provider;
83  	}
84  
85  	@Override
86  	public boolean isInteractionAllowed(ClientSession session) {
87  		return provider != null && provider.isInteractive();
88  	}
89  
90  	@Override
91  	public String[] interactive(ClientSession session, String name,
92  			String instruction, String lang, String[] prompt, boolean[] echo) {
93  		// This is keyboard-interactive or password authentication
94  		List<CredentialItem> items = new ArrayList<>();
95  		int numberOfHiddenInputs = 0;
96  		for (int i = 0; i < prompt.length; i++) {
97  			boolean hidden = i < echo.length && !echo[i];
98  			if (hidden) {
99  				numberOfHiddenInputs++;
100 			}
101 		}
102 		// RFC 4256 (SSH_MSG_USERAUTH_INFO_REQUEST) says: "The language tag is
103 		// deprecated and SHOULD be the empty string." and "[If there are no
104 		// prompts] the client SHOULD still display the name and instruction
105 		// fields" and "[The] client SHOULD print the name and instruction (if
106 		// non-empty)"
107 		if (name != null && !name.isEmpty()) {
108 			items.add(new CredentialItem.InformationalMessage(name));
109 		}
110 		if (instruction != null && !instruction.isEmpty()) {
111 			items.add(new CredentialItem.InformationalMessage(instruction));
112 		}
113 		for (int i = 0; i < prompt.length; i++) {
114 			boolean hidden = i < echo.length && !echo[i];
115 			if (hidden && numberOfHiddenInputs == 1) {
116 				// We need to somehow trigger storing the password in the
117 				// Eclipse secure storage in EGit. Currently, this is done only
118 				// for password fields.
119 				items.add(new CredentialItem.Password());
120 				// TODO Possibly change EGit to store all hidden strings
121 				// (keyed by the URI and the prompt?) so that we don't have to
122 				// use this kludge here.
123 			} else {
124 				items.add(new CredentialItem.StringType(prompt[i], hidden));
125 			}
126 		}
127 		if (items.isEmpty()) {
128 			// Huh? No info, no prompts?
129 			return prompt; // Is known to have length zero here
130 		}
131 		URIish uri = toURI(session.getUsername(),
132 				(InetSocketAddress) session.getConnectAddress());
133 		// Reset the provider for this URI if it's not the first attempt and we
134 		// have hidden inputs. Otherwise add a session listener that will remove
135 		// itself once authenticated.
136 		if (numberOfHiddenInputs > 0) {
137 			SessionListener listener = ongoing.get(session);
138 			if (listener != null) {
139 				provider.reset(uri);
140 			} else {
141 				listener = new SessionAuthMarker(ongoing);
142 				ongoing.put(session, listener);
143 				session.addSessionListener(listener);
144 			}
145 		}
146 		if (provider.get(uri, items)) {
147 			return items.stream().map(i -> {
148 				if (i instanceof CredentialItem.Password) {
149 					return new String(((CredentialItem.Password) i).getValue());
150 				} else if (i instanceof CredentialItem.StringType) {
151 					return ((CredentialItem.StringType) i).getValue();
152 				}
153 				return null;
154 			}).filter(s -> s != null).toArray(String[]::new);
155 		}
156 		// TODO What to throw to abort the connection/authentication process?
157 		// In UserAuthKeyboardInteractive.getUserResponses() it's clear that
158 		// returning null is valid and signifies "an error"; we'll try the
159 		// next authentication method. But if the user explicitly canceled,
160 		// then we don't want to try the next methods...
161 		//
162 		// Probably not a serious issue with the typical order of public-key,
163 		// keyboard-interactive, password.
164 		return null;
165 	}
166 
167 	@Override
168 	public String getUpdatedPassword(ClientSession session, String prompt,
169 			String lang) {
170 		// TODO Implement password update in password authentication?
171 		return null;
172 	}
173 
174 	/**
175 	 * Creates a {@link URIish} from the given remote address and user name.
176 	 *
177 	 * @param userName
178 	 *            for the uri
179 	 * @param remote
180 	 *            address of the remote host
181 	 * @return the uri, with {@link SshConstants#SSH_SCHEME} as scheme
182 	 */
183 	public static URIish toURI(String userName, InetSocketAddress remote) {
184 		String host = remote.getHostString();
185 		int port = remote.getPort();
186 		return new URIish() //
187 				.setScheme(SshConstants.SSH_SCHEME) //
188 				.setHost(host) //
189 				.setPort(port) //
190 				.setUser(userName);
191 	}
192 
193 	/**
194 	 * A {@link SessionListener} that removes itself from the session when
195 	 * authentication is done or the session is closed.
196 	 */
197 	private static class SessionAuthMarker implements SessionListener {
198 
199 		private final Map<Session, SessionListener> registered;
200 
201 		public SessionAuthMarker(Map<Session, SessionListener> registered) {
202 			this.registered = registered;
203 		}
204 
205 		@Override
206 		public void sessionEvent(Session session, SessionListener.Event event) {
207 			if (event == SessionListener.Event.Authenticated) {
208 				session.removeSessionListener(this);
209 				registered.remove(session, this);
210 			}
211 		}
212 
213 		@Override
214 		public void sessionClosed(Session session) {
215 			session.removeSessionListener(this);
216 			registered.remove(session, this);
217 		}
218 	}
219 }