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.

JGitClientSession.java 11KB

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