Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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