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 static java.text.MessageFormat.format;
46  
47  import java.io.IOException;
48  import java.net.SocketAddress;
49  import java.security.PublicKey;
50  import java.util.ArrayList;
51  import java.util.Iterator;
52  import java.util.LinkedHashSet;
53  import java.util.List;
54  import java.util.Set;
55  
56  import org.apache.sshd.client.ClientFactoryManager;
57  import org.apache.sshd.client.config.hosts.HostConfigEntry;
58  import org.apache.sshd.client.keyverifier.KnownHostsServerKeyVerifier.HostEntryPair;
59  import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
60  import org.apache.sshd.client.session.ClientSessionImpl;
61  import org.apache.sshd.common.FactoryManager;
62  import org.apache.sshd.common.SshException;
63  import org.apache.sshd.common.config.keys.KeyUtils;
64  import org.apache.sshd.common.io.IoSession;
65  import org.apache.sshd.common.io.IoWriteFuture;
66  import org.apache.sshd.common.util.Readable;
67  import org.eclipse.jgit.errors.InvalidPatternException;
68  import org.eclipse.jgit.fnmatch.FileNameMatcher;
69  import org.eclipse.jgit.internal.transport.sshd.proxy.StatefulProxyConnector;
70  import org.eclipse.jgit.transport.CredentialsProvider;
71  import org.eclipse.jgit.transport.SshConstants;
72  
73  /**
74   * A {@link org.apache.sshd.client.session.ClientSession ClientSession} that can
75   * be associated with the {@link HostConfigEntry} the session was created for.
76   * The {@link JGitSshClient} creates such sessions and sets this association.
77   * <p>
78   * Also provides for associating a JGit {@link CredentialsProvider} with a
79   * session.
80   * </p>
81   */
82  public class JGitClientSession extends ClientSessionImpl {
83  
84  	private HostConfigEntry hostConfig;
85  
86  	private CredentialsProvider credentialsProvider;
87  
88  	private StatefulProxyConnector proxyHandler;
89  
90  	/**
91  	 * @param manager
92  	 * @param session
93  	 * @throws Exception
94  	 */
95  	public JGitClientSession(ClientFactoryManager manager, IoSession session)
96  			throws Exception {
97  		super(manager, session);
98  	}
99  
100 	/**
101 	 * Retrieves the {@link HostConfigEntry} this session was created for.
102 	 *
103 	 * @return the {@link HostConfigEntry}, or {@code null} if none set
104 	 */
105 	public HostConfigEntry getHostConfigEntry() {
106 		return hostConfig;
107 	}
108 
109 	/**
110 	 * Sets the {@link HostConfigEntry} this session was created for.
111 	 *
112 	 * @param hostConfig
113 	 *            the {@link HostConfigEntry}
114 	 */
115 	public void setHostConfigEntry(HostConfigEntry hostConfig) {
116 		this.hostConfig = hostConfig;
117 	}
118 
119 	/**
120 	 * Sets the {@link CredentialsProvider} for this session.
121 	 *
122 	 * @param provider
123 	 *            to set
124 	 */
125 	public void setCredentialsProvider(CredentialsProvider provider) {
126 		credentialsProvider = provider;
127 	}
128 
129 	/**
130 	 * Retrieves the {@link CredentialsProvider} set for this session.
131 	 *
132 	 * @return the provider, or {@code null} if none is set.
133 	 */
134 	public CredentialsProvider getCredentialsProvider() {
135 		return credentialsProvider;
136 	}
137 
138 	/**
139 	 * Sets a {@link StatefulProxyConnector} to handle proxy connection
140 	 * protocols.
141 	 *
142 	 * @param handler
143 	 *            to set
144 	 */
145 	public void setProxyHandler(StatefulProxyConnector handler) {
146 		proxyHandler = handler;
147 	}
148 
149 	@Override
150 	protected IoWriteFuture sendIdentification(String ident)
151 			throws IOException {
152 		StatefulProxyConnector proxy = proxyHandler;
153 		if (proxy != null) {
154 			try {
155 				// We must not block here; the framework starts reading messages
156 				// from the peer only once the initial sendKexInit() following
157 				// this call to sendIdentification() has returned!
158 				proxy.runWhenDone(() -> {
159 					JGitClientSession.super.sendIdentification(ident);
160 					return null;
161 				});
162 				// Called only from the ClientSessionImpl constructor, where the
163 				// return value is ignored.
164 				return null;
165 			} catch (IOException e) {
166 				throw e;
167 			} catch (Exception other) {
168 				throw new IOException(other.getLocalizedMessage(), other);
169 			}
170 		} else {
171 			return super.sendIdentification(ident);
172 		}
173 	}
174 
175 	@Override
176 	protected byte[] sendKexInit() throws IOException {
177 		StatefulProxyConnector proxy = proxyHandler;
178 		if (proxy != null) {
179 			try {
180 				// We must not block here; the framework starts reading messages
181 				// from the peer only once the initial sendKexInit() has
182 				// returned!
183 				proxy.runWhenDone(() -> {
184 					JGitClientSession.super.sendKexInit();
185 					return null;
186 				});
187 				// This is called only from the ClientSessionImpl
188 				// constructor, where the return value is ignored.
189 				return null;
190 			} catch (IOException e) {
191 				throw e;
192 			} catch (Exception other) {
193 				throw new IOException(other.getLocalizedMessage(), other);
194 			}
195 		} else {
196 			return super.sendKexInit();
197 		}
198 	}
199 
200 	/**
201 	 * {@inheritDoc}
202 	 *
203 	 * As long as we're still setting up the proxy connection, diverts messages
204 	 * to the {@link StatefulProxyConnector}.
205 	 */
206 	@Override
207 	public void messageReceived(Readable buffer) throws Exception {
208 		StatefulProxyConnector proxy = proxyHandler;
209 		if (proxy != null) {
210 			proxy.messageReceived(getIoSession(), buffer);
211 		} else {
212 			super.messageReceived(buffer);
213 		}
214 	}
215 
216 	@Override
217 	protected void checkKeys() throws SshException {
218 		ServerKeyVerifier serverKeyVerifier = getServerKeyVerifier();
219 		// The super implementation always uses
220 		// getIoSession().getRemoteAddress(). In case of a proxy connection,
221 		// that would be the address of the proxy!
222 		SocketAddress remoteAddress = getConnectAddress();
223 		PublicKey serverKey = getKex().getServerKey();
224 		if (!serverKeyVerifier.verifyServerKey(this, remoteAddress,
225 				serverKey)) {
226 			throw new SshException(
227 					org.apache.sshd.common.SshConstants.SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE,
228 					SshdText.get().kexServerKeyInvalid);
229 		}
230 	}
231 
232 	@Override
233 	protected String resolveAvailableSignaturesProposal(
234 			FactoryManager manager) {
235 		Set<String> defaultSignatures = new LinkedHashSet<>();
236 		defaultSignatures.addAll(getSignatureFactoriesNames());
237 		HostConfigEntry config = resolveAttribute(
238 				JGitSshClient.HOST_CONFIG_ENTRY);
239 		String hostKeyAlgorithms = config
240 				.getProperty(SshConstants.HOST_KEY_ALGORITHMS);
241 		if (hostKeyAlgorithms != null && !hostKeyAlgorithms.isEmpty()) {
242 			char first = hostKeyAlgorithms.charAt(0);
243 			if (first == '+') {
244 				// Additions make not much sense -- it's either in
245 				// defaultSignatures already, or we have no implementation for
246 				// it. No point in proposing it.
247 				return String.join(",", defaultSignatures); //$NON-NLS-1$
248 			} else if (first == '-') {
249 				// This takes wildcard patterns!
250 				removeFromList(defaultSignatures,
251 						SshConstants.HOST_KEY_ALGORITHMS,
252 						hostKeyAlgorithms.substring(1));
253 				if (defaultSignatures.isEmpty()) {
254 					// Too bad: user config error. Warn here, and then fail
255 					// later.
256 					log.warn(format(
257 							SshdText.get().configNoRemainingHostKeyAlgorithms,
258 							hostKeyAlgorithms));
259 				}
260 				return String.join(",", defaultSignatures); //$NON-NLS-1$
261 			} else {
262 				// Default is overridden -- only accept the ones for which we do
263 				// have an implementation.
264 				List<String> newNames = filteredList(defaultSignatures,
265 						hostKeyAlgorithms);
266 				if (newNames.isEmpty()) {
267 					log.warn(format(
268 							SshdText.get().configNoKnownHostKeyAlgorithms,
269 							hostKeyAlgorithms));
270 					// Use the default instead.
271 				} else {
272 					return String.join(",", newNames); //$NON-NLS-1$
273 				}
274 			}
275 		}
276 		// No HostKeyAlgorithms; using default -- change order to put existing
277 		// keys first.
278 		ServerKeyVerifier verifier = getServerKeyVerifier();
279 		if (verifier instanceof ServerKeyLookup) {
280 			SocketAddress remoteAddress = resolvePeerAddress(
281 					resolveAttribute(JGitSshClient.ORIGINAL_REMOTE_ADDRESS));
282 			List<HostEntryPair> allKnownKeys = ((ServerKeyLookup) verifier)
283 					.lookup(this, remoteAddress);
284 			Set<String> reordered = new LinkedHashSet<>();
285 			for (HostEntryPair h : allKnownKeys) {
286 				PublicKey key = h.getServerKey();
287 				if (key != null) {
288 					String keyType = KeyUtils.getKeyType(key);
289 					if (keyType != null) {
290 						reordered.add(keyType);
291 					}
292 				}
293 			}
294 			reordered.addAll(defaultSignatures);
295 			return String.join(",", reordered); //$NON-NLS-1$
296 		}
297 		return String.join(",", defaultSignatures); //$NON-NLS-1$
298 	}
299 
300 	private void removeFromList(Set<String> current, String key,
301 			String patterns) {
302 		for (String toRemove : patterns.split("\\s*,\\s*")) { //$NON-NLS-1$
303 			if (toRemove.indexOf('*') < 0 && toRemove.indexOf('?') < 0) {
304 				current.remove(toRemove);
305 				continue;
306 			}
307 			try {
308 				FileNameMatcher matcher = new FileNameMatcher(toRemove, null);
309 				for (Iterator<String> i = current.iterator(); i.hasNext();) {
310 					matcher.reset();
311 					matcher.append(i.next());
312 					if (matcher.isMatch()) {
313 						i.remove();
314 					}
315 				}
316 			} catch (InvalidPatternException e) {
317 				log.warn(format(SshdText.get().configInvalidPattern, key,
318 						toRemove));
319 			}
320 		}
321 	}
322 
323 	private List<String> filteredList(Set<String> known, String values) {
324 		List<String> newNames = new ArrayList<>();
325 		for (String newValue : values.split("\\s*,\\s*")) { //$NON-NLS-1$
326 			if (known.contains(newValue)) {
327 				newNames.add(newValue);
328 			}
329 		}
330 		return newNames;
331 	}
332 
333 }