Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

OpenSshConfig.java 12KB

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