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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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.Locale;
  61. import java.util.Map;
  62. import java.util.concurrent.TimeUnit;
  63. import org.eclipse.jgit.errors.TransportException;
  64. import org.eclipse.jgit.internal.JGitText;
  65. import org.eclipse.jgit.util.FS;
  66. import org.slf4j.Logger;
  67. import org.slf4j.LoggerFactory;
  68. import com.jcraft.jsch.ConfigRepository;
  69. import com.jcraft.jsch.JSch;
  70. import com.jcraft.jsch.JSchException;
  71. import com.jcraft.jsch.Session;
  72. /**
  73. * The base session factory that loads known hosts and private keys from
  74. * <code>$HOME/.ssh</code>.
  75. * <p>
  76. * This is the default implementation used by JGit and provides most of the
  77. * compatibility necessary to match OpenSSH, a popular implementation of SSH
  78. * used by C Git.
  79. * <p>
  80. * The factory does not provide UI behavior. Override the method
  81. * {@link #configure(org.eclipse.jgit.transport.OpenSshConfig.Host, Session)} to
  82. * supply appropriate {@link com.jcraft.jsch.UserInfo} to the session.
  83. */
  84. public abstract class JschConfigSessionFactory extends SshSessionFactory {
  85. private static final Logger LOG = LoggerFactory
  86. .getLogger(JschConfigSessionFactory.class);
  87. /**
  88. * We use different Jsch instances for hosts that have an IdentityFile
  89. * configured in ~/.ssh/config. Jsch by default would cache decrypted keys
  90. * only per session, which results in repeated password prompts. Using
  91. * different Jsch instances, we can cache the keys on these instances so
  92. * that they will be re-used for successive sessions, and thus the user is
  93. * prompted for a key password only once while Eclipse runs.
  94. */
  95. private final Map<String, JSch> byIdentityFile = new HashMap<>();
  96. private JSch defaultJSch;
  97. private OpenSshConfig config;
  98. /** {@inheritDoc} */
  99. @Override
  100. public synchronized RemoteSession getSession(URIish uri,
  101. CredentialsProvider credentialsProvider, FS fs, int tms)
  102. throws TransportException {
  103. String user = uri.getUser();
  104. final String pass = uri.getPass();
  105. String host = uri.getHost();
  106. int port = uri.getPort();
  107. try {
  108. if (config == null)
  109. config = OpenSshConfig.get(fs);
  110. final OpenSshConfig.Host hc = config.lookup(host);
  111. if (port <= 0)
  112. port = hc.getPort();
  113. if (user == null)
  114. user = hc.getUser();
  115. Session session = createSession(credentialsProvider, fs, user,
  116. pass, host, port, hc);
  117. int retries = 0;
  118. while (!session.isConnected()) {
  119. try {
  120. retries++;
  121. session.connect(tms);
  122. } catch (JSchException e) {
  123. session.disconnect();
  124. session = null;
  125. // Make sure our known_hosts is not outdated
  126. knownHosts(getJSch(hc, fs), fs);
  127. if (isAuthenticationCanceled(e)) {
  128. throw e;
  129. } else if (isAuthenticationFailed(e)
  130. && credentialsProvider != null) {
  131. // if authentication failed maybe credentials changed at
  132. // the remote end therefore reset credentials and retry
  133. if (retries < 3) {
  134. credentialsProvider.reset(uri);
  135. session = createSession(credentialsProvider, fs,
  136. user, pass, host, port, hc);
  137. } else
  138. throw e;
  139. } else if (retries >= hc.getConnectionAttempts()) {
  140. throw e;
  141. } else {
  142. try {
  143. Thread.sleep(1000);
  144. session = createSession(credentialsProvider, fs,
  145. user, pass, host, port, hc);
  146. } catch (InterruptedException e1) {
  147. throw new TransportException(
  148. JGitText.get().transportSSHRetryInterrupt,
  149. e1);
  150. }
  151. }
  152. }
  153. }
  154. return new JschSession(session, uri);
  155. } catch (JSchException je) {
  156. final Throwable c = je.getCause();
  157. if (c instanceof UnknownHostException) {
  158. throw new TransportException(uri, JGitText.get().unknownHost,
  159. je);
  160. }
  161. if (c instanceof ConnectException) {
  162. throw new TransportException(uri, c.getMessage(), je);
  163. }
  164. throw new TransportException(uri, je.getMessage(), je);
  165. }
  166. }
  167. private static boolean isAuthenticationFailed(JSchException e) {
  168. return e.getCause() == null && e.getMessage().equals("Auth fail"); //$NON-NLS-1$
  169. }
  170. private static boolean isAuthenticationCanceled(JSchException e) {
  171. return e.getCause() == null && e.getMessage().equals("Auth cancel"); //$NON-NLS-1$
  172. }
  173. // Package visibility for tests
  174. Session createSession(CredentialsProvider credentialsProvider,
  175. FS fs, String user, final String pass, String host, int port,
  176. final OpenSshConfig.Host hc) throws JSchException {
  177. final Session session = createSession(hc, user, host, port, fs);
  178. // Jsch will have overridden the explicit user by the one from the SSH
  179. // config file...
  180. setUserName(session, user);
  181. // Jsch will also have overridden the port.
  182. if (port > 0 && port != session.getPort()) {
  183. session.setPort(port);
  184. }
  185. // We retry already in getSession() method. JSch must not retry
  186. // on its own.
  187. session.setConfig("MaxAuthTries", "1"); //$NON-NLS-1$ //$NON-NLS-2$
  188. if (pass != null)
  189. session.setPassword(pass);
  190. final String strictHostKeyCheckingPolicy = hc
  191. .getStrictHostKeyChecking();
  192. if (strictHostKeyCheckingPolicy != null)
  193. session.setConfig("StrictHostKeyChecking", //$NON-NLS-1$
  194. strictHostKeyCheckingPolicy);
  195. final String pauth = hc.getPreferredAuthentications();
  196. if (pauth != null)
  197. session.setConfig("PreferredAuthentications", pauth); //$NON-NLS-1$
  198. if (credentialsProvider != null
  199. && (!hc.isBatchMode() || !credentialsProvider.isInteractive())) {
  200. session.setUserInfo(new CredentialsProviderUserInfo(session,
  201. credentialsProvider));
  202. }
  203. configure(hc, session);
  204. return session;
  205. }
  206. private void setUserName(Session session, String userName) {
  207. // Jsch 0.1.54 picks up the user name from the ssh config, even if an
  208. // explicit user name was given! We must correct that if ~/.ssh/config
  209. // has a different user name.
  210. if (userName == null || userName.isEmpty()
  211. || userName.equals(session.getUserName())) {
  212. return;
  213. }
  214. try {
  215. Class<?>[] parameterTypes = { String.class };
  216. Method method = Session.class.getDeclaredMethod("setUserName", //$NON-NLS-1$
  217. parameterTypes);
  218. method.setAccessible(true);
  219. method.invoke(session, userName);
  220. } catch (NullPointerException | IllegalAccessException
  221. | IllegalArgumentException | InvocationTargetException
  222. | NoSuchMethodException | SecurityException e) {
  223. LOG.error(MessageFormat.format(JGitText.get().sshUserNameError,
  224. userName, session.getUserName()), e);
  225. }
  226. }
  227. /**
  228. * Create a new remote session for the requested address.
  229. *
  230. * @param hc
  231. * host configuration
  232. * @param user
  233. * login to authenticate as.
  234. * @param host
  235. * server name to connect to.
  236. * @param port
  237. * port number of the SSH daemon (typically 22).
  238. * @param fs
  239. * the file system abstraction which will be necessary to
  240. * perform certain file system operations.
  241. * @return new session instance, but otherwise unconfigured.
  242. * @throws com.jcraft.jsch.JSchException
  243. * the session could not be created.
  244. */
  245. protected Session createSession(final OpenSshConfig.Host hc,
  246. final String user, final String host, final int port, FS fs)
  247. throws JSchException {
  248. return getJSch(hc, fs).getSession(user, host, port);
  249. }
  250. /**
  251. * Provide additional configuration for the JSch instance. This method could
  252. * be overridden to supply a preferred
  253. * {@link com.jcraft.jsch.IdentityRepository}.
  254. *
  255. * @param jsch
  256. * jsch instance
  257. * @since 4.5
  258. */
  259. protected void configureJSch(JSch jsch) {
  260. // No additional configuration required.
  261. }
  262. /**
  263. * Provide additional configuration for the session based on the host
  264. * information. This method could be used to supply
  265. * {@link com.jcraft.jsch.UserInfo}.
  266. *
  267. * @param hc
  268. * host configuration
  269. * @param session
  270. * session to configure
  271. */
  272. protected abstract void configure(OpenSshConfig.Host hc, Session session);
  273. /**
  274. * Obtain the JSch used to create new sessions.
  275. *
  276. * @param hc
  277. * host configuration
  278. * @param fs
  279. * the file system abstraction which will be necessary to
  280. * perform certain file system operations.
  281. * @return the JSch instance to use.
  282. * @throws com.jcraft.jsch.JSchException
  283. * the user configuration could not be created.
  284. */
  285. protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
  286. if (defaultJSch == null) {
  287. defaultJSch = createDefaultJSch(fs);
  288. if (defaultJSch.getConfigRepository() == null) {
  289. defaultJSch.setConfigRepository(
  290. new JschBugFixingConfigRepository(config));
  291. }
  292. for (Object name : defaultJSch.getIdentityNames())
  293. byIdentityFile.put((String) name, defaultJSch);
  294. }
  295. final File identityFile = hc.getIdentityFile();
  296. if (identityFile == null)
  297. return defaultJSch;
  298. final String identityKey = identityFile.getAbsolutePath();
  299. JSch jsch = byIdentityFile.get(identityKey);
  300. if (jsch == null) {
  301. jsch = new JSch();
  302. configureJSch(jsch);
  303. if (jsch.getConfigRepository() == null) {
  304. jsch.setConfigRepository(defaultJSch.getConfigRepository());
  305. }
  306. jsch.setHostKeyRepository(defaultJSch.getHostKeyRepository());
  307. jsch.addIdentity(identityKey);
  308. byIdentityFile.put(identityKey, jsch);
  309. }
  310. return jsch;
  311. }
  312. /**
  313. * Create default instance of jsch
  314. *
  315. * @param fs
  316. * the file system abstraction which will be necessary to perform
  317. * certain file system operations.
  318. * @return the new default JSch implementation.
  319. * @throws com.jcraft.jsch.JSchException
  320. * known host keys cannot be loaded.
  321. */
  322. protected JSch createDefaultJSch(FS fs) throws JSchException {
  323. final JSch jsch = new JSch();
  324. configureJSch(jsch);
  325. knownHosts(jsch, fs);
  326. identities(jsch, fs);
  327. return jsch;
  328. }
  329. private static void knownHosts(final JSch sch, FS fs) throws JSchException {
  330. final File home = fs.userHome();
  331. if (home == null)
  332. return;
  333. final File known_hosts = new File(new File(home, ".ssh"), "known_hosts"); //$NON-NLS-1$ //$NON-NLS-2$
  334. try {
  335. final FileInputStream in = new FileInputStream(known_hosts);
  336. try {
  337. sch.setKnownHosts(in);
  338. } finally {
  339. in.close();
  340. }
  341. } catch (FileNotFoundException none) {
  342. // Oh well. They don't have a known hosts in home.
  343. } catch (IOException err) {
  344. // Oh well. They don't have a known hosts in home.
  345. }
  346. }
  347. private static void identities(final JSch sch, FS fs) {
  348. final File home = fs.userHome();
  349. if (home == null)
  350. return;
  351. final File sshdir = new File(home, ".ssh"); //$NON-NLS-1$
  352. if (sshdir.isDirectory()) {
  353. loadIdentity(sch, new File(sshdir, "identity")); //$NON-NLS-1$
  354. loadIdentity(sch, new File(sshdir, "id_rsa")); //$NON-NLS-1$
  355. loadIdentity(sch, new File(sshdir, "id_dsa")); //$NON-NLS-1$
  356. }
  357. }
  358. private static void loadIdentity(final JSch sch, final File priv) {
  359. if (priv.isFile()) {
  360. try {
  361. sch.addIdentity(priv.getAbsolutePath());
  362. } catch (JSchException e) {
  363. // Instead, pretend the key doesn't exist.
  364. }
  365. }
  366. }
  367. private static class JschBugFixingConfigRepository
  368. implements ConfigRepository {
  369. private final ConfigRepository base;
  370. public JschBugFixingConfigRepository(ConfigRepository base) {
  371. this.base = base;
  372. }
  373. @Override
  374. public Config getConfig(String host) {
  375. return new JschBugFixingConfig(base.getConfig(host));
  376. }
  377. /**
  378. * A {@link com.jcraft.jsch.ConfigRepository.Config} that transforms
  379. * some values from the config file into the format Jsch 0.1.54 expects.
  380. * This is a work-around for bugs in Jsch.
  381. * <p>
  382. * Additionally, this config hides the IdentityFile config entries from
  383. * Jsch; we manage those ourselves. Otherwise Jsch would cache passwords
  384. * (or rather, decrypted keys) only for a single session, resulting in
  385. * multiple password prompts for user operations that use several Jsch
  386. * sessions.
  387. */
  388. private static class JschBugFixingConfig implements Config {
  389. private static final String[] NO_IDENTITIES = {};
  390. private final Config real;
  391. public JschBugFixingConfig(Config delegate) {
  392. real = delegate;
  393. }
  394. @Override
  395. public String getHostname() {
  396. return real.getHostname();
  397. }
  398. @Override
  399. public String getUser() {
  400. return real.getUser();
  401. }
  402. @Override
  403. public int getPort() {
  404. return real.getPort();
  405. }
  406. @Override
  407. public String getValue(String key) {
  408. String k = key.toUpperCase(Locale.ROOT);
  409. if ("IDENTITYFILE".equals(k)) { //$NON-NLS-1$
  410. return null;
  411. }
  412. String result = real.getValue(key);
  413. if (result != null) {
  414. if ("SERVERALIVEINTERVAL".equals(k) //$NON-NLS-1$
  415. || "CONNECTTIMEOUT".equals(k)) { //$NON-NLS-1$
  416. // These values are in seconds. Jsch 0.1.54 passes them
  417. // on as is to java.net.Socket.setSoTimeout(), which
  418. // expects milliseconds. So convert here to
  419. // milliseconds.
  420. try {
  421. int timeout = Integer.parseInt(result);
  422. result = Long.toString(
  423. TimeUnit.SECONDS.toMillis(timeout));
  424. } catch (NumberFormatException e) {
  425. // Ignore
  426. }
  427. }
  428. }
  429. return result;
  430. }
  431. @Override
  432. public String[] getValues(String key) {
  433. String k = key.toUpperCase(Locale.ROOT);
  434. if ("IDENTITYFILE".equals(k)) { //$NON-NLS-1$
  435. return NO_IDENTITIES;
  436. }
  437. return real.getValues(key);
  438. }
  439. }
  440. }
  441. /**
  442. * Set the {@link OpenSshConfig} to use. Intended for use in tests.
  443. *
  444. * @param config
  445. * to use
  446. */
  447. void setConfig(OpenSshConfig config) {
  448. this.config = config;
  449. }
  450. }