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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. import com.jcraft.jsch.UserInfo;
  73. /**
  74. * The base session factory that loads known hosts and private keys from
  75. * <code>$HOME/.ssh</code>.
  76. * <p>
  77. * This is the default implementation used by JGit and provides most of the
  78. * compatibility necessary to match OpenSSH, a popular implementation of SSH
  79. * used by C Git.
  80. * <p>
  81. * The factory does not provide UI behavior. Override the method
  82. * {@link #configure(org.eclipse.jgit.transport.OpenSshConfig.Host, Session)}
  83. * to supply appropriate {@link UserInfo} to the session.
  84. */
  85. public abstract class JschConfigSessionFactory extends SshSessionFactory {
  86. private static final Logger LOG = LoggerFactory
  87. .getLogger(JschConfigSessionFactory.class);
  88. /**
  89. * We use different Jsch instances for hosts that have an IdentityFile
  90. * configured in ~/.ssh/config. Jsch by default would cache decrypted keys
  91. * only per session, which results in repeated password prompts. Using
  92. * different Jsch instances, we can cache the keys on these instances so
  93. * that they will be re-used for successive sessions, and thus the user is
  94. * prompted for a key password only once while Eclipse runs.
  95. */
  96. private final Map<String, JSch> byIdentityFile = new HashMap<>();
  97. private JSch defaultJSch;
  98. private OpenSshConfig config;
  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 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 {@link UserInfo}.
  265. *
  266. * @param hc
  267. * host configuration
  268. * @param session
  269. * session to configure
  270. */
  271. protected abstract void configure(OpenSshConfig.Host hc, Session session);
  272. /**
  273. * Obtain the JSch used to create new sessions.
  274. *
  275. * @param hc
  276. * host configuration
  277. * @param fs
  278. * the file system abstraction which will be necessary to
  279. * perform certain file system operations.
  280. * @return the JSch instance to use.
  281. * @throws JSchException
  282. * the user configuration could not be created.
  283. */
  284. protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
  285. if (defaultJSch == null) {
  286. defaultJSch = createDefaultJSch(fs);
  287. if (defaultJSch.getConfigRepository() == null) {
  288. defaultJSch.setConfigRepository(
  289. new JschBugFixingConfigRepository(config));
  290. }
  291. for (Object name : defaultJSch.getIdentityNames())
  292. byIdentityFile.put((String) name, defaultJSch);
  293. }
  294. final File identityFile = hc.getIdentityFile();
  295. if (identityFile == null)
  296. return defaultJSch;
  297. final String identityKey = identityFile.getAbsolutePath();
  298. JSch jsch = byIdentityFile.get(identityKey);
  299. if (jsch == null) {
  300. jsch = new JSch();
  301. configureJSch(jsch);
  302. if (jsch.getConfigRepository() == null) {
  303. jsch.setConfigRepository(defaultJSch.getConfigRepository());
  304. }
  305. jsch.setHostKeyRepository(defaultJSch.getHostKeyRepository());
  306. jsch.addIdentity(identityKey);
  307. byIdentityFile.put(identityKey, jsch);
  308. }
  309. return jsch;
  310. }
  311. /**
  312. * @param fs
  313. * the file system abstraction which will be necessary to
  314. * perform certain file system operations.
  315. * @return the new default JSch implementation.
  316. * @throws JSchException
  317. * known host keys cannot be loaded.
  318. */
  319. protected JSch createDefaultJSch(FS fs) throws JSchException {
  320. final JSch jsch = new JSch();
  321. configureJSch(jsch);
  322. knownHosts(jsch, fs);
  323. identities(jsch, fs);
  324. return jsch;
  325. }
  326. private static void knownHosts(final JSch sch, FS fs) throws JSchException {
  327. final File home = fs.userHome();
  328. if (home == null)
  329. return;
  330. final File known_hosts = new File(new File(home, ".ssh"), "known_hosts"); //$NON-NLS-1$ //$NON-NLS-2$
  331. try {
  332. final FileInputStream in = new FileInputStream(known_hosts);
  333. try {
  334. sch.setKnownHosts(in);
  335. } finally {
  336. in.close();
  337. }
  338. } catch (FileNotFoundException none) {
  339. // Oh well. They don't have a known hosts in home.
  340. } catch (IOException err) {
  341. // Oh well. They don't have a known hosts in home.
  342. }
  343. }
  344. private static void identities(final JSch sch, FS fs) {
  345. final File home = fs.userHome();
  346. if (home == null)
  347. return;
  348. final File sshdir = new File(home, ".ssh"); //$NON-NLS-1$
  349. if (sshdir.isDirectory()) {
  350. loadIdentity(sch, new File(sshdir, "identity")); //$NON-NLS-1$
  351. loadIdentity(sch, new File(sshdir, "id_rsa")); //$NON-NLS-1$
  352. loadIdentity(sch, new File(sshdir, "id_dsa")); //$NON-NLS-1$
  353. }
  354. }
  355. private static void loadIdentity(final JSch sch, final File priv) {
  356. if (priv.isFile()) {
  357. try {
  358. sch.addIdentity(priv.getAbsolutePath());
  359. } catch (JSchException e) {
  360. // Instead, pretend the key doesn't exist.
  361. }
  362. }
  363. }
  364. private static class JschBugFixingConfigRepository
  365. implements ConfigRepository {
  366. private final ConfigRepository base;
  367. public JschBugFixingConfigRepository(ConfigRepository base) {
  368. this.base = base;
  369. }
  370. @Override
  371. public Config getConfig(String host) {
  372. return new JschBugFixingConfig(base.getConfig(host));
  373. }
  374. /**
  375. * A {@link com.jcraft.jsch.ConfigRepository.Config} that transforms
  376. * some values from the config file into the format Jsch 0.1.54 expects.
  377. * This is a work-around for bugs in Jsch.
  378. * <p>
  379. * Additionally, this config hides the IdentityFile config entries from
  380. * Jsch; we manage those ourselves. Otherwise Jsch would cache passwords
  381. * (or rather, decrypted keys) only for a single session, resulting in
  382. * multiple password prompts for user operations that use several Jsch
  383. * sessions.
  384. */
  385. private static class JschBugFixingConfig implements Config {
  386. private static final String[] NO_IDENTITIES = {};
  387. private final Config real;
  388. public JschBugFixingConfig(Config delegate) {
  389. real = delegate;
  390. }
  391. @Override
  392. public String getHostname() {
  393. return real.getHostname();
  394. }
  395. @Override
  396. public String getUser() {
  397. return real.getUser();
  398. }
  399. @Override
  400. public int getPort() {
  401. return real.getPort();
  402. }
  403. @Override
  404. public String getValue(String key) {
  405. String k = key.toUpperCase(Locale.ROOT);
  406. if ("IDENTITYFILE".equals(k)) { //$NON-NLS-1$
  407. return null;
  408. }
  409. String result = real.getValue(key);
  410. if (result != null) {
  411. if ("SERVERALIVEINTERVAL".equals(k) //$NON-NLS-1$
  412. || "CONNECTTIMEOUT".equals(k)) { //$NON-NLS-1$
  413. // These values are in seconds. Jsch 0.1.54 passes them
  414. // on as is to java.net.Socket.setSoTimeout(), which
  415. // expects milliseconds. So convert here to
  416. // milliseconds.
  417. try {
  418. int timeout = Integer.parseInt(result);
  419. result = Long.toString(
  420. TimeUnit.SECONDS.toMillis(timeout));
  421. } catch (NumberFormatException e) {
  422. // Ignore
  423. }
  424. }
  425. }
  426. return result;
  427. }
  428. @Override
  429. public String[] getValues(String key) {
  430. String k = key.toUpperCase(Locale.ROOT);
  431. if ("IDENTITYFILE".equals(k)) { //$NON-NLS-1$
  432. return NO_IDENTITIES;
  433. }
  434. return real.getValues(key);
  435. }
  436. }
  437. }
  438. /**
  439. * Set the {@link OpenSshConfig} to use. Intended for use in tests.
  440. *
  441. * @param config
  442. * to use
  443. */
  444. void setConfig(OpenSshConfig config) {
  445. this.config = config;
  446. }
  447. }