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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /*
  2. * Copyright (C) 2018, Sasa Zivkov <sasa.zivkov@sap.com>
  3. * Copyright (C) 2016, Mark Ingram <markdingram@gmail.com>
  4. * Copyright (C) 2009, Constantine Plotnikov <constantine.plotnikov@gmail.com>
  5. * Copyright (C) 2008-2009, Google Inc.
  6. * Copyright (C) 2009, Google, Inc.
  7. * Copyright (C) 2009, JetBrains s.r.o.
  8. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  9. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  10. * and other copyright owners as documented in the project's IP log.
  11. *
  12. * This program and the accompanying materials are made available
  13. * under the terms of the Eclipse Distribution License v1.0 which
  14. * accompanies this distribution, is reproduced below, and is
  15. * available at http://www.eclipse.org/org/documents/edl-v10.php
  16. *
  17. * All rights reserved.
  18. *
  19. * Redistribution and use in source and binary forms, with or
  20. * without modification, are permitted provided that the following
  21. * conditions are met:
  22. *
  23. * - Redistributions of source code must retain the above copyright
  24. * notice, this list of conditions and the following disclaimer.
  25. *
  26. * - Redistributions in binary form must reproduce the above
  27. * copyright notice, this list of conditions and the following
  28. * disclaimer in the documentation and/or other materials provided
  29. * with the distribution.
  30. *
  31. * - Neither the name of the Eclipse Foundation, Inc. nor the
  32. * names of its contributors may be used to endorse or promote
  33. * products derived from this software without specific prior
  34. * written permission.
  35. *
  36. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  37. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  38. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  39. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  40. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  41. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  42. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  43. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  44. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  45. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  46. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  47. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  48. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  49. */
  50. package org.eclipse.jgit.transport;
  51. import static java.util.stream.Collectors.joining;
  52. import static java.util.stream.Collectors.toList;
  53. import static org.eclipse.jgit.transport.OpenSshConfig.SSH_PORT;
  54. import java.io.File;
  55. import java.io.FileInputStream;
  56. import java.io.FileNotFoundException;
  57. import java.io.IOException;
  58. import java.lang.reflect.InvocationTargetException;
  59. import java.lang.reflect.Method;
  60. import java.net.ConnectException;
  61. import java.net.UnknownHostException;
  62. import java.text.MessageFormat;
  63. import java.util.HashMap;
  64. import java.util.List;
  65. import java.util.Locale;
  66. import java.util.Map;
  67. import java.util.concurrent.TimeUnit;
  68. import java.util.stream.Stream;
  69. import org.eclipse.jgit.errors.TransportException;
  70. import org.eclipse.jgit.internal.JGitText;
  71. import org.eclipse.jgit.util.FS;
  72. import org.slf4j.Logger;
  73. import org.slf4j.LoggerFactory;
  74. import com.jcraft.jsch.ConfigRepository;
  75. import com.jcraft.jsch.ConfigRepository.Config;
  76. import com.jcraft.jsch.HostKey;
  77. import com.jcraft.jsch.HostKeyRepository;
  78. import com.jcraft.jsch.JSch;
  79. import com.jcraft.jsch.JSchException;
  80. import com.jcraft.jsch.Session;
  81. /**
  82. * The base session factory that loads known hosts and private keys from
  83. * <code>$HOME/.ssh</code>.
  84. * <p>
  85. * This is the default implementation used by JGit and provides most of the
  86. * compatibility necessary to match OpenSSH, a popular implementation of SSH
  87. * used by C Git.
  88. * <p>
  89. * The factory does not provide UI behavior. Override the method
  90. * {@link #configure(org.eclipse.jgit.transport.OpenSshConfig.Host, Session)} to
  91. * supply appropriate {@link com.jcraft.jsch.UserInfo} to the session.
  92. */
  93. public abstract class JschConfigSessionFactory extends SshSessionFactory {
  94. private static final Logger LOG = LoggerFactory
  95. .getLogger(JschConfigSessionFactory.class);
  96. /**
  97. * We use different Jsch instances for hosts that have an IdentityFile
  98. * configured in ~/.ssh/config. Jsch by default would cache decrypted keys
  99. * only per session, which results in repeated password prompts. Using
  100. * different Jsch instances, we can cache the keys on these instances so
  101. * that they will be re-used for successive sessions, and thus the user is
  102. * prompted for a key password only once while Eclipse runs.
  103. */
  104. private final Map<String, JSch> byIdentityFile = new HashMap<>();
  105. private JSch defaultJSch;
  106. private OpenSshConfig config;
  107. /** {@inheritDoc} */
  108. @Override
  109. public synchronized RemoteSession getSession(URIish uri,
  110. CredentialsProvider credentialsProvider, FS fs, int tms)
  111. throws TransportException {
  112. String user = uri.getUser();
  113. final String pass = uri.getPass();
  114. String host = uri.getHost();
  115. int port = uri.getPort();
  116. try {
  117. if (config == null)
  118. config = OpenSshConfig.get(fs);
  119. final OpenSshConfig.Host hc = config.lookup(host);
  120. if (port <= 0)
  121. port = hc.getPort();
  122. if (user == null)
  123. user = hc.getUser();
  124. Session session = createSession(credentialsProvider, fs, user,
  125. pass, host, port, hc);
  126. int retries = 0;
  127. while (!session.isConnected()) {
  128. try {
  129. retries++;
  130. session.connect(tms);
  131. } catch (JSchException e) {
  132. session.disconnect();
  133. session = null;
  134. // Make sure our known_hosts is not outdated
  135. knownHosts(getJSch(hc, fs), fs);
  136. if (isAuthenticationCanceled(e)) {
  137. throw e;
  138. } else if (isAuthenticationFailed(e)
  139. && credentialsProvider != null) {
  140. // if authentication failed maybe credentials changed at
  141. // the remote end therefore reset credentials and retry
  142. if (retries < 3) {
  143. credentialsProvider.reset(uri);
  144. session = createSession(credentialsProvider, fs,
  145. user, pass, host, port, hc);
  146. } else
  147. throw e;
  148. } else if (retries >= hc.getConnectionAttempts()) {
  149. throw e;
  150. } else {
  151. try {
  152. Thread.sleep(1000);
  153. session = createSession(credentialsProvider, fs,
  154. user, pass, host, port, hc);
  155. } catch (InterruptedException e1) {
  156. throw new TransportException(
  157. JGitText.get().transportSSHRetryInterrupt,
  158. e1);
  159. }
  160. }
  161. }
  162. }
  163. return new JschSession(session, uri);
  164. } catch (JSchException je) {
  165. final Throwable c = je.getCause();
  166. if (c instanceof UnknownHostException) {
  167. throw new TransportException(uri, JGitText.get().unknownHost,
  168. je);
  169. }
  170. if (c instanceof ConnectException) {
  171. throw new TransportException(uri, c.getMessage(), je);
  172. }
  173. throw new TransportException(uri, je.getMessage(), je);
  174. }
  175. }
  176. private static boolean isAuthenticationFailed(JSchException e) {
  177. return e.getCause() == null && e.getMessage().equals("Auth fail"); //$NON-NLS-1$
  178. }
  179. private static boolean isAuthenticationCanceled(JSchException e) {
  180. return e.getCause() == null && e.getMessage().equals("Auth cancel"); //$NON-NLS-1$
  181. }
  182. // Package visibility for tests
  183. Session createSession(CredentialsProvider credentialsProvider,
  184. FS fs, String user, final String pass, String host, int port,
  185. final OpenSshConfig.Host hc) throws JSchException {
  186. final Session session = createSession(hc, user, host, port, fs);
  187. // Jsch will have overridden the explicit user by the one from the SSH
  188. // config file...
  189. setUserName(session, user);
  190. // Jsch will also have overridden the port.
  191. if (port > 0 && port != session.getPort()) {
  192. session.setPort(port);
  193. }
  194. // We retry already in getSession() method. JSch must not retry
  195. // on its own.
  196. session.setConfig("MaxAuthTries", "1"); //$NON-NLS-1$ //$NON-NLS-2$
  197. if (pass != null)
  198. session.setPassword(pass);
  199. final String strictHostKeyCheckingPolicy = hc
  200. .getStrictHostKeyChecking();
  201. if (strictHostKeyCheckingPolicy != null)
  202. session.setConfig("StrictHostKeyChecking", //$NON-NLS-1$
  203. strictHostKeyCheckingPolicy);
  204. final String pauth = hc.getPreferredAuthentications();
  205. if (pauth != null)
  206. session.setConfig("PreferredAuthentications", pauth); //$NON-NLS-1$
  207. if (credentialsProvider != null
  208. && (!hc.isBatchMode() || !credentialsProvider.isInteractive())) {
  209. session.setUserInfo(new CredentialsProviderUserInfo(session,
  210. credentialsProvider));
  211. }
  212. safeConfig(session, hc.getConfig());
  213. if (hc.getConfig().getValue("HostKeyAlgorithms") == null) { //$NON-NLS-1$
  214. setPreferredKeyTypesOrder(session);
  215. }
  216. configure(hc, session);
  217. return session;
  218. }
  219. private void safeConfig(Session session, Config cfg) {
  220. // Ensure that Jsch checks all configured algorithms, not just its
  221. // built-in ones. Otherwise it may propose an algorithm for which it
  222. // doesn't have an implementation, and then run into an NPE if that
  223. // algorithm ends up being chosen.
  224. copyConfigValueToSession(session, cfg, "Ciphers", "CheckCiphers"); //$NON-NLS-1$ //$NON-NLS-2$
  225. copyConfigValueToSession(session, cfg, "KexAlgorithms", "CheckKexes"); //$NON-NLS-1$ //$NON-NLS-2$
  226. copyConfigValueToSession(session, cfg, "HostKeyAlgorithms", //$NON-NLS-1$
  227. "CheckSignatures"); //$NON-NLS-1$
  228. }
  229. private static void setPreferredKeyTypesOrder(Session session) {
  230. HostKeyRepository hkr = session.getHostKeyRepository();
  231. List<String> known = Stream.of(hkr.getHostKey(hostName(session), null))
  232. .map(HostKey::getType)
  233. .collect(toList());
  234. if (!known.isEmpty()) {
  235. String serverHostKey = "server_host_key"; //$NON-NLS-1$
  236. String current = session.getConfig(serverHostKey);
  237. if (current == null) {
  238. session.setConfig(serverHostKey, String.join(",", known)); //$NON-NLS-1$
  239. return;
  240. }
  241. String knownFirst = Stream.concat(
  242. known.stream(),
  243. Stream.of(current.split(",")) //$NON-NLS-1$
  244. .filter(s -> !known.contains(s)))
  245. .collect(joining(",")); //$NON-NLS-1$
  246. session.setConfig(serverHostKey, knownFirst);
  247. }
  248. }
  249. private static String hostName(Session s) {
  250. if (s.getPort() == SSH_PORT) {
  251. return s.getHost();
  252. }
  253. return String.format("[%s]:%d", s.getHost(), //$NON-NLS-1$
  254. Integer.valueOf(s.getPort()));
  255. }
  256. private void copyConfigValueToSession(Session session, Config cfg,
  257. String from, String to) {
  258. String value = cfg.getValue(from);
  259. if (value != null) {
  260. session.setConfig(to, value);
  261. }
  262. }
  263. private void setUserName(Session session, String userName) {
  264. // Jsch 0.1.54 picks up the user name from the ssh config, even if an
  265. // explicit user name was given! We must correct that if ~/.ssh/config
  266. // has a different user name.
  267. if (userName == null || userName.isEmpty()
  268. || userName.equals(session.getUserName())) {
  269. return;
  270. }
  271. try {
  272. Class<?>[] parameterTypes = { String.class };
  273. Method method = Session.class.getDeclaredMethod("setUserName", //$NON-NLS-1$
  274. parameterTypes);
  275. method.setAccessible(true);
  276. method.invoke(session, userName);
  277. } catch (NullPointerException | IllegalAccessException
  278. | IllegalArgumentException | InvocationTargetException
  279. | NoSuchMethodException | SecurityException e) {
  280. LOG.error(MessageFormat.format(JGitText.get().sshUserNameError,
  281. userName, session.getUserName()), e);
  282. }
  283. }
  284. /**
  285. * Create a new remote session for the requested address.
  286. *
  287. * @param hc
  288. * host configuration
  289. * @param user
  290. * login to authenticate as.
  291. * @param host
  292. * server name to connect to.
  293. * @param port
  294. * port number of the SSH daemon (typically 22).
  295. * @param fs
  296. * the file system abstraction which will be necessary to
  297. * perform certain file system operations.
  298. * @return new session instance, but otherwise unconfigured.
  299. * @throws com.jcraft.jsch.JSchException
  300. * the session could not be created.
  301. */
  302. protected Session createSession(final OpenSshConfig.Host hc,
  303. final String user, final String host, final int port, FS fs)
  304. throws JSchException {
  305. return getJSch(hc, fs).getSession(user, host, port);
  306. }
  307. /**
  308. * Provide additional configuration for the JSch instance. This method could
  309. * be overridden to supply a preferred
  310. * {@link com.jcraft.jsch.IdentityRepository}.
  311. *
  312. * @param jsch
  313. * jsch instance
  314. * @since 4.5
  315. */
  316. protected void configureJSch(JSch jsch) {
  317. // No additional configuration required.
  318. }
  319. /**
  320. * Provide additional configuration for the session based on the host
  321. * information. This method could be used to supply
  322. * {@link com.jcraft.jsch.UserInfo}.
  323. *
  324. * @param hc
  325. * host configuration
  326. * @param session
  327. * session to configure
  328. */
  329. protected abstract void configure(OpenSshConfig.Host hc, Session session);
  330. /**
  331. * Obtain the JSch used to create new sessions.
  332. *
  333. * @param hc
  334. * host configuration
  335. * @param fs
  336. * the file system abstraction which will be necessary to
  337. * perform certain file system operations.
  338. * @return the JSch instance to use.
  339. * @throws com.jcraft.jsch.JSchException
  340. * the user configuration could not be created.
  341. */
  342. protected JSch getJSch(OpenSshConfig.Host hc, FS fs) throws JSchException {
  343. if (defaultJSch == null) {
  344. defaultJSch = createDefaultJSch(fs);
  345. if (defaultJSch.getConfigRepository() == null) {
  346. defaultJSch.setConfigRepository(
  347. new JschBugFixingConfigRepository(config));
  348. }
  349. for (Object name : defaultJSch.getIdentityNames())
  350. byIdentityFile.put((String) name, defaultJSch);
  351. }
  352. final File identityFile = hc.getIdentityFile();
  353. if (identityFile == null)
  354. return defaultJSch;
  355. final String identityKey = identityFile.getAbsolutePath();
  356. JSch jsch = byIdentityFile.get(identityKey);
  357. if (jsch == null) {
  358. jsch = new JSch();
  359. configureJSch(jsch);
  360. if (jsch.getConfigRepository() == null) {
  361. jsch.setConfigRepository(defaultJSch.getConfigRepository());
  362. }
  363. jsch.setHostKeyRepository(defaultJSch.getHostKeyRepository());
  364. jsch.addIdentity(identityKey);
  365. byIdentityFile.put(identityKey, jsch);
  366. }
  367. return jsch;
  368. }
  369. /**
  370. * Create default instance of jsch
  371. *
  372. * @param fs
  373. * the file system abstraction which will be necessary to perform
  374. * certain file system operations.
  375. * @return the new default JSch implementation.
  376. * @throws com.jcraft.jsch.JSchException
  377. * known host keys cannot be loaded.
  378. */
  379. protected JSch createDefaultJSch(FS fs) throws JSchException {
  380. final JSch jsch = new JSch();
  381. JSch.setConfig("ssh-rsa", JSch.getConfig("signature.rsa")); //$NON-NLS-1$ //$NON-NLS-2$
  382. JSch.setConfig("ssh-dss", JSch.getConfig("signature.dss")); //$NON-NLS-1$ //$NON-NLS-2$
  383. configureJSch(jsch);
  384. knownHosts(jsch, fs);
  385. identities(jsch, fs);
  386. return jsch;
  387. }
  388. private static void knownHosts(JSch sch, FS fs) throws JSchException {
  389. final File home = fs.userHome();
  390. if (home == null)
  391. return;
  392. final File known_hosts = new File(new File(home, ".ssh"), "known_hosts"); //$NON-NLS-1$ //$NON-NLS-2$
  393. try (FileInputStream in = new FileInputStream(known_hosts)) {
  394. sch.setKnownHosts(in);
  395. } catch (FileNotFoundException none) {
  396. // Oh well. They don't have a known hosts in home.
  397. } catch (IOException err) {
  398. // Oh well. They don't have a known hosts in home.
  399. }
  400. }
  401. private static void identities(JSch sch, FS fs) {
  402. final File home = fs.userHome();
  403. if (home == null)
  404. return;
  405. final File sshdir = new File(home, ".ssh"); //$NON-NLS-1$
  406. if (sshdir.isDirectory()) {
  407. loadIdentity(sch, new File(sshdir, "identity")); //$NON-NLS-1$
  408. loadIdentity(sch, new File(sshdir, "id_rsa")); //$NON-NLS-1$
  409. loadIdentity(sch, new File(sshdir, "id_dsa")); //$NON-NLS-1$
  410. }
  411. }
  412. private static void loadIdentity(JSch sch, File priv) {
  413. if (priv.isFile()) {
  414. try {
  415. sch.addIdentity(priv.getAbsolutePath());
  416. } catch (JSchException e) {
  417. // Instead, pretend the key doesn't exist.
  418. }
  419. }
  420. }
  421. private static class JschBugFixingConfigRepository
  422. implements ConfigRepository {
  423. private final ConfigRepository base;
  424. public JschBugFixingConfigRepository(ConfigRepository base) {
  425. this.base = base;
  426. }
  427. @Override
  428. public Config getConfig(String host) {
  429. return new JschBugFixingConfig(base.getConfig(host));
  430. }
  431. /**
  432. * A {@link com.jcraft.jsch.ConfigRepository.Config} that transforms
  433. * some values from the config file into the format Jsch 0.1.54 expects.
  434. * This is a work-around for bugs in Jsch.
  435. * <p>
  436. * Additionally, this config hides the IdentityFile config entries from
  437. * Jsch; we manage those ourselves. Otherwise Jsch would cache passwords
  438. * (or rather, decrypted keys) only for a single session, resulting in
  439. * multiple password prompts for user operations that use several Jsch
  440. * sessions.
  441. */
  442. private static class JschBugFixingConfig implements Config {
  443. private static final String[] NO_IDENTITIES = {};
  444. private final Config real;
  445. public JschBugFixingConfig(Config delegate) {
  446. real = delegate;
  447. }
  448. @Override
  449. public String getHostname() {
  450. return real.getHostname();
  451. }
  452. @Override
  453. public String getUser() {
  454. return real.getUser();
  455. }
  456. @Override
  457. public int getPort() {
  458. return real.getPort();
  459. }
  460. @Override
  461. public String getValue(String key) {
  462. String k = key.toUpperCase(Locale.ROOT);
  463. if ("IDENTITYFILE".equals(k)) { //$NON-NLS-1$
  464. return null;
  465. }
  466. String result = real.getValue(key);
  467. if (result != null) {
  468. if ("SERVERALIVEINTERVAL".equals(k) //$NON-NLS-1$
  469. || "CONNECTTIMEOUT".equals(k)) { //$NON-NLS-1$
  470. // These values are in seconds. Jsch 0.1.54 passes them
  471. // on as is to java.net.Socket.setSoTimeout(), which
  472. // expects milliseconds. So convert here to
  473. // milliseconds.
  474. try {
  475. int timeout = Integer.parseInt(result);
  476. result = Long.toString(
  477. TimeUnit.SECONDS.toMillis(timeout));
  478. } catch (NumberFormatException e) {
  479. // Ignore
  480. }
  481. }
  482. }
  483. return result;
  484. }
  485. @Override
  486. public String[] getValues(String key) {
  487. String k = key.toUpperCase(Locale.ROOT);
  488. if ("IDENTITYFILE".equals(k)) { //$NON-NLS-1$
  489. return NO_IDENTITIES;
  490. }
  491. return real.getValues(key);
  492. }
  493. }
  494. }
  495. /**
  496. * Set the {@link OpenSshConfig} to use. Intended for use in tests.
  497. *
  498. * @param config
  499. * to use
  500. */
  501. void setConfig(OpenSshConfig config) {
  502. this.config = config;
  503. }
  504. }