This is an automated email from the ASF dual-hosted git repository.
lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git
The following commit(s) were added to refs/heads/master by this push:
new 94c660d [SSHD-924] Update SSHD documentation and add more code samples
94c660d is described below
commit 94c660dca00f651e7ec18b91687843a39bdc0e85
Author: Lyor Goldstein <[email protected]>
AuthorDate: Thu Jun 20 15:43:42 2019 +0300
[SSHD-924] Update SSHD documentation and add more code samples
---
docs/client-setup.md | 19 ++++----
docs/commands.md | 5 ++
docs/dependencies.md | 7 +--
docs/event-listeners.md | 114 ++-------------------------------------------
docs/extensions.md | 6 ---
docs/git.md | 6 +--
docs/internals.md | 45 ++++++++++++------
docs/port-forwarding.md | 46 +++++++++++++++++-
docs/scp.md | 66 +++++++++++++++++---------
docs/security-providers.md | 11 -----
docs/server-setup.md | 11 -----
docs/sftp.md | 107 +++++++++++++++++++++++++++++++-----------
12 files changed, 219 insertions(+), 224 deletions(-)
diff --git a/docs/client-setup.md b/docs/client-setup.md
index 797d7b6..05283fa 100644
--- a/docs/client-setup.md
+++ b/docs/client-setup.md
@@ -1,6 +1,5 @@
# Set up an SSH client in 5 minutes
-
SSHD is designed to easily allow setting up and using an SSH client in a few
simple steps. The client needs to be configured
and then started before it can be used to connect to an SSH server. There are
a few simple steps for creating a client
instance - for more details refer to the `SshClient` class.
@@ -35,14 +34,11 @@ key was accepted. There are other out-of-the-box verifiers
available in the code
* `RejectAllServerKeyVerifier` - rejects all server key - usually used in
tests or as a fallback verifier if none
of it predecesors validated the server key
-
* `RequiredServerKeyVerifier` - accepts only **one** specific server key
(similar to certificate pinning for SSL)
-
* `KnownHostsServerKeyVerifier` - uses the
[known_hosts](https://en.wikibooks.org/wiki/OpenSSH/Client_Configuration_Files#Public_Keys_from_other_Hosts_.E2.80.93_.7E.2F.ssh.2Fknown_hosts)
file to validate the server key. One can use this class + some existing code
to **update** the file when new servers are detected and their keys are
accepted.
-
Of course, one can implement the verifier in whatever other manner is suitable
for the specific code needs.
### `ClientIdentityLoader/KeyPairProvider`
@@ -181,7 +177,6 @@ regardless of the user's own traffic:
set the `HEARTBEAT_REPLY_WAIT` property value to a **positive** value
specifying the number of **milliseconds** the client is
willing to wait for the server's reply to the global request.
-
* Customized user code
In order to support customized user code for this feature, the
`ReservedSessionMessagesHandler` can be used to
@@ -196,7 +191,7 @@ regardless of the user's own traffic:
* Both options can be activated either on the `SshClient` (for **global**
setup) and/or
the `ClientSession` (for specific session configuration).
-* The `keepalive@,,,,` mechanism **supersedes** the the other mechanisms if
activated.
+* The `keepalive@,,,,` mechanism **supersedes** the other mechanisms if
activated.
* If specified timeout expires for the `wantReply` option then session
will be **closed**.
@@ -224,10 +219,14 @@ defaults - which however, might not be adequate for the
specific client/server.
channel.setIn(...stdin...);
channel.setOut(...stdout...);
channel.setErr(...stderr...);
- ... spawn the thread that will pump the STDIN/OUT/ERR
- channel.open().verify(...some timeout...);
- // Wait (forever) for the channel to close - signalling shell exited
- channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0L);
+ // ... spawn the thread(s) that will pump the STDIN/OUT/ERR
+ try {
+ channel.open().verify(...some timeout...);
+ // Wait (forever) for the channel to close - signalling shell
exited
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0L);
+ } finally {
+ // ... stop the pumping threads ...
+ }
}
// In order to override the PTY and/or environment
diff --git a/docs/commands.md b/docs/commands.md
index f981aa6..10ef2d4 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -146,6 +146,11 @@ The provided message is simply logged at DEBUG level.
callback.onExit(0);
}
+
+ @Override
+ public void destroy() throws Exception {
+ ...release any allocated resources...
+ }
}
```
diff --git a/docs/dependencies.md b/docs/dependencies.md
index 618f943..85a43c5 100644
--- a/docs/dependencies.md
+++ b/docs/dependencies.md
@@ -2,7 +2,6 @@
## [Bouncy Castle](https://www.bouncycastle.org/)
-
Required mainly for writing keys to PEM files or for special keys/ciphers/etc.
that are not part of the standard
[Java Cryptography
Extension](https://en.wikipedia.org/wiki/Java_Cryptography_Extension). See
[Java Cryptography Architecture (JCA) Reference
Guide](https://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/CryptoSpec.html)
@@ -15,18 +14,14 @@ keys, signatures, etc. rather than the default JCE provided
in the JVM.
- The security provider can also be registered for keys/ciphers/etc. that are
already supported by the standard JCE as a **replacement** for them.
-
- The _BouncyCastle_ code can also be used to load keys from PEM files
instead or in parallel with the built-in code that
already parses the standard PEM formats for the default JCE supported key
types.
-
-- One can use the `BouncyCastleKeyPairResourceParser` to load standard PEM
files instead of the core one - either directly
+ - One can use the `BouncyCastleKeyPairResourceParser` to load standard PEM
files instead of the core one - either directly
or via `SecurityUtils#setKeyPairResourceParser` for **global** usage - even
without registering or enabling the provider.
-
- The required _Maven_ module(s) are defined as `optional` so must be added
as an **explicit** dependency in order to be included in the classpath:
-
```xml
<dependency>
diff --git a/docs/event-listeners.md b/docs/event-listeners.md
index 22b3dcc..476ec13 100644
--- a/docs/event-listeners.md
+++ b/docs/event-listeners.md
@@ -65,12 +65,13 @@ In this context, it is worth mentioning that one can attach
to sessions **arbitr
});
```
+The attributes cache is automatically cleared once the session is closed.
+
### `ChannelListener`
Informs about channel related events - as with sessions, once can influence
the channel to some extent, depending on the channel's **state**.
The ability to influence channels is much more limited than sessions. In this
context, it is worth mentioning that one can attach to channels
-**arbitrary attributes** that can be retrieved by the user's code later on -
same was as it is done for sessions.
-
+**arbitrary attributes** that can be retrieved by the user's code later on and
are cleared when channel is closed - same was as it is done for sessions.
### `UnknownChannelReferenceHandler`
@@ -102,7 +103,6 @@ or
[server](./server-setup.md#providing-server-side-heartbeat).
**Note:** The `handleUnimplementedMessage` method serves both for handling
`SSH_MSG_UNIMPLEMENTED` and any other unrecognized
message received in the session as well.
-
```java
class MyClientSideReservedSessionMessagesHandler implements
ReservedSessionMessagesHandler {
@@ -186,111 +186,3 @@ the handler decided not to intervene.
Informs about signal requests as described in [RFC 4254 - section
6.9](https://tools.ietf.org/html/rfc4254#section-6.9), "break" requests
(sent as SIGINT) as described in [RFC
4335](https://tools.ietf.org/html/rfc4335) and "window-change" (sent as
SIGWINCH) requests as described
in [RFC 4254 - section 6.7](https://tools.ietf.org/html/rfc4254#section-6.7)
-
-
-### `SftpEventListener`
-
-Provides information about major SFTP protocol events. The provided
`File/DirectoryHandle` to the various callbacks can also be used to
-store user-defined attributes via its `AttributeStore` implementation. The
listener is registered at the `SftpSubsystemFactory`:
-
-
-```java
- public class MySfpEventListener implements SftpEventListener {
- private static final AttributeKey<SomeType> MY_SPECIAL_KEY = new
Attribute<SomeType>();
-
- ...
- @Override
- public void opening(ServerSession session, String remoteHandle, Handle
localHandle) throws IOException {
- localHandle.setAttribute(MY_SPECIAL_KEY, instanceOfSomeType);
- }
-
- @Override
- public void writing(
- ServerSession session, String remoteHandle, FileHandle
localHandle,
- long offset, byte[] data, int dataOffset, int dataLen)
- throws IOException {
- SomeType myData = localHandle.getAttribute(MY_SPECIAL_KEY);
- ...do something based on my data...
- }
- }
-
-
- SftpSubsystemFactory factory = new SftpSubsystemFactory();
- factory.addSftpEventListener(new MySftpEventListener());
-
sshd.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(factory));
-
-```
-
-**Note:** the attached attributes are automatically removed once handle has
been closed - regardless of
-whether the close attempt was successful or not. In other words, after
`SftpEventListener#closed` has been
-called, all attributes associated with the handle are cleared.
-
-### `SftpFileSystemAccessor`
-
-This is the abstraction providing the SFTP server subsystem access to files
and directories. The SFTP subsystem
-uses this abstraction to obtain file channels and/or directory streams. One
can override the default implementation
-and thus be able to track and/or intervene in all opened files and folders
throughout the SFTP server subsystem code.
-The accessor is registered/overwritten in via the `SftpSubSystemFactory`:
-
-```java
-
- SftpSubsystemFactory factory = new SftpSubsystemFactory.Builder()
- .withFileSystemAccessor(new MySftpFileSystemAccessor())
- .build();
- server.setSubsystemFactories(Collections.singletonList(factory));
-
-```
-
-**Note:**
-
-* Closing of file channel/directory streams created by the accessor are also
closed
-via callbacks to the same accessor
-
-* When closing a file channel that may have been potentially modified, the
default implementation
-forces a synchronization of the data with the file-system. This behavior can
be modified
-by setting the `sftp-auto-fsync-on-close` property to *false* (or by providing
a customized implementation
-that involves other considerations as well).
-
-### `PortForwardingEventListener`
-
-Informs and allows tracking of port forwarding events as described in [RFC
4254 - section 7](https://tools.ietf.org/html/rfc4254#section-7)
-as well as the (simple) [SOCKS](https://en.wikipedia.org/wiki/SOCKS) protocol
(versions 4, 5). In this context, one can create a
-`PortForwardingTracker` that can be used in a `try-with-resource` block so
that the set up forwarding is automatically torn down when
-the tracker is `close()`-d:
-
-
-```java
-
- try (ClientSession session = client.connect(user, host,
port).verify(...timeout...).getSession()) {
- session.addPasswordIdentity(password);
- session.auth().verify(...timeout...);
-
- try (PortForwardingTracker tracker =
session.createLocal/RemotePortForwardingTracker(...)) {
- ...do something that requires the tunnel...
- }
-
- // Tunnel is torn down when code reaches this point
- }
-```
-
-### `ScpTransferEventListener`
-
-Inform about SCP related events. `ScpTransferEventListener`(s) can be
registered on *both* client and server side:
-
-
-```java
-
- // Server side
- ScpCommandFactory factory = new ScpCommandFactory(...with/out delegate..);
- factory.addEventListener(new MyServerSideScpTransferEventListener());
- sshd.setCommandFactory(factory);
-
- // Client side
- try (ClientSession session = client.connect(user, host,
port).verify(...timeout...).getSession()) {
- session.addPasswordIdentity(password);
- session.auth().verify(...timeout...);
-
- ScpClient scp = session.createScpClient(new
MyClientSideScpTransferEventListener());
- ...scp.upload/download...
- }
-```
diff --git a/docs/extensions.md b/docs/extensions.md
index d2f5eb1..9d0b044 100644
--- a/docs/extensions.md
+++ b/docs/extensions.md
@@ -18,7 +18,6 @@ and adds proprietary logic.
* `InteractivePasswordIdentityProvider` - helps implement a
`PasswordIdentityProvider` by delegating calls
to `UserInteraction#getUpdatedPassword`. The way to use it would be as follows:
-
```java
try (ClientSession session = client.connect(login, host,
port).await().getSession()) {
session.setUserInteraction(...); // this can also be set at the
client level
@@ -32,7 +31,6 @@ try (ClientSession session = client.connect(login, host,
port).await().getSessio
or
-
```java
UserInteraction ui = ....;
try (ClientSession session = client.connect(login, host,
port).await().getSession()) {
@@ -47,20 +45,16 @@ try (ClientSession session = client.connect(login, host,
port).await().getSessio
**Note:** `UserInteraction#isInteractionAllowed` is consulted prior to
invoking `getUpdatedPassword` - if it
returns _false_ then password retrieval method is not invoked, and it is
assumed that no more passwords are available
-
* `SimpleAccessControlScpEventListener` - Provides a simple access control by
making a distinction between
methods that upload data and ones that download it via SCP. In order to use
it, simply extend it and override
its `isFileUpload/DownloadAllowed` methods
-
* `SimpleAccessControlSftpEventListener` - Provides a simple access control by
making a distinction between
methods that provide SFTP file information - including reading data - and
those that modify it
-
* `ProxyProtocolAcceptor` - A working prototype to support the PROXY protocol
as described in
[HAProxy
Documentation](http://www.haproxy.org/download/1.8/doc/proxy-protocol.txt)
-
* `ThrottlingPacketWriter` - An example of a way to overcome big window sizes
when sending data - as
described in [SSHD-754](https://issues.apache.org/jira/browse/SSHD-754) and
[SSHD-768](https://issues.apache.org/jira/browse/SSHD-768)
diff --git a/docs/git.md b/docs/git.md
index 8c9b9ef..0d27b25 100644
--- a/docs/git.md
+++ b/docs/git.md
@@ -12,7 +12,6 @@ instance to use, and even which `ClientSession`. The default
instance allocates
created - which is started and stopped as necessary. However, this can be
pretty wasteful, so if one intends to issue several commands
that access GIT repositories via SSH, one should maintain a **single** client
instance and re-use it:
-
```java
SshClient client = ...create and setup the client...
@@ -29,14 +28,12 @@ that access GIT repositories via SSH, one should maintain a
**single** client in
}
```
-
### Server-side
See `GitPackCommandFactory` and `GitPgmCommandFactory` - in order for the
various commands to function correctly, they require a `GitLocationResolver`
that is invoked in order to allow the user to decide which is the correct GIT
repository root location for a given command. The resolver is provided
with all the relevant details - including the command and server session
through which the command was received:
-
```java
GitLocationResolver resolver = (cmd, session, fs) -> ...consult some code
- perhaps based on the authenticated username...
@@ -44,8 +41,7 @@ with all the relevant details - including the command and
server session through
```
- These command factories also accept a delegate to which non-_git_ commands
are routed:
-
+These command factories also accept a delegate to which non-_git_ commands are
routed:
```java
diff --git a/docs/internals.md b/docs/internals.md
index 23c7284..7d7433b 100644
--- a/docs/internals.md
+++ b/docs/internals.md
@@ -35,6 +35,7 @@ before starting the client/server. Therefore, the default
selection process desc
# Advanced configuration and interaction
## Properties and inheritance model
+
The code's behavior is highly customizable not only via non-default
implementations of interfaces but also as far as
the **parameters** that govern its behavior - e.g., timeouts, min./max.
values, allocated memory size, etc... All the
customization related code flow implements a **hierarchical**
`PropertyResolver` inheritance model where the "closest"
@@ -48,6 +49,36 @@ to decide how to behave, then the following configuration
hierarchy is consulted
* The system properties - **Note:** any configuration value required by the
code can be provided via a system property bearing
the `org.apache.sshd.config` prefix - see `SyspropsMapWrapper` for the
implementation details.
+The easiest way to configure a target instance (client/server/session/channel)
is via one of the (many) available `PropertyResolverUtils`
+`updateProperty` methods:
+
+```java
+ PropertyResolverUtils.updateProperty(client, "prop1", 5L);
+ PropertyResolverUtils.updateProperty(server, "prop2", someInteger);
+ PropertyResolverUtils.updateProperty(session, "prop3", "hello world");
+ PropertyResolverUtils.updateProperty(channel, "prop4", false);
+```
+
+**Note**: the `updateProperty` method(s) accept **any** `Object` so care must
be taken to provide the expected type. However, at
+least for **primitive** values, the various `getXXXProperty` methods
automatically convert compatible types:
+
+```java
+ PropertyResolverUtils.updateProperty(client, "prop1", 7365L);
+
+ // all will yield 7365 converted to the relevant type
+ Long value = PropertyResolverUtils.getLongProperty(client, "prop1");
+ Integer value = PropertyResolverUtils.getLongProperty(client, "prop1");
+```
+
+including strings
+
+```java
+ PropertyResolverUtils.updateProperty(client, "prop1", "7365");
+
+ // all will yield 7365
+ Long value = PropertyResolverUtils.getLongProperty(client, "prop1");
+ Integer value = PropertyResolverUtils.getLongProperty(client, "prop1");
+```
### Using the inheritance model for fine-grained/targeted configuration
@@ -77,29 +108,23 @@ key - there are several possible values for this key:
* A simple string - in which case its contents are the welcome banner.
-
* A file [URI](https://docs.oracle.com/javase/8/docs/api/java/net/URI.html) -
or a string starting with `"file:/"` followed by the file path - see below.
-
* A [URL](https://docs.oracle.com/javase/8/docs/api/java/net/URL.html) - or a
string containing "://" - in which
case the
[URL#openStream()](https://docs.oracle.com/javase/8/docs/api/java/net/URL.html#openStream)
method is invoked
and its contents are read.
-
* A [File](https://docs.oracle.com/javase/8/docs/api/java/io/File.html) or
a [Path](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html) -
in this case, the file's contents are __re-loaded__ every time it is required
and sent as the banner contents.
-
* The special value `ServerAuthenticationManager.AUTO_WELCOME_BANNER_VALUE`
which generates a combined "random art" of
all the server's keys as described in `Perrig A.` and `Song D.`-s article
[Hash Visualization: a New Technique to improve Real-World
Security](http://sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf)
- _International Workshop on Cryptographic Techniques and E-Commerce (CrypTEC
'99)_
-
* One can also override the `ServerUserAuthService#resolveWelcomeBanner`
method and use whatever other content customization one sees fit.
**Note:**
-
1. If any of the sources yields an empty string or is missing (in the case of
a resource) then no welcome banner message is sent.
2. If the banner is loaded from a file or URL resource, then one can configure
the
[Charset](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html)
used to convert the file's contents into a string via the
`ServerAuthenticationManager.WELCOME_BANNER_CHARSET` configuration key
(default=`UTF-8`).
@@ -107,19 +132,16 @@ all the server's keys as described in `Perrig A.` and
`Song D.`-s article
3. In this context, see also the
`ServerAuthenticationManager.WELCOME_BANNER_LANGUAGE` configuration key - which
provides control over the declared language tag, although most clients seem to
ignore it.
-
### Welcome banner sending phase
According to [RFC 4252 - section
5.4](https://tools.ietf.org/html/rfc4252#section-5.4):
> The SSH server may send an SSH_MSG_USERAUTH_BANNER message at any time after
> this authentication protocol starts and before authentication is successful.
-
The code contains a `WelcomeBannerPhase` enumeration that can be used to
configure via the `ServerAuthenticationManager.WELCOME_BANNER_PHASE`
configuration key the authentication phase at which the welcome banner is sent
(see also the `ServerAuthenticationManager.DEFAULT_BANNER_PHASE` value).
In this context, note that if the `NEVER` phase is configured, no banner will
be sent even if one has been configured via one of the methods mentioned
previously.
-
## `HostConfigEntryResolver`
This interface provides the ability to intervene during the connection and
authentication phases and "re-write"
@@ -127,7 +149,6 @@ the user's original parameters. The
`DefaultConfigFileHostEntryResolver` instanc
client instance follows the [SSH config
file](https://www.digitalocean.com/community/tutorials/how-to-configure-custom-connection-options-for-your-ssh-client)
standards, but the interface can be replaced so as to implement whatever
proprietary logic is required.
-
```java
SshClient client = SshClient.setupDefaultClient();
@@ -144,7 +165,6 @@ standards, but the interface can be replaced so as to
implement whatever proprie
}
```
-
## `SshConfigFileReader`
Can be used to read various standard SSH
[client](http://linux.die.net/man/5/ssh_config)
@@ -204,20 +224,17 @@ request handlers are invoked when a
global/channel-specific request is received
* All currently registered handlers' `process` method is invoked with the
request type string parameter (among others).
The implementation should examine the request parameters and decide whether it
is able to process it.
-
* If the handler returns `Result.Unsupported` then the next registered handler
is invoked.
In other words, processing stops at the **first** handler that returned a
valid response. Thus the importance of
the `List<RequestHandler<...>>` that defines the **order** in which the
handlers are invoked. **Note**: while
it is possible to register multiple handlers for the same request and rely on
their order, it is highly recommended
to avoid this situation as it makes debugging the code and diagnosing problems
much more difficult.
-
* If no handler reported a valid result value then a failure message is sent
back to the peer. Otherwise, the returned
result is translated into the appropriate success/failure response (if the
sender asked for a response). In this context,
the handler may choose to build and send the response within its own code, in
which case it should return the
`Result.Replied` value indicating that it has done so.
-
```java
public class MySpecialChannelRequestHandler implements
ChannelRequestHandler {
diff --git a/docs/port-forwarding.md b/docs/port-forwarding.md
index 4291e9d..d5a1dc0 100644
--- a/docs/port-forwarding.md
+++ b/docs/port-forwarding.md
@@ -1,5 +1,29 @@
## Port forwarding
+### `PortForwardingEventListener`
+
+Informs and allows tracking of port forwarding events as described in [RFC
4254 - section 7](https://tools.ietf.org/html/rfc4254#section-7)
+as well as the (simple) [SOCKS](https://en.wikipedia.org/wiki/SOCKS) protocol
(versions 4, 5). In this context, one can create a
+`PortForwardingTracker` that can be used in a `try-with-resource` block so
that the set up forwarding is automatically torn down when
+the tracker is `close()`-d:
+
+
+```java
+
+ client.addPortForwardingEventListener(new MySuperDuperListener());
+
+ try (ClientSession session = client.connect(user, host,
port).verify(...timeout...).getSession()) {
+ session.addPasswordIdentity(password);
+ session.auth().verify(...timeout...);
+
+ try (PortForwardingTracker tracker =
session.createLocal/RemotePortForwardingTracker(...)) {
+ ...do something that requires the tunnel...
+ }
+
+ // Tunnel is torn down when code reaches this point
+ }
+```
+
### Standard port forwarding
Port forwarding as specified in [RFC 4254 - section
7](https://tools.ietf.org/html/rfc4254#section-7) is fully
@@ -8,8 +32,26 @@ method. The key player in this capability is the configured
`ForwardingFilter` t
and server. By default, this capability is **disabled** - i.e., the user must
provide an implementation and call the appropriate
`setForwardingFilter` method on the client/server.
-The code contains 2 simple implementations - an accept-all and a reject-all
one that can be used for these trivial
-policies. **Note:** setting a _null_ filter is equivalent to rejecting all
such attempts.
+```java
+ SshClient client = ...create/obtain an instance...
+ client.setForwardingFilter(...filter instance...);
+
+ SshServer server = ...create/obtain an instance...
+ server.setForwardingFilter(...filter instance...);
+```
+
+The code contains 2 simple implementations - an `AcceptAllForwardingFilter`
and a `RejectAllForwardingFilter` one that can be used for
+these trivial policies. **Note:** setting a _null_ filter is equivalent to
rejecting all such attempts.
+
+In order to help with the forwarding policy, the filter is actually made up of
3 "groups" of forwarding:
+
+* `AgentForwardingFilter`
+* `X11ForwardingFilter`
+* `TcpForwardingFilter`
+
+It is possible to implement each and every one separately and then combine
them via `ForwardingFilter#asForwardingFilter`. In this
+context, one does not have to implement all 3 - any implementation not
provided is assumed to be disabled. Furthermore, there are
+reasonable default implementations for all 3, so one can override only a
specific group policy and provide defaults for the rest.
### SOCKS
diff --git a/docs/scp.md b/docs/scp.md
index b68ee8d..dd4e92c 100644
--- a/docs/scp.md
+++ b/docs/scp.md
@@ -13,6 +13,31 @@ to add this additional dependency to your maven project:
```
+### `ScpTransferEventListener`
+
+Callback to inform about SCP related events. `ScpTransferEventListener`(s) can
be registered on *both* client and server side:
+
+```java
+
+ // Server side
+ ScpCommandFactory factory = new ScpCommandFactory(...with/out delegate..);
+ factory.addEventListener(new MyServerSideScpTransferEventListener());
+ sshd.setCommandFactory(factory);
+
+ // Client side
+ try (ClientSession session = client.connect(user, host, port)
+ .verify(...timeout...)
+ .getSession()) {
+ session.addPasswordIdentity(password);
+ session.auth().verify(...timeout...);
+
+ ScpClientCreator creator = ... obtain an instance ...
+ ScpClient client = creator.createScpClient(session, new
MySuperDuperListener());
+
+ ...scp.upload/download...
+ }
+```
+
### Client-side SCP
In order to obtain an `ScpClient` one needs to use an `ScpClientCreator`:
@@ -27,6 +52,20 @@ ScpClient client = creator.createScpClient(session);
A default `ScpClientCreator` instance is provided as part of the module - see
`ScpClientCreator.instance()`
+The `ScpClientCreator` can also be used to attach a default
`ScpTransferEventListener` that will be automatically
+add to **all** created SCP client instances through that creator - unless
specifically overridden:
+
+```java
+
+ClientSession session = ... obtain an instance ...
+ScpClientCreator creator = ... obtain an instance ...
+creator.setScpTransferEventListener(new MySuperDuperListener());
+
+ScpClient client1 = creator.createScpClient(session); // <<== automatically
uses MySuperDuperListener
+ScpClient client2 = creator.createScpClient(session, new SomeOtherListener());
// <<== uses SomeOtherListener instead of MySuperDuperListener
+
+```
+
#### ScpFileOpener(s)
As part of the `ScpClientCreator`, the SCP module also uses a `ScpFileOpener`
instance in order to access
@@ -41,7 +80,7 @@ The user may attach a default opener that will be
automatically attached to **al
* Example of using a non-default opener for monitoring and reporting on
transfer progress
*/
public class ScpTransferProgressMonitor extends DefaultScpFileOpener {
- public static ScpTransferProgressMonitor MONITOR = new
ScpTransferProgressMonitor();
+ public static final ScpTransferProgressMonitor MONITOR = new
ScpTransferProgressMonitor();
public ScpTransferProgressMonitor() {
super();
@@ -80,29 +119,12 @@ ScpClient client2 = creator.createScpClient(session, new
SomeOtherOpener()); /
This behavior can be controlled by setting the `scp-auto-sync-on-write`
(a.k.a. `ScpFileOpener#PROP_AUTO_SYNC_FILE_ON_WRITE`) property to _false_
or overriding the `DefaultScpFileOpener#resolveOpenOptions`, or even
overriding the `ScpFileOpener#openWrite` method altogether.
-* Patterns used in `ScpFileOpener#getMatchingFilesToSend` are matched using
case sensitivity derived from the O/S:
+* Patterns used in `ScpFileOpener#getMatchingFilesToSend` are matched using
case sensitivity derived from the O/S as detected by
+the internal `OsUtils`. If a different behavior is required, then one needs to
replace the default opener with one that uses a
+different sensitivity via `DirectoryScanner#setCaseSensitive` call (or
executes the pattern matching in another way).
* `Windows` - case insensitive
- * `Unix=true` - case sensitive
-
-as detected by the internal `OsUtils`. If a different behavior is required,
then one needs to replace the default opener with one
-that uses a different sensitivity via `DirectoryScanner#setCaseSensitive` call
(or executes the pattern matching in another way).
-
-#### ScpTransferEventListener(s)
-
-The `ScpClientCreator` can also be used to attach a default
`ScpTransferEventListener` that will be attached to
-**all** created SCP client instances through that creator - unless
specifically overridden:
-
-```java
-
-ClientSession session = ... obtain an instance ...
-ScpClientCreator creator = ... obtain an instance ...
-creator.setScpTransferEventListener(new MySuperDuperListener());
-
-ScpClient client1 = creator.createScpClient(session); // <<== automatically
uses MySuperDuperListener
-ScpClient client2 = creator.createScpClient(session, new SomeOtherListener());
// <<== uses SomeOtherListener instead of MySuperDuperListener
-
-```
+ * `Unix` - case sensitive
### Server-side SCP
diff --git a/docs/security-providers.md b/docs/security-providers.md
index bbb3f69..71f9d52 100644
--- a/docs/security-providers.md
+++ b/docs/security-providers.md
@@ -15,35 +15,29 @@ no-arguments constructor. The code automatically parses the
list and attempts to
**Note:**
-
- The registration code automatically parses the configured registrars list
and instantiates them. In this context, one can use the
special `none` value to indicate that the code should not attempt to
automatically register the default providers.
- A registrar instance might be created but eventually discarded and not
invoked if it is disabled, unsupported or already registered
programmatically via `SecurityUtils#registerSecurityProvider`.
-
- The registration attempt is a **one-shot** deal - i.e., once the registrars
list is parsed and successfully resolved, any modifications
to the registered security providers must be done **programatically**. One can
call `SecurityUtils#isRegistrationCompleted()` to find out
if the registration phase has already been executed.
-
- The registrars are consulted in the same **order** as they were initially
registered - either programmatically or via the system property
configuration. Therefore, if two or more registrars support the same
algorithm, then the earlier registered one will be used.
-
- If no matching registrar was found, then the default security provider is
used. If none set, the JCE defaults are invoked. The default
security provider can be configured either via the
`org.apache.sshd.security.defaultProvider` system property or by
programmatically
invoking `SecurityUtils#setDefaultProviderChoice`. **Note:** if the system
property option is used, then it is assumed to contain a security
provider's **name** (rather than its `Provider` class name...).
-
- If programmatic selection of the default security provider choice is
required, then the code flow must ensure that
`SecurityUtils#setDefaultProviderChoice` is called before **any** security
entity (e.g., ciphers, keys, etc...) are
required. Theoretically, one could change the choice after ciphers have been
been requested but before keys were generated
(e.g....), but it is dangerous and may yield unpredictable behavior.
-
### Implementing a new security provider registrar
See `AbstractSecurityProviderRegistrar` helper class for a default
implementation of most of the required functionality, as
@@ -70,26 +64,21 @@ is assumed to contain a comma-separated list of supported
`KeyFactory` algorithm
**Note:**
-
* The same naming convention can be used to enable/disable the registrar -
even if supported - e.g.,
`org.apache.sshd.security.provider.BC.enabled=false` disables the
_BouncyCastle_ registrar.
-
* One can use `all` or `*` to specify that all entities of the specified type
are supported - e.g.,
`org.apache.sshd.security.provider.BC.MessageDigest=all`. In this context, one
can override the
`getDefaultSecurityEntitySupportValue` method if no fine-grained configuration
is required per-entity type,
-
* The result of an `isXxxSupported` call is/should be **cached** (see
`AbstractSecurityProviderRegistrar`).
-
* For ease of implementation, all support query calls are routed to the
`isSecurityEntitySupported` method
so that one can concentrate all the configuration in a single method. This is
done for **convenience**
reasons - the code will invoke the correct support query as per the type of
entity it needs. E.g., if it
needs a cipher, it will invoke `isCipherSupported` - which by default will
invoke `isSecurityEntitySupported`
with the `Cipher` class as its argument.
-
* Specifically for **ciphers** the argument to the support query contains a
**transformation** (e.g., `AES/CBC/NoPadding`)
so one should take that into account when parsing the input argument to decide
which cipher is referenced - see
`SecurityProviderRegistrar.getEffectiveSecurityEntityName(Class<?>, String)`
helper method
diff --git a/docs/server-setup.md b/docs/server-setup.md
index 3e6b2db..8c89f56 100644
--- a/docs/server-setup.md
+++ b/docs/server-setup.md
@@ -26,12 +26,10 @@ There are a few things that need to be configured on the
server before being abl
**random** free port is selected by the O/S. In any case, once the server is
`start()`-ed one can query the
instance as to the assigned port via `sshd.getPort()`.
-
In this context, the listen bind address can also be specified explicitly via
`sshd.setHost(...some IP address...)`
that causes the server to bind to a specific network address rather than
**all** addresses (the default). Using
`"0.0.0.0"` as the bind address is also tantamount to binding to all addresses.
-
* `KeyPairProvider` - `sshd.setKeyPairProvider(...);` - sets the host's
private keys used for key exchange with
clients as well as representing the host's "identities". There are several
choices - one can load keys from standard
PEM files or generate them in the code. It's usually a good idea to save
generated keys, so that if the SSHD server
@@ -39,28 +37,23 @@ is restarted, the same keys will be used to authenticate
the server and avoid th
the host keys are modified. **Note**: saving key files in PEM format requires
that the [Bouncy Castle](https://www.bouncycastle.org/)
supporting artifacts be available in the code's classpath.
-
* `ShellFactory` - That's the part one usually has to write to customize the
SSHD server. The shell factory will
be used to create a new shell each time a user logs in and wants to run an
interactive shell. SSHD provides a simple
implementation that you can use if you want. This implementation will create a
process and delegate everything to it,
so it's mostly useful to launch the OS native shell. E.g.,
-
```java
sshd.setShellFactory(new ProcessShellFactory(new String[] { "/bin/sh",
"-i", "-l" }));
```
-
There is an out-of-the-box `InteractiveProcessShellFactory` that detects the
O/S and spawns the relevant shell. Note
that the `ShellFactory` is not required. If none is configured, any request
for an interactive shell will be denied to clients.
-
* `CommandFactory` - The `CommandFactory` provides the ability to run a
**single** direct command at a time instead
of an interactive session (it also uses a **different** channel type than
shells). It can be used **in addition** to the `ShellFactory`.
-
SSHD provides a `CommandFactory` to support SCP that can be configured in the
following way:
@@ -74,7 +67,6 @@ One can also use the `ScpCommandFactory` on top of one's own
`CommandFactory` by
of the `ScpCommandFactory`. The `ScpCommandFactory` will intercept SCP
commands and execute them by itself, while passing all
other commands to the delegate `CommandFactory`
-
```java
sshd.setCommandFactory(new ScpCommandFactory(myCommandFactory));
@@ -92,10 +84,8 @@ The SSHD server security layer has to be customized to suit
your needs. This lay
* `HostBasedAuthenticator` for host based authentication - [RFC 4252 section
9](https://www.ietf.org/rfc/rfc4252.txt)
* `KeyboardInteractiveAuthenticator` for user interactive authentication -
[RFC 4256](https://www.ietf.org/rfc/rfc4256.txt)
-
These custom classes can be configured on the SSHD server using the respective
setter methods:
-
```java
sshd.setPasswordAuthenticator(new MyPasswordAuthenticator());
@@ -155,4 +145,3 @@ In order to support customized user code for this feature,
the `ReservedSessionM
implement any kind of user-defined heartbeat. *Note:* if the user configured
such a mechanism, then the
`sendReservedHeartbeat` method **must** be implemented since the default
throws `UnsupportedOperationException`
which will cause the session to be terminated the 1st time the method is
invoked.
-
diff --git a/docs/sftp.md b/docs/sftp.md
index 070fc5c..a6f0373 100644
--- a/docs/sftp.md
+++ b/docs/sftp.md
@@ -27,8 +27,65 @@ On the server side, the following code needs to be added:
### `SftpEventListener`
-(See above more details...) - users may register an `SftpEventListener` (or
more...) in the `SftpSubsystemFactory` in
-order to monitor and even intervene in the susbsytem's functionality.
+Provides information about major SFTP protocol events. The provided
`File/DirectoryHandle` to the various callbacks can also be used to
+store user-defined attributes via its `AttributeStore` implementation. The
listener is registered at the `SftpSubsystemFactory`:
+
+```java
+ public class MySfpEventListener implements SftpEventListener {
+ private static final AttributeKey<SomeType> MY_SPECIAL_KEY = new
Attribute<SomeType>();
+
+ ...
+ @Override
+ public void opening(ServerSession session, String remoteHandle, Handle
localHandle) throws IOException {
+ localHandle.setAttribute(MY_SPECIAL_KEY, instanceOfSomeType);
+ }
+
+ @Override
+ public void writing(
+ ServerSession session, String remoteHandle, FileHandle
localHandle,
+ long offset, byte[] data, int dataOffset, int dataLen)
+ throws IOException {
+ SomeType myData = localHandle.getAttribute(MY_SPECIAL_KEY);
+ ...do something based on my data...
+ }
+ }
+
+
+ SftpSubsystemFactory factory = new SftpSubsystemFactory();
+ factory.addSftpEventListener(new MySftpEventListener());
+
sshd.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(factory));
+
+```
+
+**Note:** the attached attributes are automatically removed once handle has
been closed - regardless of
+whether the close attempt was successful or not. In other words, after
`SftpEventListener#closed` has been
+called, all attributes associated with the handle are cleared.
+
+### `SftpFileSystemAccessor`
+
+This is the abstraction providing the SFTP server subsystem access to files
and directories. The SFTP subsystem
+uses this abstraction to obtain file channels and/or directory streams. One
can override the default implementation
+and thus be able to track and/or intervene in all opened files and folders
throughout the SFTP server subsystem code.
+The accessor is registered/overwritten in via the `SftpSubSystemFactory`:
+
+```java
+
+ SftpSubsystemFactory factory = new SftpSubsystemFactory.Builder()
+ .withFileSystemAccessor(new MySftpFileSystemAccessor())
+ .build();
+ server.setSubsystemFactories(Collections.singletonList(factory));
+
+```
+
+**Note:**
+
+* Closing of file channel/directory streams created by the accessor are also
closed
+via callbacks to the same accessor
+
+* When closing a file channel that may have been potentially modified, the
default implementation
+forces a synchronization of the data with the file-system. This behavior can
be modified
+by setting the `sftp-auto-fsync-on-close` property to *false* (or by providing
a customized implementation
+that involves other considerations as well).
### Client-side SFTP
@@ -45,7 +102,6 @@ In order to obtain an `SftpClient` instance one needs to use
an `SftpClientFacto
A default client factory implementations is provided in the module - see
`SftpClientFactory.instance()`
-
### Using a custom `SftpClientFactory`
The code creates `SftpClient`-s and `SftpFileSystem`-s using a default
built-in `SftpClientFactory` instance (see
@@ -70,7 +126,6 @@ implementations - e.g., in order to override some default
behavior - e.g.:
### Version selection via `SftpVersionSelector`
-
The SFTP subsystem code supports versions 3-6 (inclusive), and by default
attempts to negotiate the highest
possible one - on both client and server code. The user can intervene and
force a specific version or a narrower
range.
@@ -98,7 +153,7 @@ range.
```
-On the server side, version selection restriction is more complex - please
remember that the according to the
+On the server side, version selection restriction is more complex - please
remember that according to the
protocol specification
>> The server responds with a SSH_FXP_VERSION packet, supplying the lowest (!)
>> of its own and the client's version number
@@ -214,7 +269,8 @@ configuration keys and values.
params.put("param2", value2);
// The value of 'param1' is overridden in the URI
- try (FileSystem fs = FileSystems.newFileSystem(new
URI("sftp://user:password@host/some/remote/path?param1=otherValue1", params)) {
+ try (FileSystem fs = FileSystems.newFileSystem(
+ new
URI("sftp://user:password@host/some/remote/path?param1=otherValue1", params)) {
Path remotePath = fs.getPath("/some/remote/path");
... work with the remote path...
}
@@ -284,23 +340,25 @@ UTF-8 is used. **Note:** the value can be a charset name
or a `java.nio.charset.
PropertyResolverUtils.updateProperty(client,
SftpClient.NAME_DECODING_CHARSET, "ISO-8859-8");
try (ClientSession session = client.connect(...)) {
- // default for ALL SFTP clients obtained through the session -
overrides client setting
- PropertyResolverUtils.updateProperty(session,
SftpClient.NAME_DECODING_CHARSET, "ISO-8859-4");
- session.authenticate(...);
-
- SftpClientFactory factory = SftpClientFactory.instance();
- try (SftpClient sftp = factory.createSftpClient(session)) {
- for (DirEntry entry : sftp.readDir(...some path...)) {
- ...handle entry assuming ISO-8859-4 (inherited from the
session) encoded names...
- }
-
- // override the inherited default from the session
- sftp.setNameDecodingCharset(Charset.forName("ISO-8859-1"));
-
- for (DirEntry entry : sftp.readDir(...some other path...)) {
- ...handle entry assuming ISO-8859-1 encoded names...
- }
- }
+ session.addPasswordIdentity(password);
+ session.auth().verify(timeout);
+
+ // default for ALL SFTP clients obtained through the session -
overrides client setting
+ PropertyResolverUtils.updateProperty(session,
SftpClient.NAME_DECODING_CHARSET, "ISO-8859-4");
+
+ SftpClientFactory factory = SftpClientFactory.instance();
+ try (SftpClient sftp = factory.createSftpClient(session)) {
+ for (DirEntry entry : sftp.readDir(...some path...)) {
+ ...handle entry assuming ISO-8859-4 (inherited from the
session) encoded names...
+ }
+
+ // override the inherited default from the session
+ sftp.setNameDecodingCharset(Charset.forName("ISO-8859-1"));
+
+ for (DirEntry entry : sftp.readDir(...some other path...)) {
+ ...handle entry assuming ISO-8859-1 encoded names...
+ }
+ }
}
```
@@ -326,7 +384,6 @@ Furthermore several [OpenSSH SFTP
extensions](https://github.com/openssh/openssh
* `[email protected]`
* `[email protected]`
-
On the server side, the reported standard extensions are configured via the
`SftpSubsystem.CLIENT_EXTENSIONS_PROP` configuration
key, and the _OpenSSH_ ones via the `SftpSubsystem.OPENSSH_EXTENSIONS_PROP`.
@@ -335,7 +392,6 @@ to query the client whether the remote server supports the
specific extension an
can easily add support for more extensions in a similar manner as the existing
ones by implementing an appropriate `ExtensionParser`
and then registering it at the `ParserUtils` - see the existing ones for
details how this can be achieved.
-
```java
// properietary/special extension parser
@@ -371,7 +427,6 @@ and then registering it at the `ParserUtils` - see the
existing ones for details
One can skip all the conditional code if a specific known extension is
required:
-
```java
try (ClientSession session = client.connect(username, host,
port).verify(timeout).getSession()) {