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.

JschConfigSessionFactory.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /*
  2. * Copyright (C) 2016, Mark Ingram <markdingram@gmail.com>
  3. * Copyright (C) 2009, Constantine Plotnikov <constantine.plotnikov@gmail.com>
  4. * Copyright (C) 2008-2009, Google Inc.
  5. * Copyright (C) 2009, Google, Inc.
  6. * Copyright (C) 2009, JetBrains s.r.o.
  7. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  8. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  9. * and other copyright owners as documented in the project's IP log.
  10. *
  11. * This program and the accompanying materials are made available
  12. * under the terms of the Eclipse Distribution License v1.0 which
  13. * accompanies this distribution, is reproduced below, and is
  14. * available at http://www.eclipse.org/org/documents/edl-v10.php
  15. *
  16. * All rights reserved.
  17. *
  18. * Redistribution and use in source and binary forms, with or
  19. * without modification, are permitted provided that the following
  20. * conditions are met:
  21. *
  22. * - Redistributions of source code must retain the above copyright
  23. * notice, this list of conditions and the following disclaimer.
  24. *
  25. * - Redistributions in binary form must reproduce the above
  26. * copyright notice, this list of conditions and the following
  27. * disclaimer in the documentation and/or other materials provided
  28. * with the distribution.
  29. *
  30. * - Neither the name of the Eclipse Foundation, Inc. nor the
  31. * names of its contributors may be used to endorse or promote
  32. * products derived from this software without specific prior
  33. * written permission.
  34. *
  35. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  36. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  37. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  39. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  40. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  42. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  43. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  44. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  45. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  46. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  47. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  48. */
  49. package org.eclipse.jgit.transport;
  50. import java.io.File;
  51. import java.io.FileInputStream;
  52. import java.io.FileNotFoundException;
  53. import java.io.IOException;
  54. import java.lang.reflect.InvocationTargetException;
  55. import java.lang.reflect.Method;
  56. import java.net.ConnectException;
  57. import java.net.UnknownHostException;
  58. import java.text.MessageFormat;
  59. import java.util.HashMap;
  60. import java.util.Map;
  61. import org.eclipse.jgit.errors.TransportException;
  62. import org.eclipse.jgit.internal.JGitText;
  63. import org.eclipse.jgit.util.FS;
  64. import org.slf4j.Logger;
  65. import org.slf4j.LoggerFactory;
  66. import com.jcraft.jsch.JSch;
  67. import com.jcraft.jsch.JSchException;
  68. import com.jcraft.jsch.Session;
  69. import com.jcraft.jsch.UserInfo;
  70. /**
  71. * The base session factory that loads known hosts and private keys from
  72. * <code>$HOME/.ssh</code>.
  73. * <p>
  74. * This is the default implementation used by JGit and provides most of the
  75. * compatibility necessary to match OpenSSH, a popular implementation of SSH
  76. * used by C Git.
  77. * <p>
  78. * The factory does not provide UI behavior. Override the method
  79. * {@link #configure(org.eclipse.jgit.transport.OpenSshConfig.Host, Session)}
  80. * to supply appropriate {@link UserInfo} to the session.
  81. */
  82. public abstract class JschConfigSessionFactory extends SshSessionFactory {
  83. private static final Logger LOG = LoggerFactory
  84. .getLogger(JschConfigSessionFactory.class);
  85. private final Map<String, JSch> byIdentityFile = new HashMap<>();
  86. private JSch defaultJSch;
  87. private OpenSshConfig config;
  88. @Override
  89. public synchronized RemoteSession getSession(URIish uri,
  90. CredentialsProvider credentialsProvider, FS fs, int tms)
  91. throws TransportException {
  92. String user = uri.getUser();
  93. final String pass = uri.getPass();
  94. String host = uri.getHost();
  95. int port = uri.getPort();
  96. try {
  97. if (config == null)
  98. config = OpenSshConfig.get(fs);
  99. final OpenSshConfig.Host hc = config.lookup(host);
  100. host = hc.getHostName();
  101. if (port <= 0)
  102. port = hc.getPort();
  103. if (user == null)
  104. user = hc.getUser();
  105. Session session = createSession(credentialsProvider, fs, user,
  106. pass, host, port, hc);
  107. int retries = 0;
  108. while (!session.isConnected()) {
  109. try {
  110. retries++;
  111. session.connect(tms);
  112. } catch (JSchException e) {
  113. session.disconnect();
  114. session = null;
  115. // Make sure our known_hosts is not outdated
  116. knownHosts(getJSch(hc, fs), fs);
  117. if (isAuthenticationCanceled(e)) {
  118. throw e;
  119. } else if (isAuthenticationFailed(e)
  120. && credentialsProvider != null) {
  121. // if authentication failed maybe credentials changed at
  122. // the remote end therefore reset credentials and retry
  123. if (retries < 3) {
  124. credentialsProvider.reset(uri);
  125. session = createSession(credentialsProvider, fs,
  126. user, pass, host, port, hc);
  127. } else
  128. throw e;
  129. } else if (retries >= hc.getConnectionAttempts()) {
  130. throw e;
  131. } else {
  132. try {
  133. Thread.sleep(1000);
  134. session = createSession(credentialsProvider, fs,
  135. user, pass, host, port, hc);
  136. } catch (InterruptedException e1) {
  137. throw new TransportException(
  138. JGitText.get().transportSSHRetryInterrupt,
  139. e1);
  140. }
  141. }
  142. }
  143. }
  144. return new JschSession(session, uri);
  145. } catch (JSchException je) {
  146. final Throwable c = je.getCause();
  147. if (c instanceof UnknownHostException) {
  148. throw new TransportException(uri, JGitText.get().unknownHost,
  149. je);
  150. }
  151. if (c instanceof ConnectException) {
  152. throw new TransportException(uri, c.getMessage(), je);
  153. }
  154. throw new TransportException(uri, je.getMessage(), je);
  155. }
  156. }
  157. private static boolean isAuthenticationFailed(JSchException e) {
  158. return e.getCause() == null && e.getMessage().equals("Auth fail"); //$NON-NLS-1$
  159. }
  160. private static boolean isAuthenticationCanceled(JSchException e) {
  161. return e.getCause() == null && e.getMessage().equals("Auth cancel"); //$NON-NLS-1$
  162. }
  163. private Session createSession(CredentialsProvider credentialsProvider,
  164. FS fs, String user, final String pass, String host, int port,
  165. final OpenSshConfig.Host hc) throws JSchException {
  166. final Session session = createSession(hc, user, host, port, fs);
  167. // Jsch will have overridden the explicit user by the one from the SSH
  168. // config file...
  169. setUserName(session, user);
  170. // We retry already in getSession() method. JSch must not retry
  171. // on its own.
  172. session.setConfig("MaxAuthTries", "1"); //$NON-NLS-1$ //$NON-NLS-2$
  173. if (pass != null)
  174. session.setPassword(pass);
  175. final String strictHostKeyCheckingPolicy = hc
  176. .getStrictHostKeyChecking();
  177. if (strictHostKeyCheckingPolicy != null)
  178. session.setConfig("StrictHostKeyChecking", //$NON-NLS-1$
  179. strictHostKeyCheckingPolicy);
  180. final String pauth = hc.getPreferredAuthentications();
  181. if (pauth != null)
  182. session.setConfig("PreferredAuthentications", pauth); //$NON-NLS-1$
  183. if (credentialsProvider != null
  184. && (!hc.isBatchMode() || !credentialsProvider.isInteractive())) {
  185. session.setUserInfo(new CredentialsProviderUserInfo(session,
  186. credentialsProvider));
  187. }
  188. configure(hc, session);
  189. return session;
  190. }
  191. private void setUserName(Session session, String userName) {
  192. // Jsch 0.1.54 picks up the user name from the ssh config, even if an
  193. // explicit user name was given! We must correct that if ~/.ssh/config
  194. // has a different user name.
  195. if (userName == null || userName.isEmpty()
  196. || userName.equals(session.getUserName())) {
  197. return;
  198. }
  199. try {
  200. Class<?>[] parameterTypes = { String.class };
  201. Method method = Session.class.getDeclaredMethod("setUserName", //$NON-NLS-1$
  202. parameterTypes);
  203. method.setAccessible(true);
  204. method.invoke(session, userName);
  205. } catch (NullPointerException | IllegalAccessException
  206. | IllegalArgumentException | InvocationTargetException
  207. | NoSuchMethodException | SecurityException e) {
  208. LOG.error(MessageFormat.format(JGitText.get().sshUserNameError,
  209. userName, session.getUserName()), e);
  210. }
  211. }
  212. /**
  213. * Create a new remote session for the requested address.
  214. *
  215. * @param hc
  216. * host configuration
  217. * @param user
  218. * login to authenticate as.
  219. * @param host
  220. * server name to connect to.
  221. * @param port
  222. * port number of the SSH daemon (typically 22).
  223. * @param fs
  224. * the file system abstraction which will be necessary to
  225. * perform certain file system operations.
  226. * @return new session instance, but otherwise unconfigured.
  227. * @throws JSchException
  228. * the session could not be created.
  229. */
  230. protected Session createSession(final OpenSshConfig.Host hc,
  231. final String user, final String host, final int port, FS fs)
  232. throws JSchException {
  233. return getJSch(hc, fs).getSession(user, host, port);
  234. }
  235. /**
  236. * Provide additional configuration for the JSch instance. This method could
  237. * be overridden to supply a preferred
  238. * {@link com.jcraft.jsch.IdentityRepository}.
  239. *
  240. * @param jsch
  241. * jsch instance
  242. * @since 4.5
  243. */
  244. protected void configureJSch(JSch jsch) {
  245. // No additional configuration required.
  246. }
  247. /**
  248. * Provide additional configuration for the session based on the host
  249. * information. This method could be used to supply {@link UserInfo}.
  250. *
  251. * @param hc
  252. * host configuration
  253. * @param session
  254. * session to configure
  255. */
  256. protected abstract void configure(OpenSshConfig.Host hc, Session session);
  257. /**
  258. * Obtain the JSch used to create new sessions.
  259. *
  260. * @param hc
  261. * host configuration
  262. * @param fs
  263. * the file system abstraction which will be necessary to
  264. * perform certain file system operations.
  265. * @return the JSch instance to use.
  266. * @throws JSchException
  267. * the user configuration could not be created.
  268. */
  269. protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
  270. if (defaultJSch == null) {
  271. defaultJSch = createDefaultJSch(fs);
  272. if (defaultJSch.getConfigRepository() == null) {
  273. defaultJSch.setConfigRepository(config);
  274. }
  275. for (Object name : defaultJSch.getIdentityNames())
  276. byIdentityFile.put((String) name, defaultJSch);
  277. }
  278. final File identityFile = hc.getIdentityFile();
  279. if (identityFile == null)
  280. return defaultJSch;
  281. final String identityKey = identityFile.getAbsolutePath();
  282. JSch jsch = byIdentityFile.get(identityKey);
  283. if (jsch == null) {
  284. jsch = new JSch();
  285. configureJSch(jsch);
  286. if (jsch.getConfigRepository() == null) {
  287. jsch.setConfigRepository(defaultJSch.getConfigRepository());
  288. }
  289. jsch.setHostKeyRepository(defaultJSch.getHostKeyRepository());
  290. jsch.addIdentity(identityKey);
  291. byIdentityFile.put(identityKey, jsch);
  292. }
  293. return jsch;
  294. }
  295. /**
  296. * @param fs
  297. * the file system abstraction which will be necessary to
  298. * perform certain file system operations.
  299. * @return the new default JSch implementation.
  300. * @throws JSchException
  301. * known host keys cannot be loaded.
  302. */
  303. protected JSch createDefaultJSch(FS fs) throws JSchException {
  304. final JSch jsch = new JSch();
  305. configureJSch(jsch);
  306. knownHosts(jsch, fs);
  307. identities(jsch, fs);
  308. return jsch;
  309. }
  310. private static void knownHosts(final JSch sch, FS fs) throws JSchException {
  311. final File home = fs.userHome();
  312. if (home == null)
  313. return;
  314. final File known_hosts = new File(new File(home, ".ssh"), "known_hosts"); //$NON-NLS-1$ //$NON-NLS-2$
  315. try {
  316. final FileInputStream in = new FileInputStream(known_hosts);
  317. try {
  318. sch.setKnownHosts(in);
  319. } finally {
  320. in.close();
  321. }
  322. } catch (FileNotFoundException none) {
  323. // Oh well. They don't have a known hosts in home.
  324. } catch (IOException err) {
  325. // Oh well. They don't have a known hosts in home.
  326. }
  327. }
  328. private static void identities(final JSch sch, FS fs) {
  329. final File home = fs.userHome();
  330. if (home == null)
  331. return;
  332. final File sshdir = new File(home, ".ssh"); //$NON-NLS-1$
  333. if (sshdir.isDirectory()) {
  334. loadIdentity(sch, new File(sshdir, "identity")); //$NON-NLS-1$
  335. loadIdentity(sch, new File(sshdir, "id_rsa")); //$NON-NLS-1$
  336. loadIdentity(sch, new File(sshdir, "id_dsa")); //$NON-NLS-1$
  337. }
  338. }
  339. private static void loadIdentity(final JSch sch, final File priv) {
  340. if (priv.isFile()) {
  341. try {
  342. sch.addIdentity(priv.getAbsolutePath());
  343. } catch (JSchException e) {
  344. // Instead, pretend the key doesn't exist.
  345. }
  346. }
  347. }
  348. }