1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
|
/*
* Copyright (C) 2018, 2022 Thomas Wolf <thomas.wolf@paranor.ch> and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.internal.transport.sshd;
import static java.text.MessageFormat.format;
import static org.apache.sshd.core.CoreModuleProperties.PASSWORD_PROMPTS;
import static org.apache.sshd.core.CoreModuleProperties.PREFERRED_AUTHS;
import static org.eclipse.jgit.internal.transport.ssh.OpenSshConfigFile.positive;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.config.hosts.HostConfigEntry;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.future.DefaultConnectFuture;
import org.apache.sshd.client.session.ClientSessionImpl;
import org.apache.sshd.client.session.SessionFactory;
import org.apache.sshd.common.AttributeRepository;
import org.apache.sshd.common.config.keys.FilePasswordProvider;
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoConnectFuture;
import org.apache.sshd.common.io.IoSession;
import org.apache.sshd.common.keyprovider.AbstractResourceKeyPairProvider;
import org.apache.sshd.common.keyprovider.KeyIdentityProvider;
import org.apache.sshd.common.session.SessionContext;
import org.apache.sshd.common.session.helpers.AbstractSession;
import org.apache.sshd.common.util.ValidateUtils;
import org.apache.sshd.common.util.net.SshdSocketAddress;
import org.eclipse.jgit.internal.transport.sshd.JGitClientSession.ChainingAttributes;
import org.eclipse.jgit.internal.transport.sshd.JGitClientSession.SessionAttributes;
import org.eclipse.jgit.internal.transport.sshd.proxy.HttpClientConnector;
import org.eclipse.jgit.internal.transport.sshd.proxy.Socks5ClientConnector;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.SshConstants;
import org.eclipse.jgit.transport.sshd.KeyCache;
import org.eclipse.jgit.transport.sshd.KeyPasswordProvider;
import org.eclipse.jgit.transport.sshd.ProxyData;
import org.eclipse.jgit.transport.sshd.ProxyDataFactory;
import org.eclipse.jgit.util.StringUtils;
/**
* Customized {@link SshClient} for JGit. It creates specialized
* {@link JGitClientSession}s that know about the {@link HostConfigEntry} they
* were created for, and it loads all KeyPair identities lazily.
*/
public class JGitSshClient extends SshClient {
/**
* We need access to this during the constructor of the ClientSession,
* before setConnectAddress() can have been called. So we have to remember
* it in an attribute on the SshClient, from where we can then retrieve it.
*/
static final AttributeKey<HostConfigEntry> HOST_CONFIG_ENTRY = new AttributeKey<>();
static final AttributeKey<InetSocketAddress> ORIGINAL_REMOTE_ADDRESS = new AttributeKey<>();
/**
* An attribute key for the comma-separated list of default preferred
* authentication mechanisms.
*/
public static final AttributeKey<String> PREFERRED_AUTHENTICATIONS = new AttributeKey<>();
/**
* An attribute key for the home directory.
*/
public static final AttributeKey<Path> HOME_DIRECTORY = new AttributeKey<>();
/**
* An attribute key for storing an alternate local address to connect to if
* a local forward from a ProxyJump ssh config is present. If set,
* {@link #connect(HostConfigEntry, AttributeRepository, SocketAddress)}
* will not connect to the address obtained from the {@link HostConfigEntry}
* but to the address stored in this key (which is assumed to forward the
* {@code HostConfigEntry} address).
*/
public static final AttributeKey<SshdSocketAddress> LOCAL_FORWARD_ADDRESS = new AttributeKey<>();
private KeyCache keyCache;
private CredentialsProvider credentialsProvider;
private Supplier<KeyPasswordProvider> keyPasswordProviderFactory;
private ProxyDataFactory proxyDatabase;
@Override
protected SessionFactory createSessionFactory() {
// Override the parent's default
return new JGitSessionFactory(this);
}
@Override
public ConnectFuture connect(HostConfigEntry hostConfig,
AttributeRepository context, SocketAddress localAddress)
throws IOException {
if (connector == null) {
throw new IllegalStateException("SshClient not started."); //$NON-NLS-1$
}
Objects.requireNonNull(hostConfig, "No host configuration"); //$NON-NLS-1$
String originalHost = ValidateUtils.checkNotNullAndNotEmpty(
hostConfig.getHostName(), "No target host"); //$NON-NLS-1$
int originalPort = hostConfig.getPort();
ValidateUtils.checkTrue(originalPort > 0, "Invalid port: %d", //$NON-NLS-1$
originalPort);
InetSocketAddress originalAddress = new InetSocketAddress(originalHost,
originalPort);
InetSocketAddress targetAddress = originalAddress;
String userName = hostConfig.getUsername();
String id = userName + '@' + originalAddress;
AttributeRepository attributes = chain(context, this);
SshdSocketAddress localForward = attributes
.resolveAttribute(LOCAL_FORWARD_ADDRESS);
if (localForward != null) {
targetAddress = new InetSocketAddress(localForward.getHostName(),
localForward.getPort());
id += '/' + targetAddress.toString();
}
ConnectFuture connectFuture = new DefaultConnectFuture(id, null);
SshFutureListener<IoConnectFuture> listener = createConnectCompletionListener(
connectFuture, userName, originalAddress, hostConfig);
attributes = sessionAttributes(attributes, hostConfig, originalAddress);
// Proxy support
if (localForward == null) {
ProxyData proxy = getProxyData(targetAddress);
if (proxy != null) {
targetAddress = configureProxy(proxy, targetAddress);
proxy.clearPassword();
}
}
connector.connect(targetAddress, attributes, localAddress)
.addListener(listener);
return connectFuture;
}
private AttributeRepository chain(AttributeRepository self,
AttributeRepository parent) {
if (self == null) {
return Objects.requireNonNull(parent);
}
if (parent == null || parent == self) {
return self;
}
return new ChainingAttributes(self, parent);
}
private AttributeRepository sessionAttributes(AttributeRepository parent,
HostConfigEntry hostConfig, InetSocketAddress originalAddress) {
// sshd needs some entries from the host config already in the
// constructor of the session. Put those into a dedicated
// AttributeRepository for the new session where it will find them.
// We can set the host config only once the session object has been
// created.
Map<AttributeKey<?>, Object> data = new HashMap<>();
data.put(HOST_CONFIG_ENTRY, hostConfig);
data.put(ORIGINAL_REMOTE_ADDRESS, originalAddress);
data.put(TARGET_SERVER, new SshdSocketAddress(originalAddress));
String preferredAuths = hostConfig.getProperty(
SshConstants.PREFERRED_AUTHENTICATIONS,
resolveAttribute(PREFERRED_AUTHENTICATIONS));
if (!StringUtils.isEmptyOrNull(preferredAuths)) {
data.put(SessionAttributes.PROPERTIES,
Collections.singletonMap(
PREFERRED_AUTHS.getName(),
preferredAuths));
}
return new SessionAttributes(
AttributeRepository.ofAttributesMap(data),
parent, this);
}
private ProxyData getProxyData(InetSocketAddress remoteAddress) {
ProxyDataFactory factory = getProxyDatabase();
return factory == null ? null : factory.get(remoteAddress);
}
private InetSocketAddress configureProxy(ProxyData proxyData,
InetSocketAddress remoteAddress) {
Proxy proxy = proxyData.getProxy();
if (proxy.type() == Proxy.Type.DIRECT
|| !(proxy.address() instanceof InetSocketAddress)) {
return remoteAddress;
}
InetSocketAddress address = (InetSocketAddress) proxy.address();
if (address.isUnresolved()) {
address = new InetSocketAddress(address.getHostName(),
address.getPort());
}
switch (proxy.type()) {
case HTTP:
setClientProxyConnector(
new HttpClientConnector(address, remoteAddress,
proxyData.getUser(), proxyData.getPassword()));
return address;
case SOCKS:
setClientProxyConnector(
new Socks5ClientConnector(address, remoteAddress,
proxyData.getUser(), proxyData.getPassword()));
return address;
default:
log.warn(format(SshdText.get().unknownProxyProtocol,
proxy.type().name()));
return remoteAddress;
}
}
private SshFutureListener<IoConnectFuture> createConnectCompletionListener(
ConnectFuture connectFuture, String username,
InetSocketAddress address, HostConfigEntry hostConfig) {
return new SshFutureListener<>() {
@Override
public void operationComplete(IoConnectFuture future) {
if (future.isCanceled()) {
connectFuture.cancel();
return;
}
Throwable t = future.getException();
if (t != null) {
connectFuture.setException(t);
return;
}
IoSession ioSession = future.getSession();
try {
JGitClientSession session = createSession(ioSession,
username, address, hostConfig);
connectFuture.setSession(session);
} catch (RuntimeException e) {
connectFuture.setException(e);
ioSession.close(true);
}
}
@Override
public String toString() {
return "JGitSshClient$ConnectCompletionListener[" + username //$NON-NLS-1$
+ '@' + address + ']';
}
};
}
private JGitClientSession createSession(IoSession ioSession,
String username, InetSocketAddress address,
HostConfigEntry hostConfig) {
AbstractSession rawSession = AbstractSession.getSession(ioSession);
if (!(rawSession instanceof JGitClientSession)) {
throw new IllegalStateException("Wrong session type: " //$NON-NLS-1$
+ rawSession.getClass().getCanonicalName());
}
JGitClientSession session = (JGitClientSession) rawSession;
session.setUsername(username);
session.setConnectAddress(address);
session.setHostConfigEntry(hostConfig);
if (session.getCredentialsProvider() == null) {
session.setCredentialsProvider(getCredentialsProvider());
}
int numberOfPasswordPrompts = getNumberOfPasswordPrompts(hostConfig);
PASSWORD_PROMPTS.set(session, Integer.valueOf(numberOfPasswordPrompts));
session.setAttribute(JGitClientSession.KEY_PASSWORD_PROVIDER_FACTORY,
getKeyPasswordProviderFactory());
List<Path> identities = hostConfig.getIdentities().stream()
.map(s -> {
try {
return Paths.get(s);
} catch (InvalidPathException e) {
log.warn(format(SshdText.get().configInvalidPath,
SshConstants.IDENTITY_FILE, s), e);
return null;
}
}).filter(p -> p != null && Files.exists(p))
.collect(Collectors.toList());
CachingKeyPairProvider ourConfiguredKeysProvider = new CachingKeyPairProvider(
identities, keyCache);
FilePasswordProvider passwordProvider = getFilePasswordProvider();
ourConfiguredKeysProvider.setPasswordFinder(passwordProvider);
if (hostConfig.isIdentitiesOnly()) {
session.setKeyIdentityProvider(ourConfiguredKeysProvider);
} else {
KeyIdentityProvider defaultKeysProvider = getKeyIdentityProvider();
if (defaultKeysProvider instanceof AbstractResourceKeyPairProvider<?>) {
((AbstractResourceKeyPairProvider<?>) defaultKeysProvider)
.setPasswordFinder(passwordProvider);
}
KeyIdentityProvider combinedProvider = new CombinedKeyIdentityProvider(
ourConfiguredKeysProvider, defaultKeysProvider);
session.setKeyIdentityProvider(combinedProvider);
}
return session;
}
private int getNumberOfPasswordPrompts(HostConfigEntry hostConfig) {
String prompts = hostConfig
.getProperty(SshConstants.NUMBER_OF_PASSWORD_PROMPTS);
if (prompts != null) {
prompts = prompts.trim();
int value = positive(prompts);
if (value > 0) {
return value;
}
log.warn(format(SshdText.get().configInvalidPositive,
SshConstants.NUMBER_OF_PASSWORD_PROMPTS, prompts));
}
return PASSWORD_PROMPTS.getRequiredDefault().intValue();
}
/**
* Set a cache for loaded keys. Newly discovered keys will be added when
* IdentityFile host entries from the ssh config file are used during
* session authentication.
*
* @param cache
* to use
*/
public void setKeyCache(KeyCache cache) {
keyCache = cache;
}
/**
* Sets a {@link ProxyDataFactory} for connecting through proxies.
*
* @param factory
* to use, or {@code null} if proxying is not desired or
* supported
*/
public void setProxyDatabase(ProxyDataFactory factory) {
proxyDatabase = factory;
}
/**
* Retrieves the {@link ProxyDataFactory}.
*
* @return the factory, or {@code null} if none is set
*/
protected ProxyDataFactory getProxyDatabase() {
return proxyDatabase;
}
/**
* Sets the {@link CredentialsProvider} for this client.
*
* @param provider
* to set
*/
public void setCredentialsProvider(CredentialsProvider provider) {
credentialsProvider = provider;
}
/**
* Retrieves the {@link CredentialsProvider} set for this client.
*
* @return the provider, or {@code null} if none is set.
*/
public CredentialsProvider getCredentialsProvider() {
return credentialsProvider;
}
/**
* Sets a supplier for a {@link KeyPasswordProvider} for this client.
*
* @param factory
* to set
*/
public void setKeyPasswordProviderFactory(
Supplier<KeyPasswordProvider> factory) {
keyPasswordProviderFactory = factory;
}
/**
* Retrieves the {@link KeyPasswordProvider} factory of this client.
*
* @return a factory to create {@link KeyPasswordProvider}s
*/
public Supplier<KeyPasswordProvider> getKeyPasswordProviderFactory() {
return keyPasswordProviderFactory;
}
/**
* A {@link SessionFactory} to create our own specialized
* {@link JGitClientSession}s.
*/
private static class JGitSessionFactory extends SessionFactory {
public JGitSessionFactory(JGitSshClient client) {
super(client);
}
@Override
protected ClientSessionImpl doCreateSession(IoSession ioSession)
throws Exception {
return new JGitClientSession(getClient(), ioSession);
}
}
/**
* A {@link KeyIdentityProvider} that iterates over the {@link Iterable}s
* returned by other {@link KeyIdentityProvider}s.
*/
private static class CombinedKeyIdentityProvider
implements KeyIdentityProvider {
private final List<KeyIdentityProvider> providers;
public CombinedKeyIdentityProvider(KeyIdentityProvider... providers) {
this(Arrays.stream(providers).filter(Objects::nonNull)
.collect(Collectors.toList()));
}
public CombinedKeyIdentityProvider(
List<KeyIdentityProvider> providers) {
this.providers = providers;
}
@Override
public Iterable<KeyPair> loadKeys(SessionContext context) {
return () -> new Iterator<>() {
private Iterator<KeyIdentityProvider> factories = providers
.iterator();
private Iterator<KeyPair> current;
private Boolean hasElement;
@Override
public boolean hasNext() {
if (hasElement != null) {
return hasElement.booleanValue();
}
while (current == null || !current.hasNext()) {
if (factories.hasNext()) {
try {
current = factories.next().loadKeys(context)
.iterator();
} catch (IOException | GeneralSecurityException e) {
throw new RuntimeException(e);
}
} else {
current = null;
hasElement = Boolean.FALSE;
return false;
}
}
hasElement = Boolean.TRUE;
return true;
}
@Override
public KeyPair next() {
if ((hasElement == null && !hasNext())
|| !hasElement.booleanValue()) {
throw new NoSuchElementException();
}
hasElement = null;
KeyPair result;
try {
result = current.next();
} catch (NoSuchElementException e) {
result = null;
}
return result;
}
};
}
}
}
|