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

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