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.

OpenSshConfig.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /*
  2. * Copyright (C) 2008, 2014, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.FileInputStream;
  47. import java.io.FileNotFoundException;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.io.InputStreamReader;
  51. import java.security.AccessController;
  52. import java.security.PrivilegedAction;
  53. import java.util.ArrayList;
  54. import java.util.Collections;
  55. import java.util.LinkedHashMap;
  56. import java.util.List;
  57. import java.util.Map;
  58. import org.eclipse.jgit.errors.InvalidPatternException;
  59. import org.eclipse.jgit.fnmatch.FileNameMatcher;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.util.FS;
  62. import org.eclipse.jgit.util.StringUtils;
  63. /**
  64. * Simple configuration parser for the OpenSSH ~/.ssh/config file.
  65. * <p>
  66. * Since JSch does not (currently) have the ability to parse an OpenSSH
  67. * configuration file this is a simple parser to read that file and make the
  68. * critical options available to {@link SshSessionFactory}.
  69. */
  70. public class OpenSshConfig {
  71. /** IANA assigned port number for SSH. */
  72. static final int SSH_PORT = 22;
  73. /**
  74. * Obtain the user's configuration data.
  75. * <p>
  76. * The configuration file is always returned to the caller, even if no file
  77. * exists in the user's home directory at the time the call was made. Lookup
  78. * requests are cached and are automatically updated if the user modifies
  79. * the configuration file since the last time it was cached.
  80. *
  81. * @param fs
  82. * the file system abstraction which will be necessary to
  83. * perform certain file system operations.
  84. * @return a caching reader of the user's configuration file.
  85. */
  86. public static OpenSshConfig get(FS fs) {
  87. File home = fs.userHome();
  88. if (home == null)
  89. home = new File(".").getAbsoluteFile(); //$NON-NLS-1$
  90. final File config = new File(new File(home, ".ssh"), Constants.CONFIG); //$NON-NLS-1$
  91. final OpenSshConfig osc = new OpenSshConfig(home, config);
  92. osc.refresh();
  93. return osc;
  94. }
  95. /** The user's home directory, as key files may be relative to here. */
  96. private final File home;
  97. /** The .ssh/config file we read and monitor for updates. */
  98. private final File configFile;
  99. /** Modification time of {@link #configFile} when {@link #hosts} loaded. */
  100. private long lastModified;
  101. /** Cached entries read out of the configuration file. */
  102. private Map<String, Host> hosts;
  103. OpenSshConfig(final File h, final File cfg) {
  104. home = h;
  105. configFile = cfg;
  106. hosts = Collections.emptyMap();
  107. }
  108. /**
  109. * Locate the configuration for a specific host request.
  110. *
  111. * @param hostName
  112. * the name the user has supplied to the SSH tool. This may be a
  113. * real host name, or it may just be a "Host" block in the
  114. * configuration file.
  115. * @return r configuration for the requested name. Never null.
  116. */
  117. public Host lookup(final String hostName) {
  118. final Map<String, Host> cache = refresh();
  119. Host h = cache.get(hostName);
  120. if (h == null)
  121. h = new Host();
  122. if (h.patternsApplied)
  123. return h;
  124. for (final Map.Entry<String, Host> e : cache.entrySet()) {
  125. if (!isHostPattern(e.getKey()))
  126. continue;
  127. if (!isHostMatch(e.getKey(), hostName))
  128. continue;
  129. h.copyFrom(e.getValue());
  130. }
  131. if (h.hostName == null)
  132. h.hostName = hostName;
  133. if (h.user == null)
  134. h.user = OpenSshConfig.userName();
  135. if (h.port == 0)
  136. h.port = OpenSshConfig.SSH_PORT;
  137. if (h.connectionAttempts == 0)
  138. h.connectionAttempts = 1;
  139. h.patternsApplied = true;
  140. return h;
  141. }
  142. private synchronized Map<String, Host> refresh() {
  143. final long mtime = configFile.lastModified();
  144. if (mtime != lastModified) {
  145. try {
  146. final FileInputStream in = new FileInputStream(configFile);
  147. try {
  148. hosts = parse(in);
  149. } finally {
  150. in.close();
  151. }
  152. } catch (FileNotFoundException none) {
  153. hosts = Collections.emptyMap();
  154. } catch (IOException err) {
  155. hosts = Collections.emptyMap();
  156. }
  157. lastModified = mtime;
  158. }
  159. return hosts;
  160. }
  161. private Map<String, Host> parse(final InputStream in) throws IOException {
  162. final Map<String, Host> m = new LinkedHashMap<String, Host>();
  163. final BufferedReader br = new BufferedReader(new InputStreamReader(in));
  164. final List<Host> current = new ArrayList<Host>(4);
  165. String line;
  166. while ((line = br.readLine()) != null) {
  167. line = line.trim();
  168. if (line.length() == 0 || line.startsWith("#")) //$NON-NLS-1$
  169. continue;
  170. final String[] parts = line.split("[ \t]*[= \t]", 2); //$NON-NLS-1$
  171. final String keyword = parts[0].trim();
  172. final String argValue = parts[1].trim();
  173. if (StringUtils.equalsIgnoreCase("Host", keyword)) { //$NON-NLS-1$
  174. current.clear();
  175. for (final String pattern : argValue.split("[ \t]")) { //$NON-NLS-1$
  176. final String name = dequote(pattern);
  177. Host c = m.get(name);
  178. if (c == null) {
  179. c = new Host();
  180. m.put(name, c);
  181. }
  182. current.add(c);
  183. }
  184. continue;
  185. }
  186. if (current.isEmpty()) {
  187. // We received an option outside of a Host block. We
  188. // don't know who this should match against, so skip.
  189. //
  190. continue;
  191. }
  192. if (StringUtils.equalsIgnoreCase("HostName", keyword)) { //$NON-NLS-1$
  193. for (final Host c : current)
  194. if (c.hostName == null)
  195. c.hostName = dequote(argValue);
  196. } else if (StringUtils.equalsIgnoreCase("User", keyword)) { //$NON-NLS-1$
  197. for (final Host c : current)
  198. if (c.user == null)
  199. c.user = dequote(argValue);
  200. } else if (StringUtils.equalsIgnoreCase("Port", keyword)) { //$NON-NLS-1$
  201. try {
  202. final int port = Integer.parseInt(dequote(argValue));
  203. for (final Host c : current)
  204. if (c.port == 0)
  205. c.port = port;
  206. } catch (NumberFormatException nfe) {
  207. // Bad port number. Don't set it.
  208. }
  209. } else if (StringUtils.equalsIgnoreCase("IdentityFile", keyword)) { //$NON-NLS-1$
  210. for (final Host c : current)
  211. if (c.identityFile == null)
  212. c.identityFile = toFile(dequote(argValue));
  213. } else if (StringUtils.equalsIgnoreCase(
  214. "PreferredAuthentications", keyword)) { //$NON-NLS-1$
  215. for (final Host c : current)
  216. if (c.preferredAuthentications == null)
  217. c.preferredAuthentications = nows(dequote(argValue));
  218. } else if (StringUtils.equalsIgnoreCase("BatchMode", keyword)) { //$NON-NLS-1$
  219. for (final Host c : current)
  220. if (c.batchMode == null)
  221. c.batchMode = yesno(dequote(argValue));
  222. } else if (StringUtils.equalsIgnoreCase(
  223. "StrictHostKeyChecking", keyword)) { //$NON-NLS-1$
  224. String value = dequote(argValue);
  225. for (final Host c : current)
  226. if (c.strictHostKeyChecking == null)
  227. c.strictHostKeyChecking = value;
  228. } else if (StringUtils.equalsIgnoreCase(
  229. "ConnectionAttempts", keyword)) { //$NON-NLS-1$
  230. try {
  231. final int connectionAttempts = Integer.parseInt(dequote(argValue));
  232. if (connectionAttempts > 0) {
  233. for (final Host c : current)
  234. if (c.connectionAttempts == 0)
  235. c.connectionAttempts = connectionAttempts;
  236. }
  237. } catch (NumberFormatException nfe) {
  238. // ignore bad values
  239. }
  240. }
  241. }
  242. return m;
  243. }
  244. private static boolean isHostPattern(final String s) {
  245. return s.indexOf('*') >= 0 || s.indexOf('?') >= 0;
  246. }
  247. private static boolean isHostMatch(final String pattern, final String name) {
  248. final FileNameMatcher fn;
  249. try {
  250. fn = new FileNameMatcher(pattern, null);
  251. } catch (InvalidPatternException e) {
  252. return false;
  253. }
  254. fn.append(name);
  255. return fn.isMatch();
  256. }
  257. private static String dequote(final String value) {
  258. if (value.startsWith("\"") && value.endsWith("\"")) //$NON-NLS-1$ //$NON-NLS-2$
  259. return value.substring(1, value.length() - 1);
  260. return value;
  261. }
  262. private static String nows(final String value) {
  263. final StringBuilder b = new StringBuilder();
  264. for (int i = 0; i < value.length(); i++) {
  265. if (!Character.isSpaceChar(value.charAt(i)))
  266. b.append(value.charAt(i));
  267. }
  268. return b.toString();
  269. }
  270. private static Boolean yesno(final String value) {
  271. if (StringUtils.equalsIgnoreCase("yes", value)) //$NON-NLS-1$
  272. return Boolean.TRUE;
  273. return Boolean.FALSE;
  274. }
  275. private File toFile(final String path) {
  276. if (path.startsWith("~/")) //$NON-NLS-1$
  277. return new File(home, path.substring(2));
  278. File ret = new File(path);
  279. if (ret.isAbsolute())
  280. return ret;
  281. return new File(home, path);
  282. }
  283. static String userName() {
  284. return AccessController.doPrivileged(new PrivilegedAction<String>() {
  285. public String run() {
  286. return System.getProperty("user.name"); //$NON-NLS-1$
  287. }
  288. });
  289. }
  290. /**
  291. * Configuration of one "Host" block in the configuration file.
  292. * <p>
  293. * If returned from {@link OpenSshConfig#lookup(String)} some or all of the
  294. * properties may not be populated. The properties which are not populated
  295. * should be defaulted by the caller.
  296. * <p>
  297. * When returned from {@link OpenSshConfig#lookup(String)} any wildcard
  298. * entries which appear later in the configuration file will have been
  299. * already merged into this block.
  300. */
  301. public static class Host {
  302. boolean patternsApplied;
  303. String hostName;
  304. int port;
  305. File identityFile;
  306. String user;
  307. String preferredAuthentications;
  308. Boolean batchMode;
  309. String strictHostKeyChecking;
  310. int connectionAttempts;
  311. void copyFrom(final Host src) {
  312. if (hostName == null)
  313. hostName = src.hostName;
  314. if (port == 0)
  315. port = src.port;
  316. if (identityFile == null)
  317. identityFile = src.identityFile;
  318. if (user == null)
  319. user = src.user;
  320. if (preferredAuthentications == null)
  321. preferredAuthentications = src.preferredAuthentications;
  322. if (batchMode == null)
  323. batchMode = src.batchMode;
  324. if (strictHostKeyChecking == null)
  325. strictHostKeyChecking = src.strictHostKeyChecking;
  326. if (connectionAttempts == 0)
  327. connectionAttempts = src.connectionAttempts;
  328. }
  329. /**
  330. * @return the value StrictHostKeyChecking property, the valid values
  331. * are "yes" (unknown hosts are not accepted), "no" (unknown
  332. * hosts are always accepted), and "ask" (user should be asked
  333. * before accepting the host)
  334. */
  335. public String getStrictHostKeyChecking() {
  336. return strictHostKeyChecking;
  337. }
  338. /**
  339. * @return the real IP address or host name to connect to; never null.
  340. */
  341. public String getHostName() {
  342. return hostName;
  343. }
  344. /**
  345. * @return the real port number to connect to; never 0.
  346. */
  347. public int getPort() {
  348. return port;
  349. }
  350. /**
  351. * @return path of the private key file to use for authentication; null
  352. * if the caller should use default authentication strategies.
  353. */
  354. public File getIdentityFile() {
  355. return identityFile;
  356. }
  357. /**
  358. * @return the real user name to connect as; never null.
  359. */
  360. public String getUser() {
  361. return user;
  362. }
  363. /**
  364. * @return the preferred authentication methods, separated by commas if
  365. * more than one authentication method is preferred.
  366. */
  367. public String getPreferredAuthentications() {
  368. return preferredAuthentications;
  369. }
  370. /**
  371. * @return true if batch (non-interactive) mode is preferred for this
  372. * host connection.
  373. */
  374. public boolean isBatchMode() {
  375. return batchMode != null && batchMode.booleanValue();
  376. }
  377. /**
  378. * @return the number of tries (one per second) to connect before
  379. * exiting. The argument must be an integer. This may be useful
  380. * in scripts if the connection sometimes fails. The default is
  381. * 1.
  382. * @since 3.4
  383. */
  384. public int getConnectionAttempts() {
  385. return connectionAttempts;
  386. }
  387. }
  388. }