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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 static org.eclipse.jgit.internal.transport.ssh.OpenSshConfigFile.positive;
  46. import java.io.IOException;
  47. import java.net.InetSocketAddress;
  48. import java.net.Proxy;
  49. import java.net.SocketAddress;
  50. import java.nio.file.Files;
  51. import java.nio.file.InvalidPathException;
  52. import java.nio.file.Path;
  53. import java.nio.file.Paths;
  54. import java.security.GeneralSecurityException;
  55. import java.security.KeyPair;
  56. import java.util.Arrays;
  57. import java.util.Iterator;
  58. import java.util.List;
  59. import java.util.NoSuchElementException;
  60. import java.util.Objects;
  61. import java.util.stream.Collectors;
  62. import org.apache.sshd.client.SshClient;
  63. import org.apache.sshd.client.config.hosts.HostConfigEntry;
  64. import org.apache.sshd.client.future.ConnectFuture;
  65. import org.apache.sshd.client.future.DefaultConnectFuture;
  66. import org.apache.sshd.client.session.ClientSessionImpl;
  67. import org.apache.sshd.client.session.SessionFactory;
  68. import org.apache.sshd.common.AttributeRepository;
  69. import org.apache.sshd.common.config.keys.FilePasswordProvider;
  70. import org.apache.sshd.common.future.SshFutureListener;
  71. import org.apache.sshd.common.io.IoConnectFuture;
  72. import org.apache.sshd.common.io.IoSession;
  73. import org.apache.sshd.common.keyprovider.AbstractResourceKeyPairProvider;
  74. import org.apache.sshd.common.keyprovider.KeyIdentityProvider;
  75. import org.apache.sshd.common.session.SessionContext;
  76. import org.apache.sshd.common.session.helpers.AbstractSession;
  77. import org.apache.sshd.common.util.ValidateUtils;
  78. import org.eclipse.jgit.internal.transport.sshd.proxy.HttpClientConnector;
  79. import org.eclipse.jgit.internal.transport.sshd.proxy.Socks5ClientConnector;
  80. import org.eclipse.jgit.transport.CredentialsProvider;
  81. import org.eclipse.jgit.transport.SshConstants;
  82. import org.eclipse.jgit.transport.sshd.KeyCache;
  83. import org.eclipse.jgit.transport.sshd.ProxyData;
  84. import org.eclipse.jgit.transport.sshd.ProxyDataFactory;
  85. /**
  86. * Customized {@link SshClient} for JGit. It creates specialized
  87. * {@link JGitClientSession}s that know about the {@link HostConfigEntry} they
  88. * were created for, and it loads all KeyPair identities lazily.
  89. */
  90. public class JGitSshClient extends SshClient {
  91. /**
  92. * We need access to this during the constructor of the ClientSession,
  93. * before setConnectAddress() can have been called. So we have to remember
  94. * it in an attribute on the SshClient, from where we can then retrieve it.
  95. */
  96. static final AttributeKey<HostConfigEntry> HOST_CONFIG_ENTRY = new AttributeKey<>();
  97. static final AttributeKey<InetSocketAddress> ORIGINAL_REMOTE_ADDRESS = new AttributeKey<>();
  98. /**
  99. * An attribute key for the comma-separated list of default preferred
  100. * authentication mechanisms.
  101. */
  102. public static final AttributeKey<String> PREFERRED_AUTHENTICATIONS = new AttributeKey<>();
  103. private KeyCache keyCache;
  104. private CredentialsProvider credentialsProvider;
  105. private ProxyDataFactory proxyDatabase;
  106. @Override
  107. protected SessionFactory createSessionFactory() {
  108. // Override the parent's default
  109. return new JGitSessionFactory(this);
  110. }
  111. @Override
  112. public ConnectFuture connect(HostConfigEntry hostConfig,
  113. AttributeRepository context, SocketAddress localAddress)
  114. throws IOException {
  115. if (connector == null) {
  116. throw new IllegalStateException("SshClient not started."); //$NON-NLS-1$
  117. }
  118. Objects.requireNonNull(hostConfig, "No host configuration"); //$NON-NLS-1$
  119. String host = ValidateUtils.checkNotNullAndNotEmpty(
  120. hostConfig.getHostName(), "No target host"); //$NON-NLS-1$
  121. int port = hostConfig.getPort();
  122. ValidateUtils.checkTrue(port > 0, "Invalid port: %d", port); //$NON-NLS-1$
  123. String userName = hostConfig.getUsername();
  124. InetSocketAddress address = new InetSocketAddress(host, port);
  125. ConnectFuture connectFuture = new DefaultConnectFuture(
  126. userName + '@' + address, null);
  127. SshFutureListener<IoConnectFuture> listener = createConnectCompletionListener(
  128. connectFuture, userName, address, hostConfig);
  129. // sshd needs some entries from the host config already in the
  130. // constructor of the session. Put those as properties on this client,
  131. // where it will find them. We can set the host config only once the
  132. // session object has been created.
  133. copyProperty(
  134. hostConfig.getProperty(SshConstants.PREFERRED_AUTHENTICATIONS,
  135. getAttribute(PREFERRED_AUTHENTICATIONS)),
  136. PREFERRED_AUTHS);
  137. setAttribute(HOST_CONFIG_ENTRY, hostConfig);
  138. setAttribute(ORIGINAL_REMOTE_ADDRESS, address);
  139. // Proxy support
  140. ProxyData proxy = getProxyData(address);
  141. if (proxy != null) {
  142. address = configureProxy(proxy, address);
  143. proxy.clearPassword();
  144. }
  145. connector.connect(address, this, localAddress).addListener(listener);
  146. return connectFuture;
  147. }
  148. private void copyProperty(String value, String key) {
  149. if (value != null && !value.isEmpty()) {
  150. getProperties().put(key, value);
  151. }
  152. }
  153. private ProxyData getProxyData(InetSocketAddress remoteAddress) {
  154. ProxyDataFactory factory = getProxyDatabase();
  155. return factory == null ? null : factory.get(remoteAddress);
  156. }
  157. private InetSocketAddress configureProxy(ProxyData proxyData,
  158. InetSocketAddress remoteAddress) {
  159. Proxy proxy = proxyData.getProxy();
  160. if (proxy.type() == Proxy.Type.DIRECT
  161. || !(proxy.address() instanceof InetSocketAddress)) {
  162. return remoteAddress;
  163. }
  164. InetSocketAddress address = (InetSocketAddress) proxy.address();
  165. if (address.isUnresolved()) {
  166. address = new InetSocketAddress(address.getHostName(),
  167. address.getPort());
  168. }
  169. switch (proxy.type()) {
  170. case HTTP:
  171. setClientProxyConnector(
  172. new HttpClientConnector(address, remoteAddress,
  173. proxyData.getUser(), proxyData.getPassword()));
  174. return address;
  175. case SOCKS:
  176. setClientProxyConnector(
  177. new Socks5ClientConnector(address, remoteAddress,
  178. proxyData.getUser(), proxyData.getPassword()));
  179. return address;
  180. default:
  181. log.warn(format(SshdText.get().unknownProxyProtocol,
  182. proxy.type().name()));
  183. return remoteAddress;
  184. }
  185. }
  186. private SshFutureListener<IoConnectFuture> createConnectCompletionListener(
  187. ConnectFuture connectFuture, String username,
  188. InetSocketAddress address, HostConfigEntry hostConfig) {
  189. return new SshFutureListener<IoConnectFuture>() {
  190. @Override
  191. public void operationComplete(IoConnectFuture future) {
  192. if (future.isCanceled()) {
  193. connectFuture.cancel();
  194. return;
  195. }
  196. Throwable t = future.getException();
  197. if (t != null) {
  198. connectFuture.setException(t);
  199. return;
  200. }
  201. IoSession ioSession = future.getSession();
  202. try {
  203. JGitClientSession session = createSession(ioSession,
  204. username, address, hostConfig);
  205. connectFuture.setSession(session);
  206. } catch (RuntimeException e) {
  207. connectFuture.setException(e);
  208. ioSession.close(true);
  209. }
  210. }
  211. @Override
  212. public String toString() {
  213. return "JGitSshClient$ConnectCompletionListener[" + username //$NON-NLS-1$
  214. + '@' + address + ']';
  215. }
  216. };
  217. }
  218. private JGitClientSession createSession(IoSession ioSession,
  219. String username, InetSocketAddress address,
  220. HostConfigEntry hostConfig) {
  221. AbstractSession rawSession = AbstractSession.getSession(ioSession);
  222. if (!(rawSession instanceof JGitClientSession)) {
  223. throw new IllegalStateException("Wrong session type: " //$NON-NLS-1$
  224. + rawSession.getClass().getCanonicalName());
  225. }
  226. JGitClientSession session = (JGitClientSession) rawSession;
  227. session.setUsername(username);
  228. session.setConnectAddress(address);
  229. session.setHostConfigEntry(hostConfig);
  230. if (session.getCredentialsProvider() == null) {
  231. session.setCredentialsProvider(getCredentialsProvider());
  232. }
  233. int numberOfPasswordPrompts = getNumberOfPasswordPrompts(hostConfig);
  234. session.getProperties().put(PASSWORD_PROMPTS,
  235. Integer.valueOf(numberOfPasswordPrompts));
  236. FilePasswordProvider passwordProvider = getFilePasswordProvider();
  237. if (passwordProvider instanceof RepeatingFilePasswordProvider) {
  238. ((RepeatingFilePasswordProvider) passwordProvider)
  239. .setAttempts(numberOfPasswordPrompts);
  240. }
  241. List<Path> identities = hostConfig.getIdentities().stream()
  242. .map(s -> {
  243. try {
  244. return Paths.get(s);
  245. } catch (InvalidPathException e) {
  246. log.warn(format(SshdText.get().configInvalidPath,
  247. SshConstants.IDENTITY_FILE, s), e);
  248. return null;
  249. }
  250. }).filter(p -> p != null && Files.exists(p))
  251. .collect(Collectors.toList());
  252. CachingKeyPairProvider ourConfiguredKeysProvider = new CachingKeyPairProvider(
  253. identities, keyCache);
  254. ourConfiguredKeysProvider.setPasswordFinder(passwordProvider);
  255. if (hostConfig.isIdentitiesOnly()) {
  256. session.setKeyIdentityProvider(ourConfiguredKeysProvider);
  257. } else {
  258. KeyIdentityProvider defaultKeysProvider = getKeyIdentityProvider();
  259. if (defaultKeysProvider instanceof AbstractResourceKeyPairProvider<?>) {
  260. ((AbstractResourceKeyPairProvider<?>) defaultKeysProvider)
  261. .setPasswordFinder(passwordProvider);
  262. }
  263. KeyIdentityProvider combinedProvider = new CombinedKeyIdentityProvider(
  264. ourConfiguredKeysProvider, defaultKeysProvider);
  265. session.setKeyIdentityProvider(combinedProvider);
  266. }
  267. return session;
  268. }
  269. private int getNumberOfPasswordPrompts(HostConfigEntry hostConfig) {
  270. String prompts = hostConfig
  271. .getProperty(SshConstants.NUMBER_OF_PASSWORD_PROMPTS);
  272. if (prompts != null) {
  273. prompts = prompts.trim();
  274. int value = positive(prompts);
  275. if (value > 0) {
  276. return value;
  277. }
  278. log.warn(format(SshdText.get().configInvalidPositive,
  279. SshConstants.NUMBER_OF_PASSWORD_PROMPTS, prompts));
  280. }
  281. // Default for NumberOfPasswordPrompts according to
  282. // https://man.openbsd.org/ssh_config
  283. return 3;
  284. }
  285. /**
  286. * Set a cache for loaded keys. Newly discovered keys will be added when
  287. * IdentityFile host entries from the ssh config file are used during
  288. * session authentication.
  289. *
  290. * @param cache
  291. * to use
  292. */
  293. public void setKeyCache(KeyCache cache) {
  294. keyCache = cache;
  295. }
  296. /**
  297. * Sets a {@link ProxyDataFactory} for connecting through proxies.
  298. *
  299. * @param factory
  300. * to use, or {@code null} if proxying is not desired or
  301. * supported
  302. */
  303. public void setProxyDatabase(ProxyDataFactory factory) {
  304. proxyDatabase = factory;
  305. }
  306. /**
  307. * Retrieves the {@link ProxyDataFactory}.
  308. *
  309. * @return the factory, or {@code null} if none is set
  310. */
  311. protected ProxyDataFactory getProxyDatabase() {
  312. return proxyDatabase;
  313. }
  314. /**
  315. * Sets the {@link CredentialsProvider} for this client.
  316. *
  317. * @param provider
  318. * to set
  319. */
  320. public void setCredentialsProvider(CredentialsProvider provider) {
  321. credentialsProvider = provider;
  322. }
  323. /**
  324. * Retrieves the {@link CredentialsProvider} set for this client.
  325. *
  326. * @return the provider, or {@code null} if none is set.
  327. */
  328. public CredentialsProvider getCredentialsProvider() {
  329. return credentialsProvider;
  330. }
  331. /**
  332. * A {@link SessionFactory} to create our own specialized
  333. * {@link JGitClientSession}s.
  334. */
  335. private static class JGitSessionFactory extends SessionFactory {
  336. public JGitSessionFactory(JGitSshClient client) {
  337. super(client);
  338. }
  339. @Override
  340. protected ClientSessionImpl doCreateSession(IoSession ioSession)
  341. throws Exception {
  342. return new JGitClientSession(getClient(), ioSession);
  343. }
  344. }
  345. /**
  346. * A {@link KeyIdentityProvider} that iterates over the {@link Iterable}s
  347. * returned by other {@link KeyIdentityProvider}s.
  348. */
  349. private static class CombinedKeyIdentityProvider
  350. implements KeyIdentityProvider {
  351. private final List<KeyIdentityProvider> providers;
  352. public CombinedKeyIdentityProvider(KeyIdentityProvider... providers) {
  353. this(Arrays.stream(providers).filter(Objects::nonNull)
  354. .collect(Collectors.toList()));
  355. }
  356. public CombinedKeyIdentityProvider(
  357. List<KeyIdentityProvider> providers) {
  358. this.providers = providers;
  359. }
  360. @Override
  361. public Iterable<KeyPair> loadKeys(SessionContext context) {
  362. return () -> new Iterator<KeyPair>() {
  363. private Iterator<KeyIdentityProvider> factories = providers
  364. .iterator();
  365. private Iterator<KeyPair> current;
  366. private Boolean hasElement;
  367. @Override
  368. public boolean hasNext() {
  369. if (hasElement != null) {
  370. return hasElement.booleanValue();
  371. }
  372. while (current == null || !current.hasNext()) {
  373. if (factories.hasNext()) {
  374. try {
  375. current = factories.next().loadKeys(context)
  376. .iterator();
  377. } catch (IOException | GeneralSecurityException e) {
  378. throw new RuntimeException(e);
  379. }
  380. } else {
  381. current = null;
  382. hasElement = Boolean.FALSE;
  383. return false;
  384. }
  385. }
  386. hasElement = Boolean.TRUE;
  387. return true;
  388. }
  389. @Override
  390. public KeyPair next() {
  391. if (hasElement == null && !hasNext()
  392. || !hasElement.booleanValue()) {
  393. throw new NoSuchElementException();
  394. }
  395. hasElement = null;
  396. KeyPair result;
  397. try {
  398. result = current.next();
  399. } catch (NoSuchElementException e) {
  400. result = null;
  401. }
  402. return result;
  403. }
  404. };
  405. }
  406. }
  407. }