You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JGitSshClient.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. import static java.text.MessageFormat.format;
  45. import java.io.IOException;
  46. import java.net.InetSocketAddress;
  47. import java.nio.file.Files;
  48. import java.nio.file.InvalidPathException;
  49. import java.nio.file.Path;
  50. import java.nio.file.Paths;
  51. import java.security.KeyPair;
  52. import java.util.Arrays;
  53. import java.util.Iterator;
  54. import java.util.List;
  55. import java.util.NoSuchElementException;
  56. import java.util.Objects;
  57. import java.util.stream.Collectors;
  58. import org.apache.sshd.client.SshClient;
  59. import org.apache.sshd.client.config.hosts.HostConfigEntry;
  60. import org.apache.sshd.client.future.ConnectFuture;
  61. import org.apache.sshd.client.future.DefaultConnectFuture;
  62. import org.apache.sshd.client.session.ClientSessionImpl;
  63. import org.apache.sshd.client.session.SessionFactory;
  64. import org.apache.sshd.common.future.SshFutureListener;
  65. import org.apache.sshd.common.io.IoConnectFuture;
  66. import org.apache.sshd.common.io.IoSession;
  67. import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
  68. import org.apache.sshd.common.keyprovider.KeyPairProvider;
  69. import org.apache.sshd.common.session.helpers.AbstractSession;
  70. import org.apache.sshd.common.util.ValidateUtils;
  71. import org.eclipse.jgit.transport.CredentialsProvider;
  72. import org.eclipse.jgit.transport.SshConstants;
  73. import org.eclipse.jgit.transport.sshd.KeyCache;
  74. /**
  75. * Customized {@link SshClient} for JGit. It creates specialized
  76. * {@link JGitClientSession}s that know about the {@link HostConfigEntry} they
  77. * were created for, and it loads all KeyPair identities lazily.
  78. */
  79. public class JGitSshClient extends SshClient {
  80. private KeyCache keyCache;
  81. private CredentialsProvider credentialsProvider;
  82. @Override
  83. protected SessionFactory createSessionFactory() {
  84. // Override the parent's default
  85. return new JGitSessionFactory(this);
  86. }
  87. @Override
  88. public ConnectFuture connect(HostConfigEntry hostConfig)
  89. throws IOException {
  90. if (connector == null) {
  91. throw new IllegalStateException("SshClient not started."); //$NON-NLS-1$
  92. }
  93. Objects.requireNonNull(hostConfig, "No host configuration"); //$NON-NLS-1$
  94. String host = ValidateUtils.checkNotNullAndNotEmpty(
  95. hostConfig.getHostName(), "No target host"); //$NON-NLS-1$
  96. int port = hostConfig.getPort();
  97. ValidateUtils.checkTrue(port > 0, "Invalid port: %d", port); //$NON-NLS-1$
  98. String userName = hostConfig.getUsername();
  99. InetSocketAddress address = new InetSocketAddress(host, port);
  100. ConnectFuture connectFuture = new DefaultConnectFuture(
  101. userName + '@' + address, null);
  102. SshFutureListener<IoConnectFuture> listener = createConnectCompletionListener(
  103. connectFuture, userName, address, hostConfig);
  104. connector.connect(address).addListener(listener);
  105. return connectFuture;
  106. }
  107. private SshFutureListener<IoConnectFuture> createConnectCompletionListener(
  108. ConnectFuture connectFuture, String username,
  109. InetSocketAddress address, HostConfigEntry hostConfig) {
  110. return new SshFutureListener<IoConnectFuture>() {
  111. @Override
  112. public void operationComplete(IoConnectFuture future) {
  113. if (future.isCanceled()) {
  114. connectFuture.cancel();
  115. return;
  116. }
  117. Throwable t = future.getException();
  118. if (t != null) {
  119. connectFuture.setException(t);
  120. return;
  121. }
  122. IoSession ioSession = future.getSession();
  123. try {
  124. JGitClientSession session = createSession(ioSession,
  125. username, address, hostConfig);
  126. connectFuture.setSession(session);
  127. } catch (RuntimeException e) {
  128. connectFuture.setException(e);
  129. ioSession.close(true);
  130. }
  131. }
  132. @Override
  133. public String toString() {
  134. return "JGitSshClient$ConnectCompletionListener[" + username //$NON-NLS-1$
  135. + '@' + address + ']';
  136. }
  137. };
  138. }
  139. private JGitClientSession createSession(IoSession ioSession,
  140. String username, InetSocketAddress address,
  141. HostConfigEntry hostConfig) {
  142. AbstractSession rawSession = AbstractSession.getSession(ioSession);
  143. if (!(rawSession instanceof JGitClientSession)) {
  144. throw new IllegalStateException("Wrong session type: " //$NON-NLS-1$
  145. + rawSession.getClass().getCanonicalName());
  146. }
  147. JGitClientSession session = (JGitClientSession) rawSession;
  148. session.setUsername(username);
  149. session.setConnectAddress(address);
  150. session.setHostConfigEntry(hostConfig);
  151. if (session.getCredentialsProvider() == null) {
  152. session.setCredentialsProvider(getCredentialsProvider());
  153. }
  154. FileKeyPairProvider ourConfiguredKeysProvider = null;
  155. List<Path> identities = hostConfig.getIdentities().stream()
  156. .map(s -> {
  157. try {
  158. return Paths.get(s);
  159. } catch (InvalidPathException e) {
  160. log.warn(format(SshdText.get().configInvalidPath,
  161. SshConstants.IDENTITY_FILE, s), e);
  162. return null;
  163. }
  164. }).filter(p -> p != null && Files.exists(p))
  165. .collect(Collectors.toList());
  166. ourConfiguredKeysProvider = new CachingKeyPairProvider(identities,
  167. keyCache);
  168. ourConfiguredKeysProvider.setPasswordFinder(getFilePasswordProvider());
  169. if (hostConfig.isIdentitiesOnly()) {
  170. session.setKeyPairProvider(ourConfiguredKeysProvider);
  171. } else {
  172. KeyPairProvider defaultKeysProvider = getKeyPairProvider();
  173. if (defaultKeysProvider instanceof FileKeyPairProvider) {
  174. ((FileKeyPairProvider) defaultKeysProvider)
  175. .setPasswordFinder(getFilePasswordProvider());
  176. }
  177. KeyPairProvider combinedProvider = new CombinedKeyPairProvider(
  178. ourConfiguredKeysProvider, defaultKeysProvider);
  179. session.setKeyPairProvider(combinedProvider);
  180. }
  181. return session;
  182. }
  183. /**
  184. * Set a cache for loaded keys. Newly discovered keys will be added when
  185. * IdentityFile host entries from the ssh config file are used during
  186. * session authentication.
  187. *
  188. * @param cache
  189. * to use
  190. */
  191. public void setKeyCache(KeyCache cache) {
  192. keyCache = cache;
  193. }
  194. /**
  195. * Sets the {@link CredentialsProvider} for this client.
  196. *
  197. * @param provider
  198. * to set
  199. */
  200. public void setCredentialsProvider(CredentialsProvider provider) {
  201. credentialsProvider = provider;
  202. }
  203. /**
  204. * Retrieves the {@link CredentialsProvider} set for this client.
  205. *
  206. * @return the provider, or {@code null} if none is set.
  207. */
  208. public CredentialsProvider getCredentialsProvider() {
  209. return credentialsProvider;
  210. }
  211. /**
  212. * A {@link SessionFactory} to create our own specialized
  213. * {@link JGitClientSession}s.
  214. */
  215. private static class JGitSessionFactory extends SessionFactory {
  216. public JGitSessionFactory(JGitSshClient client) {
  217. super(client);
  218. }
  219. @Override
  220. protected ClientSessionImpl doCreateSession(IoSession ioSession)
  221. throws Exception {
  222. return new JGitClientSession(getClient(), ioSession);
  223. }
  224. }
  225. /**
  226. * A {@link KeyPairProvider} that iterates over the {@link Iterable}s
  227. * returned by other {@link KeyPairProvider}s.
  228. */
  229. private static class CombinedKeyPairProvider implements KeyPairProvider {
  230. private final List<KeyPairProvider> providers;
  231. public CombinedKeyPairProvider(KeyPairProvider... providers) {
  232. this(Arrays.stream(providers).filter(Objects::nonNull)
  233. .collect(Collectors.toList()));
  234. }
  235. public CombinedKeyPairProvider(List<KeyPairProvider> providers) {
  236. this.providers = providers;
  237. }
  238. @Override
  239. public Iterable<String> getKeyTypes() {
  240. throw new UnsupportedOperationException(
  241. "Should not have been called in a ssh client"); //$NON-NLS-1$
  242. }
  243. @Override
  244. public KeyPair loadKey(String type) {
  245. throw new UnsupportedOperationException(
  246. "Should not have been called in a ssh client"); //$NON-NLS-1$
  247. }
  248. @Override
  249. public Iterable<KeyPair> loadKeys() {
  250. return () -> new Iterator<KeyPair>() {
  251. private Iterator<KeyPairProvider> factories = providers.iterator();
  252. private Iterator<KeyPair> current;
  253. private Boolean hasElement;
  254. @Override
  255. public boolean hasNext() {
  256. if (hasElement != null) {
  257. return hasElement.booleanValue();
  258. }
  259. while (current == null || !current.hasNext()) {
  260. if (factories.hasNext()) {
  261. current = factories.next().loadKeys().iterator();
  262. } else {
  263. current = null;
  264. hasElement = Boolean.FALSE;
  265. return false;
  266. }
  267. }
  268. hasElement = Boolean.TRUE;
  269. return true;
  270. }
  271. @Override
  272. public KeyPair next() {
  273. if (hasElement == null && !hasNext()
  274. || !hasElement.booleanValue()) {
  275. throw new NoSuchElementException();
  276. }
  277. hasElement = null;
  278. KeyPair result;
  279. try {
  280. result = current.next();
  281. } catch (NoSuchElementException e) {
  282. result = null;
  283. }
  284. return result;
  285. }
  286. };
  287. }
  288. }
  289. }