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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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.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();
  90. final File config = new File(new File(home, ".ssh"), Constants.CONFIG);
  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. h.patternsApplied = true;
  138. return h;
  139. }
  140. private synchronized Map<String, Host> refresh() {
  141. final long mtime = configFile.lastModified();
  142. if (mtime != lastModified) {
  143. try {
  144. final FileInputStream in = new FileInputStream(configFile);
  145. try {
  146. hosts = parse(in);
  147. } finally {
  148. in.close();
  149. }
  150. } catch (FileNotFoundException none) {
  151. hosts = Collections.emptyMap();
  152. } catch (IOException err) {
  153. hosts = Collections.emptyMap();
  154. }
  155. lastModified = mtime;
  156. }
  157. return hosts;
  158. }
  159. private Map<String, Host> parse(final InputStream in) throws IOException {
  160. final Map<String, Host> m = new LinkedHashMap<String, Host>();
  161. final BufferedReader br = new BufferedReader(new InputStreamReader(in));
  162. final List<Host> current = new ArrayList<Host>(4);
  163. String line;
  164. while ((line = br.readLine()) != null) {
  165. line = line.trim();
  166. if (line.length() == 0 || line.startsWith("#"))
  167. continue;
  168. final String[] parts = line.split("[ \t]*[= \t]", 2);
  169. final String keyword = parts[0].trim();
  170. final String argValue = parts[1].trim();
  171. if (StringUtils.equalsIgnoreCase("Host", keyword)) {
  172. current.clear();
  173. for (final String pattern : argValue.split("[ \t]")) {
  174. final String name = dequote(pattern);
  175. Host c = m.get(name);
  176. if (c == null) {
  177. c = new Host();
  178. m.put(name, c);
  179. }
  180. current.add(c);
  181. }
  182. continue;
  183. }
  184. if (current.isEmpty()) {
  185. // We received an option outside of a Host block. We
  186. // don't know who this should match against, so skip.
  187. //
  188. continue;
  189. }
  190. if (StringUtils.equalsIgnoreCase("HostName", keyword)) {
  191. for (final Host c : current)
  192. if (c.hostName == null)
  193. c.hostName = dequote(argValue);
  194. } else if (StringUtils.equalsIgnoreCase("User", keyword)) {
  195. for (final Host c : current)
  196. if (c.user == null)
  197. c.user = dequote(argValue);
  198. } else if (StringUtils.equalsIgnoreCase("Port", keyword)) {
  199. try {
  200. final int port = Integer.parseInt(dequote(argValue));
  201. for (final Host c : current)
  202. if (c.port == 0)
  203. c.port = port;
  204. } catch (NumberFormatException nfe) {
  205. // Bad port number. Don't set it.
  206. }
  207. } else if (StringUtils.equalsIgnoreCase("IdentityFile", keyword)) {
  208. for (final Host c : current)
  209. if (c.identityFile == null)
  210. c.identityFile = toFile(dequote(argValue));
  211. } else if (StringUtils.equalsIgnoreCase("PreferredAuthentications", keyword)) {
  212. for (final Host c : current)
  213. if (c.preferredAuthentications == null)
  214. c.preferredAuthentications = nows(dequote(argValue));
  215. } else if (StringUtils.equalsIgnoreCase("BatchMode", keyword)) {
  216. for (final Host c : current)
  217. if (c.batchMode == null)
  218. c.batchMode = yesno(dequote(argValue));
  219. } else if (StringUtils.equalsIgnoreCase("StrictHostKeyChecking", keyword)) {
  220. String value = dequote(argValue);
  221. for (final Host c : current)
  222. if (c.strictHostKeyChecking == null)
  223. c.strictHostKeyChecking = value;
  224. }
  225. }
  226. return m;
  227. }
  228. private static boolean isHostPattern(final String s) {
  229. return s.indexOf('*') >= 0 || s.indexOf('?') >= 0;
  230. }
  231. private static boolean isHostMatch(final String pattern, final String name) {
  232. final FileNameMatcher fn;
  233. try {
  234. fn = new FileNameMatcher(pattern, null);
  235. } catch (InvalidPatternException e) {
  236. return false;
  237. }
  238. fn.append(name);
  239. return fn.isMatch();
  240. }
  241. private static String dequote(final String value) {
  242. if (value.startsWith("\"") && value.endsWith("\""))
  243. return value.substring(1, value.length() - 1);
  244. return value;
  245. }
  246. private static String nows(final String value) {
  247. final StringBuilder b = new StringBuilder();
  248. for (int i = 0; i < value.length(); i++) {
  249. if (!Character.isSpaceChar(value.charAt(i)))
  250. b.append(value.charAt(i));
  251. }
  252. return b.toString();
  253. }
  254. private static Boolean yesno(final String value) {
  255. if (StringUtils.equalsIgnoreCase("yes", value))
  256. return Boolean.TRUE;
  257. return Boolean.FALSE;
  258. }
  259. private File toFile(final String path) {
  260. if (path.startsWith("~/"))
  261. return new File(home, path.substring(2));
  262. File ret = new File(path);
  263. if (ret.isAbsolute())
  264. return ret;
  265. return new File(home, path);
  266. }
  267. static String userName() {
  268. return AccessController.doPrivileged(new PrivilegedAction<String>() {
  269. public String run() {
  270. return System.getProperty("user.name");
  271. }
  272. });
  273. }
  274. /**
  275. * Configuration of one "Host" block in the configuration file.
  276. * <p>
  277. * If returned from {@link OpenSshConfig#lookup(String)} some or all of the
  278. * properties may not be populated. The properties which are not populated
  279. * should be defaulted by the caller.
  280. * <p>
  281. * When returned from {@link OpenSshConfig#lookup(String)} any wildcard
  282. * entries which appear later in the configuration file will have been
  283. * already merged into this block.
  284. */
  285. public static class Host {
  286. boolean patternsApplied;
  287. String hostName;
  288. int port;
  289. File identityFile;
  290. String user;
  291. String preferredAuthentications;
  292. Boolean batchMode;
  293. String strictHostKeyChecking;
  294. void copyFrom(final Host src) {
  295. if (hostName == null)
  296. hostName = src.hostName;
  297. if (port == 0)
  298. port = src.port;
  299. if (identityFile == null)
  300. identityFile = src.identityFile;
  301. if (user == null)
  302. user = src.user;
  303. if (preferredAuthentications == null)
  304. preferredAuthentications = src.preferredAuthentications;
  305. if (batchMode == null)
  306. batchMode = src.batchMode;
  307. if (strictHostKeyChecking == null)
  308. strictHostKeyChecking = src.strictHostKeyChecking;
  309. }
  310. /**
  311. * @return the value StrictHostKeyChecking property, the valid values
  312. * are "yes" (unknown hosts are not accepted), "no" (unknown
  313. * hosts are always accepted), and "ask" (user should be asked
  314. * before accepting the host)
  315. */
  316. public String getStrictHostKeyChecking() {
  317. return strictHostKeyChecking;
  318. }
  319. /**
  320. * @return the real IP address or host name to connect to; never null.
  321. */
  322. public String getHostName() {
  323. return hostName;
  324. }
  325. /**
  326. * @return the real port number to connect to; never 0.
  327. */
  328. public int getPort() {
  329. return port;
  330. }
  331. /**
  332. * @return path of the private key file to use for authentication; null
  333. * if the caller should use default authentication strategies.
  334. */
  335. public File getIdentityFile() {
  336. return identityFile;
  337. }
  338. /**
  339. * @return the real user name to connect as; never null.
  340. */
  341. public String getUser() {
  342. return user;
  343. }
  344. /**
  345. * @return the preferred authentication methods, separated by commas if
  346. * more than one authentication method is preferred.
  347. */
  348. public String getPreferredAuthentications() {
  349. return preferredAuthentications;
  350. }
  351. /**
  352. * @return true if batch (non-interactive) mode is preferred for this
  353. * host connection.
  354. */
  355. public boolean isBatchMode() {
  356. return batchMode != null && batchMode.booleanValue();
  357. }
  358. }
  359. }