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 11KB

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