View Javadoc
1   /*
2    * Copyright (C) 2008, 2018, 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  
44  package org.eclipse.jgit.transport;
45  
46  import static org.eclipse.jgit.internal.transport.ssh.OpenSshConfigFile.positive;
47  
48  import java.io.File;
49  import java.util.List;
50  import java.util.Map;
51  import java.util.TreeMap;
52  
53  import org.eclipse.jgit.internal.transport.ssh.OpenSshConfigFile;
54  import org.eclipse.jgit.internal.transport.ssh.OpenSshConfigFile.HostEntry;
55  import org.eclipse.jgit.util.FS;
56  
57  import com.jcraft.jsch.ConfigRepository;
58  
59  /**
60   * Fairly complete configuration parser for the OpenSSH ~/.ssh/config file.
61   * <p>
62   * JSch does have its own config file parser
63   * {@link com.jcraft.jsch.OpenSSHConfig} since version 0.1.50, but it has a
64   * number of problems:
65   * <ul>
66   * <li>it splits lines of the format "keyword = value" wrongly: you'd end up
67   * with the value "= value".
68   * <li>its "Host" keyword is not case insensitive.
69   * <li>it doesn't handle quoted values.
70   * <li>JSch's OpenSSHConfig doesn't monitor for config file changes.
71   * </ul>
72   * <p>
73   * This parser makes the critical options available to
74   * {@link org.eclipse.jgit.transport.SshSessionFactory} via
75   * {@link org.eclipse.jgit.transport.OpenSshConfig.Host} objects returned by
76   * {@link #lookup(String)}, and implements a fully conforming
77   * {@link com.jcraft.jsch.ConfigRepository} providing
78   * {@link com.jcraft.jsch.ConfigRepository.Config}s via
79   * {@link #getConfig(String)}.
80   * </p>
81   *
82   * @see OpenSshConfigFile
83   */
84  public class OpenSshConfig implements ConfigRepository {
85  
86  	/**
87  	 * Obtain the user's configuration data.
88  	 * <p>
89  	 * The configuration file is always returned to the caller, even if no file
90  	 * exists in the user's home directory at the time the call was made. Lookup
91  	 * requests are cached and are automatically updated if the user modifies
92  	 * the configuration file since the last time it was cached.
93  	 *
94  	 * @param fs
95  	 *            the file system abstraction which will be necessary to
96  	 *            perform certain file system operations.
97  	 * @return a caching reader of the user's configuration file.
98  	 */
99  	public static OpenSshConfig get(FS fs) {
100 		File home = fs.userHome();
101 		if (home == null)
102 			home = new File(".").getAbsoluteFile(); //$NON-NLS-1$
103 
104 		final File config = new File(new File(home, SshConstants.SSH_DIR),
105 				SshConstants.CONFIG);
106 		return new OpenSshConfig(home, config);
107 	}
108 
109 	/** The base file. */
110 	private OpenSshConfigFile configFile;
111 
112 	OpenSshConfig(File h, File cfg) {
113 		configFile = new OpenSshConfigFile(h, cfg,
114 				SshSessionFactory.getLocalUserName());
115 	}
116 
117 	/**
118 	 * Locate the configuration for a specific host request.
119 	 *
120 	 * @param hostName
121 	 *            the name the user has supplied to the SSH tool. This may be a
122 	 *            real host name, or it may just be a "Host" block in the
123 	 *            configuration file.
124 	 * @return r configuration for the requested name. Never null.
125 	 */
126 	public Host lookup(String hostName) {
127 		HostEntry entry = configFile.lookup(hostName, -1, null);
128 		return new Host(entry, hostName, configFile.getLocalUserName());
129 	}
130 
131 	/**
132 	 * Configuration of one "Host" block in the configuration file.
133 	 * <p>
134 	 * If returned from {@link OpenSshConfig#lookup(String)} some or all of the
135 	 * properties may not be populated. The properties which are not populated
136 	 * should be defaulted by the caller.
137 	 * <p>
138 	 * When returned from {@link OpenSshConfig#lookup(String)} any wildcard
139 	 * entries which appear later in the configuration file will have been
140 	 * already merged into this block.
141 	 */
142 	public static class Host {
143 		String hostName;
144 
145 		int port;
146 
147 		File identityFile;
148 
149 		String user;
150 
151 		String preferredAuthentications;
152 
153 		Boolean batchMode;
154 
155 		String strictHostKeyChecking;
156 
157 		int connectionAttempts;
158 
159 		private HostEntry entry;
160 
161 		private Config config;
162 
163 		// See com.jcraft.jsch.OpenSSHConfig. Translates some command-line keys
164 		// to ssh-config keys.
165 		private static final Map<String, String> KEY_MAP = new TreeMap<>(
166 				String.CASE_INSENSITIVE_ORDER);
167 
168 		static {
169 			KEY_MAP.put("kex", SshConstants.KEX_ALGORITHMS); //$NON-NLS-1$
170 			KEY_MAP.put("server_host_key", SshConstants.HOST_KEY_ALGORITHMS); //$NON-NLS-1$
171 			KEY_MAP.put("cipher.c2s", SshConstants.CIPHERS); //$NON-NLS-1$
172 			KEY_MAP.put("cipher.s2c", SshConstants.CIPHERS); //$NON-NLS-1$
173 			KEY_MAP.put("mac.c2s", SshConstants.MACS); //$NON-NLS-1$
174 			KEY_MAP.put("mac.s2c", SshConstants.MACS); //$NON-NLS-1$
175 			KEY_MAP.put("compression.s2c", SshConstants.COMPRESSION); //$NON-NLS-1$
176 			KEY_MAP.put("compression.c2s", SshConstants.COMPRESSION); //$NON-NLS-1$
177 			KEY_MAP.put("compression_level", "CompressionLevel"); //$NON-NLS-1$ //$NON-NLS-2$
178 			KEY_MAP.put("MaxAuthTries", //$NON-NLS-1$
179 					SshConstants.NUMBER_OF_PASSWORD_PROMPTS);
180 		}
181 
182 		private static String mapKey(String key) {
183 			String k = KEY_MAP.get(key);
184 			return k != null ? k : key;
185 		}
186 
187 		/**
188 		 * Creates a new uninitialized {@link Host}.
189 		 */
190 		public Host() {
191 			// For API backwards compatibility with pre-4.9 JGit
192 		}
193 
194 		Host(HostEntry entry, String hostName, String localUserName) {
195 			this.entry = entry;
196 			complete(hostName, localUserName);
197 		}
198 
199 		/**
200 		 * @return the value StrictHostKeyChecking property, the valid values
201 		 *         are "yes" (unknown hosts are not accepted), "no" (unknown
202 		 *         hosts are always accepted), and "ask" (user should be asked
203 		 *         before accepting the host)
204 		 */
205 		public String getStrictHostKeyChecking() {
206 			return strictHostKeyChecking;
207 		}
208 
209 		/**
210 		 * @return the real IP address or host name to connect to; never null.
211 		 */
212 		public String getHostName() {
213 			return hostName;
214 		}
215 
216 		/**
217 		 * @return the real port number to connect to; never 0.
218 		 */
219 		public int getPort() {
220 			return port;
221 		}
222 
223 		/**
224 		 * @return path of the private key file to use for authentication; null
225 		 *         if the caller should use default authentication strategies.
226 		 */
227 		public File getIdentityFile() {
228 			return identityFile;
229 		}
230 
231 		/**
232 		 * @return the real user name to connect as; never null.
233 		 */
234 		public String getUser() {
235 			return user;
236 		}
237 
238 		/**
239 		 * @return the preferred authentication methods, separated by commas if
240 		 *         more than one authentication method is preferred.
241 		 */
242 		public String getPreferredAuthentications() {
243 			return preferredAuthentications;
244 		}
245 
246 		/**
247 		 * @return true if batch (non-interactive) mode is preferred for this
248 		 *         host connection.
249 		 */
250 		public boolean isBatchMode() {
251 			return batchMode != null && batchMode.booleanValue();
252 		}
253 
254 		/**
255 		 * @return the number of tries (one per second) to connect before
256 		 *         exiting. The argument must be an integer. This may be useful
257 		 *         in scripts if the connection sometimes fails. The default is
258 		 *         1.
259 		 * @since 3.4
260 		 */
261 		public int getConnectionAttempts() {
262 			return connectionAttempts;
263 		}
264 
265 
266 		private void complete(String initialHostName, String localUserName) {
267 			// Try to set values from the options.
268 			hostName = entry.getValue(SshConstants.HOST_NAME);
269 			user = entry.getValue(SshConstants.USER);
270 			port = positive(entry.getValue(SshConstants.PORT));
271 			connectionAttempts = positive(
272 					entry.getValue(SshConstants.CONNECTION_ATTEMPTS));
273 			strictHostKeyChecking = entry
274 					.getValue(SshConstants.STRICT_HOST_KEY_CHECKING);
275 			batchMode = Boolean.valueOf(OpenSshConfigFile
276 					.flag(entry.getValue(SshConstants.BATCH_MODE)));
277 			preferredAuthentications = entry
278 					.getValue(SshConstants.PREFERRED_AUTHENTICATIONS);
279 			// Fill in defaults if still not set
280 			if (hostName == null || hostName.isEmpty()) {
281 				hostName = initialHostName;
282 			}
283 			if (user == null || user.isEmpty()) {
284 				user = localUserName;
285 			}
286 			if (port <= 0) {
287 				port = SshConstants.SSH_DEFAULT_PORT;
288 			}
289 			if (connectionAttempts <= 0) {
290 				connectionAttempts = 1;
291 			}
292 			List<String> identityFiles = entry
293 					.getValues(SshConstants.IDENTITY_FILE);
294 			if (identityFiles != null && !identityFiles.isEmpty()) {
295 				identityFile = new File(identityFiles.get(0));
296 			}
297 		}
298 
299 		Config getConfig() {
300 			if (config == null) {
301 				config = new Config() {
302 
303 					@Override
304 					public String getHostname() {
305 						return Host.this.getHostName();
306 					}
307 
308 					@Override
309 					public String getUser() {
310 						return Host.this.getUser();
311 					}
312 
313 					@Override
314 					public int getPort() {
315 						return Host.this.getPort();
316 					}
317 
318 					@Override
319 					public String getValue(String key) {
320 						// See com.jcraft.jsch.OpenSSHConfig.MyConfig.getValue()
321 						// for this special case.
322 						if (key.equals("compression.s2c") //$NON-NLS-1$
323 								|| key.equals("compression.c2s")) { //$NON-NLS-1$
324 							if (!OpenSshConfigFile.flag(
325 									Host.this.entry.getValue(mapKey(key)))) {
326 								return "none,zlib@openssh.com,zlib"; //$NON-NLS-1$
327 							}
328 							return "zlib@openssh.com,zlib,none"; //$NON-NLS-1$
329 						}
330 						return Host.this.entry.getValue(mapKey(key));
331 					}
332 
333 					@Override
334 					public String[] getValues(String key) {
335 						List<String> values = Host.this.entry
336 								.getValues(mapKey(key));
337 						if (values == null) {
338 							return new String[0];
339 						}
340 						return values.toArray(new String[0]);
341 					}
342 				};
343 			}
344 			return config;
345 		}
346 
347 		@Override
348 		@SuppressWarnings("nls")
349 		public String toString() {
350 			return "Host [hostName=" + hostName + ", port=" + port
351 					+ ", identityFile=" + identityFile + ", user=" + user
352 					+ ", preferredAuthentications=" + preferredAuthentications
353 					+ ", batchMode=" + batchMode + ", strictHostKeyChecking="
354 					+ strictHostKeyChecking + ", connectionAttempts="
355 					+ connectionAttempts + ", entry=" + entry + "]";
356 		}
357 	}
358 
359 	/**
360 	 * {@inheritDoc}
361 	 * <p>
362 	 * Retrieves the full {@link com.jcraft.jsch.ConfigRepository.Config Config}
363 	 * for the given host name. Should be called only by Jsch and tests.
364 	 *
365 	 * @since 4.9
366 	 */
367 	@Override
368 	public Config getConfig(String hostName) {
369 		Host host = lookup(hostName);
370 		return host.getConfig();
371 	}
372 
373 	/** {@inheritDoc} */
374 	@Override
375 	public String toString() {
376 		return "OpenSshConfig [configFile=" + configFile + ']'; //$NON-NLS-1$
377 	}
378 }