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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /*
  2. * Copyright (C) 2008-2009, 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.util.FS;
  61. import org.eclipse.jgit.util.StringUtils;
  62. /**
  63. * Simple configuration parser for the OpenSSH ~/.ssh/config file.
  64. * <p>
  65. * Since JSch does not (currently) have the ability to parse an OpenSSH
  66. * configuration file this is a simple parser to read that file and make the
  67. * critical options available to {@link SshSessionFactory}.
  68. */
  69. public class OpenSshConfig {
  70. /** IANA assigned port number for SSH. */
  71. static final int SSH_PORT = 22;
  72. /**
  73. * Obtain the user's configuration data.
  74. * <p>
  75. * The configuration file is always returned to the caller, even if no file
  76. * exists in the user's home directory at the time the call was made. Lookup
  77. * requests are cached and are automatically updated if the user modifies
  78. * the configuration file since the last time it was cached.
  79. *
  80. * @param fs
  81. * the file system abstraction which will be necessary to
  82. * perform certain file system operations.
  83. * @return a caching reader of the user's configuration file.
  84. */
  85. public static OpenSshConfig get(FS fs) {
  86. File home = fs.userHome();
  87. if (home == null)
  88. home = new File(".").getAbsoluteFile();
  89. final File config = new File(new File(home, ".ssh"), "config");
  90. final OpenSshConfig osc = new OpenSshConfig(home, config);
  91. osc.refresh();
  92. return osc;
  93. }
  94. /** The user's home directory, as key files may be relative to here. */
  95. private final File home;
  96. /** The .ssh/config file we read and monitor for updates. */
  97. private final File configFile;
  98. /** Modification time of {@link #configFile} when {@link #hosts} loaded. */
  99. private long lastModified;
  100. /** Cached entries read out of the configuration file. */
  101. private Map<String, Host> hosts;
  102. OpenSshConfig(final File h, final File cfg) {
  103. home = h;
  104. configFile = cfg;
  105. hosts = Collections.emptyMap();
  106. }
  107. /**
  108. * Locate the configuration for a specific host request.
  109. *
  110. * @param hostName
  111. * the name the user has supplied to the SSH tool. This may be a
  112. * real host name, or it may just be a "Host" block in the
  113. * configuration file.
  114. * @return r configuration for the requested name. Never null.
  115. */
  116. public Host lookup(final String hostName) {
  117. final Map<String, Host> cache = refresh();
  118. Host h = cache.get(hostName);
  119. if (h == null)
  120. h = new Host();
  121. if (h.patternsApplied)
  122. return h;
  123. for (final Map.Entry<String, Host> e : cache.entrySet()) {
  124. if (!isHostPattern(e.getKey()))
  125. continue;
  126. if (!isHostMatch(e.getKey(), hostName))
  127. continue;
  128. h.copyFrom(e.getValue());
  129. }
  130. if (h.hostName == null)
  131. h.hostName = hostName;
  132. if (h.user == null)
  133. h.user = OpenSshConfig.userName();
  134. if (h.port == 0)
  135. h.port = OpenSshConfig.SSH_PORT;
  136. h.patternsApplied = true;
  137. return h;
  138. }
  139. private synchronized Map<String, Host> refresh() {
  140. final long mtime = configFile.lastModified();
  141. if (mtime != lastModified) {
  142. try {
  143. final FileInputStream in = new FileInputStream(configFile);
  144. try {
  145. hosts = parse(in);
  146. } finally {
  147. in.close();
  148. }
  149. } catch (FileNotFoundException none) {
  150. hosts = Collections.emptyMap();
  151. } catch (IOException err) {
  152. hosts = Collections.emptyMap();
  153. }
  154. lastModified = mtime;
  155. }
  156. return hosts;
  157. }
  158. private Map<String, Host> parse(final InputStream in) throws IOException {
  159. final Map<String, Host> m = new LinkedHashMap<String, Host>();
  160. final BufferedReader br = new BufferedReader(new InputStreamReader(in));
  161. final List<Host> current = new ArrayList<Host>(4);
  162. String line;
  163. while ((line = br.readLine()) != null) {
  164. line = line.trim();
  165. if (line.length() == 0 || line.startsWith("#"))
  166. continue;
  167. final String[] parts = line.split("[ \t]*[= \t]", 2);
  168. final String keyword = parts[0].trim();
  169. final String argValue = parts[1].trim();
  170. if (StringUtils.equalsIgnoreCase("Host", keyword)) {
  171. current.clear();
  172. for (final String pattern : argValue.split("[ \t]")) {
  173. final String name = dequote(pattern);
  174. Host c = m.get(name);
  175. if (c == null) {
  176. c = new Host();
  177. m.put(name, c);
  178. }
  179. current.add(c);
  180. }
  181. continue;
  182. }
  183. if (current.isEmpty()) {
  184. // We received an option outside of a Host block. We
  185. // don't know who this should match against, so skip.
  186. //
  187. continue;
  188. }
  189. if (StringUtils.equalsIgnoreCase("HostName", keyword)) {
  190. for (final Host c : current)
  191. if (c.hostName == null)
  192. c.hostName = dequote(argValue);
  193. } else if (StringUtils.equalsIgnoreCase("User", keyword)) {
  194. for (final Host c : current)
  195. if (c.user == null)
  196. c.user = dequote(argValue);
  197. } else if (StringUtils.equalsIgnoreCase("Port", keyword)) {
  198. try {
  199. final int port = Integer.parseInt(dequote(argValue));
  200. for (final Host c : current)
  201. if (c.port == 0)
  202. c.port = port;
  203. } catch (NumberFormatException nfe) {
  204. // Bad port number. Don't set it.
  205. }
  206. } else if (StringUtils.equalsIgnoreCase("IdentityFile", keyword)) {
  207. for (final Host c : current)
  208. if (c.identityFile == null)
  209. c.identityFile = toFile(dequote(argValue));
  210. } else if (StringUtils.equalsIgnoreCase("PreferredAuthentications", keyword)) {
  211. for (final Host c : current)
  212. if (c.preferredAuthentications == null)
  213. c.preferredAuthentications = nows(dequote(argValue));
  214. } else if (StringUtils.equalsIgnoreCase("BatchMode", keyword)) {
  215. for (final Host c : current)
  216. if (c.batchMode == null)
  217. c.batchMode = yesno(dequote(argValue));
  218. } else if (StringUtils.equalsIgnoreCase("StrictHostKeyChecking", keyword)) {
  219. String value = dequote(argValue);
  220. for (final Host c : current)
  221. if (c.strictHostKeyChecking == null)
  222. c.strictHostKeyChecking = value;
  223. }
  224. }
  225. return m;
  226. }
  227. private static boolean isHostPattern(final String s) {
  228. return s.indexOf('*') >= 0 || s.indexOf('?') >= 0;
  229. }
  230. private static boolean isHostMatch(final String pattern, final String name) {
  231. final FileNameMatcher fn;
  232. try {
  233. fn = new FileNameMatcher(pattern, null);
  234. } catch (InvalidPatternException e) {
  235. return false;
  236. }
  237. fn.append(name);
  238. return fn.isMatch();
  239. }
  240. private static String dequote(final String value) {
  241. if (value.startsWith("\"") && value.endsWith("\""))
  242. return value.substring(1, value.length() - 1);
  243. return value;
  244. }
  245. private static String nows(final String value) {
  246. final StringBuilder b = new StringBuilder();
  247. for (int i = 0; i < value.length(); i++) {
  248. if (!Character.isSpaceChar(value.charAt(i)))
  249. b.append(value.charAt(i));
  250. }
  251. return b.toString();
  252. }
  253. private static Boolean yesno(final String value) {
  254. if (StringUtils.equalsIgnoreCase("yes", value))
  255. return Boolean.TRUE;
  256. return Boolean.FALSE;
  257. }
  258. private File toFile(final String path) {
  259. if (path.startsWith("~/"))
  260. return new File(home, path.substring(2));
  261. File ret = new File(path);
  262. if (ret.isAbsolute())
  263. return ret;
  264. return new File(home, path);
  265. }
  266. static String userName() {
  267. return AccessController.doPrivileged(new PrivilegedAction<String>() {
  268. public String run() {
  269. return System.getProperty("user.name");
  270. }
  271. });
  272. }
  273. /**
  274. * Configuration of one "Host" block in the configuration file.
  275. * <p>
  276. * If returned from {@link OpenSshConfig#lookup(String)} some or all of the
  277. * properties may not be populated. The properties which are not populated
  278. * should be defaulted by the caller.
  279. * <p>
  280. * When returned from {@link OpenSshConfig#lookup(String)} any wildcard
  281. * entries which appear later in the configuration file will have been
  282. * already merged into this block.
  283. */
  284. public static class Host {
  285. boolean patternsApplied;
  286. String hostName;
  287. int port;
  288. File identityFile;
  289. String user;
  290. String preferredAuthentications;
  291. Boolean batchMode;
  292. String strictHostKeyChecking;
  293. void copyFrom(final Host src) {
  294. if (hostName == null)
  295. hostName = src.hostName;
  296. if (port == 0)
  297. port = src.port;
  298. if (identityFile == null)
  299. identityFile = src.identityFile;
  300. if (user == null)
  301. user = src.user;
  302. if (preferredAuthentications == null)
  303. preferredAuthentications = src.preferredAuthentications;
  304. if (batchMode == null)
  305. batchMode = src.batchMode;
  306. if (strictHostKeyChecking == null)
  307. strictHostKeyChecking = src.strictHostKeyChecking;
  308. }
  309. /**
  310. * @return the value StrictHostKeyChecking property, the valid values
  311. * are "yes" (unknown hosts are not accepted), "no" (unknown
  312. * hosts are always accepted), and "ask" (user should be asked
  313. * before accepting the host)
  314. */
  315. public String getStrictHostKeyChecking() {
  316. return strictHostKeyChecking;
  317. }
  318. /**
  319. * @return the real IP address or host name to connect to; never null.
  320. */
  321. public String getHostName() {
  322. return hostName;
  323. }
  324. /**
  325. * @return the real port number to connect to; never 0.
  326. */
  327. public int getPort() {
  328. return port;
  329. }
  330. /**
  331. * @return path of the private key file to use for authentication; null
  332. * if the caller should use default authentication strategies.
  333. */
  334. public File getIdentityFile() {
  335. return identityFile;
  336. }
  337. /**
  338. * @return the real user name to connect as; never null.
  339. */
  340. public String getUser() {
  341. return user;
  342. }
  343. /**
  344. * @return the preferred authentication methods, separated by commas if
  345. * more than one authentication method is preferred.
  346. */
  347. public String getPreferredAuthentications() {
  348. return preferredAuthentications;
  349. }
  350. /**
  351. * @return true if batch (non-interactive) mode is preferred for this
  352. * host connection.
  353. */
  354. public boolean isBatchMode() {
  355. return batchMode != null && batchMode.booleanValue();
  356. }
  357. }
  358. }