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

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