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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. // Nothing; we do this below together with the KEX init in
  139. // sendStartSsh(). Called only from the ClientSessionImpl constructor,
  140. // where the return value is ignored.
  141. return null;
  142. }
  143. @Override
  144. protected byte[] sendKexInit() throws IOException {
  145. StatefulProxyConnector proxy = proxyHandler;
  146. if (proxy != null) {
  147. try {
  148. // We must not block here; the framework starts reading messages
  149. // from the peer only once sendKexInit() has returned!
  150. proxy.runWhenDone(() -> {
  151. sendStartSsh();
  152. return null;
  153. });
  154. // sendKexInit() is called only from the ClientSessionImpl
  155. // constructor, where the return value is ignored.
  156. return null;
  157. } catch (IOException e) {
  158. throw e;
  159. } catch (Exception other) {
  160. throw new IOException(other.getLocalizedMessage(), other);
  161. }
  162. } else {
  163. return sendStartSsh();
  164. }
  165. }
  166. /**
  167. * Sends the initial messages starting the ssh setup: the client
  168. * identification and the KEX init message.
  169. *
  170. * @return the client's KEX seed
  171. * @throws IOException
  172. * if something goes wrong
  173. */
  174. private byte[] sendStartSsh() throws IOException {
  175. super.sendIdentification(clientVersion);
  176. return super.sendKexInit();
  177. }
  178. /**
  179. * {@inheritDoc}
  180. *
  181. * As long as we're still setting up the proxy connection, diverts messages
  182. * to the {@link StatefulProxyConnector}.
  183. */
  184. @Override
  185. public void messageReceived(Readable buffer) throws Exception {
  186. StatefulProxyConnector proxy = proxyHandler;
  187. if (proxy != null) {
  188. proxy.messageReceived(getIoSession(), buffer);
  189. } else {
  190. super.messageReceived(buffer);
  191. }
  192. }
  193. @Override
  194. protected void checkKeys() throws SshException {
  195. ServerKeyVerifier serverKeyVerifier = getServerKeyVerifier();
  196. // The super implementation always uses
  197. // getIoSession().getRemoteAddress(). In case of a proxy connection,
  198. // that would be the address of the proxy!
  199. SocketAddress remoteAddress = getConnectAddress();
  200. PublicKey serverKey = getKex().getServerKey();
  201. if (!serverKeyVerifier.verifyServerKey(this, remoteAddress,
  202. serverKey)) {
  203. throw new SshException(
  204. org.apache.sshd.common.SshConstants.SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE,
  205. SshdText.get().kexServerKeyInvalid);
  206. }
  207. }
  208. @Override
  209. protected String resolveAvailableSignaturesProposal(
  210. FactoryManager manager) {
  211. Set<String> defaultSignatures = new LinkedHashSet<>();
  212. defaultSignatures.addAll(getSignatureFactoriesNames());
  213. HostConfigEntry config = resolveAttribute(
  214. JGitSshClient.HOST_CONFIG_ENTRY);
  215. String hostKeyAlgorithms = config
  216. .getProperty(SshConstants.HOST_KEY_ALGORITHMS);
  217. if (hostKeyAlgorithms != null && !hostKeyAlgorithms.isEmpty()) {
  218. char first = hostKeyAlgorithms.charAt(0);
  219. if (first == '+') {
  220. // Additions make not much sense -- it's either in
  221. // defaultSignatures already, or we have no implementation for
  222. // it. No point in proposing it.
  223. return String.join(",", defaultSignatures); //$NON-NLS-1$
  224. } else if (first == '-') {
  225. // This takes wildcard patterns!
  226. removeFromList(defaultSignatures,
  227. SshConstants.HOST_KEY_ALGORITHMS,
  228. hostKeyAlgorithms.substring(1));
  229. if (defaultSignatures.isEmpty()) {
  230. // Too bad: user config error. Warn here, and then fail
  231. // later.
  232. log.warn(format(
  233. SshdText.get().configNoRemainingHostKeyAlgorithms,
  234. hostKeyAlgorithms));
  235. }
  236. return String.join(",", defaultSignatures); //$NON-NLS-1$
  237. } else {
  238. // Default is overridden -- only accept the ones for which we do
  239. // have an implementation.
  240. List<String> newNames = filteredList(defaultSignatures,
  241. hostKeyAlgorithms);
  242. if (newNames.isEmpty()) {
  243. log.warn(format(
  244. SshdText.get().configNoKnownHostKeyAlgorithms,
  245. hostKeyAlgorithms));
  246. // Use the default instead.
  247. } else {
  248. return String.join(",", newNames); //$NON-NLS-1$
  249. }
  250. }
  251. }
  252. // No HostKeyAlgorithms; using default -- change order to put existing
  253. // keys first.
  254. ServerKeyVerifier verifier = getServerKeyVerifier();
  255. if (verifier instanceof ServerKeyLookup) {
  256. SocketAddress remoteAddress = resolvePeerAddress(
  257. resolveAttribute(JGitSshClient.ORIGINAL_REMOTE_ADDRESS));
  258. List<HostEntryPair> allKnownKeys = ((ServerKeyLookup) verifier)
  259. .lookup(this, remoteAddress);
  260. Set<String> reordered = new LinkedHashSet<>();
  261. for (HostEntryPair h : allKnownKeys) {
  262. PublicKey key = h.getServerKey();
  263. if (key != null) {
  264. String keyType = KeyUtils.getKeyType(key);
  265. if (keyType != null) {
  266. reordered.add(keyType);
  267. }
  268. }
  269. }
  270. reordered.addAll(defaultSignatures);
  271. return String.join(",", reordered); //$NON-NLS-1$
  272. }
  273. return String.join(",", defaultSignatures); //$NON-NLS-1$
  274. }
  275. private void removeFromList(Set<String> current, String key,
  276. String patterns) {
  277. for (String toRemove : patterns.split("\\s*,\\s*")) { //$NON-NLS-1$
  278. if (toRemove.indexOf('*') < 0 && toRemove.indexOf('?') < 0) {
  279. current.remove(toRemove);
  280. continue;
  281. }
  282. try {
  283. FileNameMatcher matcher = new FileNameMatcher(toRemove, null);
  284. for (Iterator<String> i = current.iterator(); i.hasNext();) {
  285. matcher.reset();
  286. matcher.append(i.next());
  287. if (matcher.isMatch()) {
  288. i.remove();
  289. }
  290. }
  291. } catch (InvalidPatternException e) {
  292. log.warn(format(SshdText.get().configInvalidPattern, key,
  293. toRemove));
  294. }
  295. }
  296. }
  297. private List<String> filteredList(Set<String> known, String values) {
  298. List<String> newNames = new ArrayList<>();
  299. for (String newValue : values.split("\\s*,\\s*")) { //$NON-NLS-1$
  300. if (known.contains(newValue)) {
  301. newNames.add(newValue);
  302. }
  303. }
  304. return newNames;
  305. }
  306. }