Compare commits

...

13 Commits

Author SHA1 Message Date
Jeroen van Erp
dc6b20772b Prepare release 0.38.0 2024-01-02 09:26:09 +01:00
Henning Pöttker
81e87a4d35 Add unit tests of strict key exchange extension (#918) 2023-12-23 10:26:29 +01:00
Henning Pöttker
a262f51900 Implement OpenSSH strict key exchange extension (#917) 2023-12-21 22:33:54 +01:00
David Kocher
50c753dc58 Fixed writing known hosts key string (#903)
* Fix #902.

* Add test.
2023-11-21 21:24:28 +01:00
Raul Santelices
1c547886c8 Fix for Remote port forwarding buffers can grow without limits (issue #658) (#913)
* Fix for Remote port forwarding buffers can grow without limits (issue #658)

* Update test classes to use JUnit 5

* Fix MB computation
2023-11-21 21:21:35 +01:00
Jeroen van Erp
b7dc869a13 Moved host verification tests to JUnit5 (#906) 2023-10-23 12:24:29 +02:00
Florian Klemenz
4774721b49 adds fallback to posix-rename@openssh.com extension if possible and c… (#827)
* adds fallback to posix-rename@openssh.com extension if possible and communicates possible problems with flags to the developer

* Adds '{}' around if/else statements

* adds basic tests for file rename

* fix comments

* fixes indentation

* adds helper methods to make existing sftp rename tests more concise

* adds basic test for atomic rewrite

* adds possibility to request a specific client version (e.g. for testing purposes)

* adds testcases for SFTP rename flags fallback behaviour

* refactoring to make SFTPEngine.init(int requestedVersion) protected

---------

Co-authored-by: Florian Klemenz <florian.klemenz@fau.de>
Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2023-10-23 10:46:14 +02:00
exceptionfactory
542bb35bda Add ChaCha20-Poly1305 Support for OpenSSH Keys (#904)
* Add ChaCha20-Poly1305 Support for OpenSSH Keys

- Updated ChachaPolyCipher to support decryption without Additional Authenticated Data

* Added test for ChachaPolyCipher without AAD

* Streamlined ChachaPolyCipher.update() method
2023-10-16 22:54:22 +02:00
Jeroen van Erp
3b67d2b476 Prepare release 0.37.0 2023-10-11 22:56:18 +02:00
exceptionfactory
9b9b208434 Add AES-GCM Support for OpenSSH Private Keys (#899)
* Added AES-GCM Support for OpenSSH Private Keys

* Small simplification

Signed-off-by: Jeroen van Erp <jeroen@hierynomus.com>

---------

Signed-off-by: Jeroen van Erp <jeroen@hierynomus.com>
Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2023-10-11 22:48:02 +02:00
Jeroen van Erp
a3cce0d2f9 Fix bunch of warnings 2023-10-11 22:41:50 +02:00
Henning Pöttker
5d040dd4bb Fix zlib compression (#901)
* add failing integrationtest for https://github.com/hierynomus/sshj/issues/893

* Fix zlib compression

---------

Co-authored-by: Malte Otten <malte.otten@emsysvpp.de>
2023-10-11 20:57:20 +02:00
exceptionfactory
461c0e46d4 Improved malformed file handling for OpenSSH Private Keys (#898) 2023-10-09 09:17:01 +02:00
43 changed files with 2145 additions and 418 deletions

View File

@@ -1,7 +1,7 @@
= sshj - SSHv2 library for Java
Jeroen van Erp
:sshj_groupid: com.hierynomus
:sshj_version: 0.36.0
:sshj_version: 0.38.0
:source-highlighter: pygments
image:https://github.com/hierynomus/sshj/actions/workflows/gradle.yml/badge.svg[link="https://github.com/hierynomus/sshj/actions/workflows/gradle.yml"]
@@ -10,6 +10,8 @@ image:https://codecov.io/gh/hierynomus/sshj/branch/master/graph/badge.svg["codec
image:http://www.javadoc.io/badge/com.hierynomus/sshj.svg?color=blue["JavaDocs", link="http://www.javadoc.io/doc/com.hierynomus/sshj"]
image:https://maven-badges.herokuapp.com/maven-central/com.hierynomus/sshj/badge.svg["Maven Central",link="https://maven-badges.herokuapp.com/maven-central/com.hierynomus/sshj"]
WARNING: SSHJ versions up to and including 0.37.0 are vulnerable to https://nvd.nist.gov/vuln/detail/CVE-2023-48795[CVE-2023-48795 - Terrapin]. Please upgrade to 0.38.0 or higher.
To get started, have a look at one of the examples. Hopefully you will find the API pleasant to work with :)
== Getting SSHJ
@@ -46,7 +48,7 @@ If your project is built using another build tool that uses the Maven Central re
In the `examples` directory, there is a separate Maven project that shows how the library can be used in some sample cases. If you want to run them, follow these guidelines:
. Install http://maven.apache.org/[Maven 2.2.1] or up.
. Clone the Overthere repository.
. Clone the SSHJ repository.
. Go into the `examples` directory and run the command `mvn eclipse:eclipse`.
. Import the `examples` project into Eclipse.
. Change the login details in the example classes (address, username and password) and run them!
@@ -108,6 +110,18 @@ Issue tracker: https://github.com/hierynomus/sshj/issues
Fork away!
== Release history
SSHJ 0.38.0 (2024-01-02)::
* Mitigated CVE-2023-48795 - Terrapin
* Merged https://github.com/hierynomus/sshj/pull/917[#917]: Implement OpenSSH strict key exchange extension
* Merged https://github.com/hierynomus/sshj/pull/903[#903]: Fix for writing known hosts key string
* Merged https://github.com/hierynomus/sshj/pull/913[#913]: Prevent remote port forwarding buffers to grow without bounds
* Moved tess to JUnit5
* Merged https://github.com/hierynomus/sshj/pull/827[#827]: Fallback to posix-rename@openssh.com extension if available
* Merged https://github.com/hierynomus/sshj/pull/904[#904]: Add ChaCha20-Poly1305 support for OpenSSH keys
SSHJ 0.37.0 (2023-10-11)::
* Merged https://github.com/hierynomus/sshj/pull/899[#899]: Add support for AES-GCM OpenSSH private keys
* Merged https://github.com/hierynomus/sshj/pull/901[#901]: Fix ZLib compression bug
* Merged https://github.com/hierynomus/sshj/pull/898[#898]: Improved malformed file handling for OpenSSH private keys
SSHJ 0.36.0 (2023-09-04)::
* Rewrote Integration tests to JUnit5
* Merged https://github.com/hierynomus/sshj/pull/851[#851]: Fix race condition in key exchange causing intermittent SSH_MSG_UNIMPLEMENTED

View File

@@ -24,7 +24,7 @@
<groupId>com.hierynomus</groupId>
<artifactId>sshj-examples</artifactId>
<packaging>jar</packaging>
<version>0.33.0</version>
<version>0.37.0</version>
<name>sshj-examples</name>
<description>Examples for SSHv2 library for Java</description>

View File

@@ -146,8 +146,9 @@ public class SshdContainer extends GenericContainer<SshdContainer> {
.withFileFromString("sshd_config", sshdConfig.build());
}
@Override
public void accept(@NotNull DockerfileBuilder builder) {
builder.from("alpine:3.18.3");
builder.from("alpine:3.19.0");
builder.run("apk add --no-cache openssh");
builder.expose(22);
builder.copy("entrypoint.sh", "/entrypoint.sh");
@@ -214,6 +215,9 @@ public class SshdContainer extends GenericContainer<SshdContainer> {
case STDERR:
logger().info("sshd stderr: {}", outputFrame.getUtf8String().stripTrailing());
break;
case END:
break;
}
});
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hierynomus.sshj.sftp;
import com.hierynomus.sshj.SshdContainer;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.InMemorySourceFile;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
@Testcontainers
public class PutFileCompressedTest {
private static class TestInMemorySourceFile extends InMemorySourceFile {
private final String name;
private final byte[] data;
public TestInMemorySourceFile(String name, byte[] data) {
this.name = name;
this.data = data;
}
@Override
public String getName() {
return name;
}
@Override
public long getLength() {
return data.length;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
}
@Container
private static SshdContainer sshd = new SshdContainer();
@Test
public void shouldPutCompressedFile_GH893() throws Throwable {
try (SSHClient client = sshd.getConnectedClient()) {
client.authPublickey("sshj", "src/test/resources/id_rsa");
client.useCompression();
try (SFTPClient sftp = client.newSFTPClient()) {
String filename = "test.txt";
// needs to be a larger file for bug taking effect
byte[] content = new byte[5000];
Random r = new Random(1);
r.nextBytes(content);
sftp.put(new TestInMemorySourceFile(filename,content), "/home/sshj/");
}
}
}
}

View File

@@ -26,7 +26,6 @@ import org.junit.jupiter.params.provider.ValueSource;
import com.hierynomus.sshj.SshdContainer;
import com.hierynomus.sshj.SshdContainer.SshdConfigBuilder;
import net.schmizz.sshj.Config;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.transport.verification.OpenSSHKnownHosts;

View File

@@ -26,7 +26,6 @@ import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import com.hierynomus.sshj.SshdContainer;
import com.hierynomus.sshj.transport.mac.Macs;
import net.schmizz.sshj.Config;
import net.schmizz.sshj.DefaultConfig;

View File

@@ -0,0 +1,111 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hierynomus.sshj.transport.kex;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.hierynomus.sshj.SshdContainer;
import net.schmizz.sshj.SSHClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Testcontainers
class StrictKeyExchangeTest {
@Container
private static final SshdContainer sshd = new SshdContainer();
private final List<Logger> watchedLoggers = new ArrayList<>();
private final ListAppender<ILoggingEvent> logWatcher = new ListAppender<>();
@BeforeEach
void setUpLogWatcher() {
logWatcher.start();
setUpLogger("net.schmizz.sshj.transport.Decoder");
setUpLogger("net.schmizz.sshj.transport.Encoder");
setUpLogger("net.schmizz.sshj.transport.KeyExchanger");
}
@AfterEach
void tearDown() {
watchedLoggers.forEach(Logger::detachAndStopAllAppenders);
}
private void setUpLogger(String className) {
Logger logger = ((Logger) LoggerFactory.getLogger(className));
logger.addAppender(logWatcher);
watchedLoggers.add(logger);
}
@Test
void strictKeyExchange() throws Throwable {
try (SSHClient client = sshd.getConnectedClient()) {
client.authPublickey("sshj", "src/itest/resources/keyfiles/id_rsa_opensshv1");
assertTrue(client.isAuthenticated());
}
List<String> keyExchangerLogs = getLogs("KeyExchanger");
assertThat(keyExchangerLogs).containsSequence(
"Initiating key exchange",
"Sending SSH_MSG_KEXINIT",
"Received SSH_MSG_KEXINIT",
"Enabling strict key exchange extension"
);
List<String> decoderLogs = getLogs("Decoder").stream()
.map(log -> log.split(":")[0])
.collect(Collectors.toList());
assertThat(decoderLogs).containsExactly(
"Received packet #0",
"Received packet #1",
"Received packet #2",
"Received packet #0",
"Received packet #1",
"Received packet #2",
"Received packet #3"
);
List<String> encoderLogs = getLogs("Encoder").stream()
.map(log -> log.split(":")[0])
.collect(Collectors.toList());
assertThat(encoderLogs).containsExactly(
"Encoding packet #0",
"Encoding packet #1",
"Encoding packet #2",
"Encoding packet #0",
"Encoding packet #1",
"Encoding packet #2",
"Encoding packet #3"
);
}
private List<String> getLogs(String className) {
return logWatcher.list.stream()
.filter(event -> event.getLoggerName().endsWith(className))
.map(ILoggingEvent::getFormattedMessage)
.collect(Collectors.toList());
}
}

View File

@@ -22,9 +22,6 @@ import net.schmizz.sshj.signature.SignatureDSA;
import net.schmizz.sshj.signature.SignatureECDSA;
import net.schmizz.sshj.signature.SignatureRSA;
import java.util.Arrays;
import java.util.List;
public class KeyAlgorithms {
public static Factory SSHRSA() { return new Factory("ssh-rsa", new SignatureRSA.FactorySSHRSA(), KeyType.RSA); }

View File

@@ -16,9 +16,8 @@
package com.hierynomus.sshj.transport.cipher;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import javax.crypto.spec.IvParameterSpec;
@@ -82,8 +81,7 @@ public class ChachaPolyCipher extends BaseCipher {
}
@Override
protected void initCipher(javax.crypto.Cipher cipher, Mode mode, byte[] key, byte[] iv)
throws InvalidKeyException, InvalidAlgorithmParameterException {
protected void initCipher(javax.crypto.Cipher cipher, Mode mode, byte[] key, byte[] iv) {
this.mode = mode;
cipherKey = getKeySpec(Arrays.copyOfRange(key, 0, CHACHA_KEY_SIZE));
@@ -127,28 +125,34 @@ public class ChachaPolyCipher extends BaseCipher {
@Override
public void update(byte[] input, int inputOffset, int inputLen) {
if (inputOffset != AAD_LENGTH) {
if (inputOffset != 0 && inputOffset != AAD_LENGTH) {
throw new IllegalArgumentException("updateAAD called with inputOffset " + inputOffset);
}
final int macInputLength = AAD_LENGTH + inputLen;
final int macInputLength = inputOffset + inputLen;
if (mode == Mode.Decrypt) {
byte[] macInput = new byte[macInputLength];
System.arraycopy(encryptedAad, 0, macInput, 0, AAD_LENGTH);
System.arraycopy(input, AAD_LENGTH, macInput, AAD_LENGTH, inputLen);
final byte[] macInput = new byte[macInputLength];
byte[] expectedPolyTag = mac.doFinal(macInput);
byte[] actualPolyTag = Arrays.copyOfRange(input, macInputLength, macInputLength + POLY_TAG_LENGTH);
if (!Arrays.equals(actualPolyTag, expectedPolyTag)) {
if (inputOffset == 0) {
// Handle decryption without AAD
System.arraycopy(input, 0, macInput, 0, inputLen);
} else {
// Handle decryption with previous AAD from updateAAD()
System.arraycopy(encryptedAad, 0, macInput, 0, AAD_LENGTH);
System.arraycopy(input, AAD_LENGTH, macInput, AAD_LENGTH, inputLen);
}
final byte[] expectedPolyTag = mac.doFinal(macInput);
final byte[] actualPolyTag = Arrays.copyOfRange(input, macInputLength, macInputLength + POLY_TAG_LENGTH);
if (!MessageDigest.isEqual(actualPolyTag, expectedPolyTag)) {
throw new SSHRuntimeException("MAC Error");
}
}
try {
cipher.update(input, AAD_LENGTH, inputLen, input, AAD_LENGTH);
cipher.update(input, inputOffset, inputLen, input, inputOffset);
} catch (GeneralSecurityException e) {
throw new SSHRuntimeException("Error updating data through cipher", e);
throw new SSHRuntimeException("ChaCha20 cipher processing failed", e);
}
if (mode == Mode.Encrypt) {

View File

@@ -18,6 +18,8 @@ package com.hierynomus.sshj.userauth.keyprovider;
import com.hierynomus.sshj.common.KeyAlgorithm;
import com.hierynomus.sshj.common.KeyDecryptionFailedException;
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
import com.hierynomus.sshj.transport.cipher.ChachaPolyCiphers;
import com.hierynomus.sshj.transport.cipher.GcmCiphers;
import net.i2p.crypto.eddsa.EdDSAPrivateKey;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec;
@@ -36,6 +38,7 @@ import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import com.hierynomus.sshj.userauth.keyprovider.bcrypt.BCrypt;
import org.bouncycastle.openssl.EncryptionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -47,24 +50,43 @@ import java.io.Reader;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* Reads a key file in the new OpenSSH format.
* The format is described in the following document: https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
*/
public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
private static final Logger logger = LoggerFactory.getLogger(OpenSSHKeyV1KeyFile.class);
private static final String BEGIN = "-----BEGIN ";
private static final String END = "-----END ";
private static final byte[] AUTH_MAGIC = "openssh-key-v1\0".getBytes();
public static final String OPENSSH_PRIVATE_KEY = "OPENSSH PRIVATE KEY-----";
public static final String BCRYPT = "bcrypt";
private static final String NONE_CIPHER = "none";
private static final Map<String, Factory.Named<Cipher>> SUPPORTED_CIPHERS = new HashMap<>();
static {
SUPPORTED_CIPHERS.put(BlockCiphers.TripleDESCBC().getName(), BlockCiphers.TripleDESCBC());
SUPPORTED_CIPHERS.put(BlockCiphers.AES128CBC().getName(), BlockCiphers.AES128CBC());
SUPPORTED_CIPHERS.put(BlockCiphers.AES192CBC().getName(), BlockCiphers.AES192CBC());
SUPPORTED_CIPHERS.put(BlockCiphers.AES256CBC().getName(), BlockCiphers.AES256CBC());
SUPPORTED_CIPHERS.put(BlockCiphers.AES128CTR().getName(), BlockCiphers.AES128CTR());
SUPPORTED_CIPHERS.put(BlockCiphers.AES192CTR().getName(), BlockCiphers.AES192CTR());
SUPPORTED_CIPHERS.put(BlockCiphers.AES256CTR().getName(), BlockCiphers.AES256CTR());
SUPPORTED_CIPHERS.put(GcmCiphers.AES256GCM().getName(), GcmCiphers.AES256GCM());
SUPPORTED_CIPHERS.put(GcmCiphers.AES128GCM().getName(), GcmCiphers.AES128GCM());
SUPPORTED_CIPHERS.put(ChachaPolyCiphers.CHACHA_POLY_OPENSSH().getName(), ChachaPolyCiphers.CHACHA_POLY_OPENSSH());
}
private PublicKey pubKey;
public static class Factory
@@ -98,19 +120,19 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
@Override
protected KeyPair readKeyPair() throws IOException {
BufferedReader reader = new BufferedReader(resource.getReader());
final BufferedReader reader = new BufferedReader(resource.getReader());
try {
if (!checkHeader(reader)) {
throw new IOException("This key is not in 'openssh-key-v1' format");
if (checkHeader(reader)) {
final String encodedPrivateKey = readEncodedKey(reader);
byte[] decodedPrivateKey = Base64.getDecoder().decode(encodedPrivateKey);
final PlainBuffer bufferedPrivateKey = new PlainBuffer(decodedPrivateKey);
return readDecodedKeyPair(bufferedPrivateKey);
} else {
final String message = String.format("File header not found [%s%s]", BEGIN, OPENSSH_PRIVATE_KEY);
throw new IOException(message);
}
String keyFile = readKeyFile(reader);
byte[] decode = Base64.getDecoder().decode(keyFile);
PlainBuffer keyBuffer = new PlainBuffer(decode);
return readDecodedKeyPair(keyBuffer);
} catch (GeneralSecurityException e) {
throw new SSHRuntimeException(e);
} catch (final GeneralSecurityException e) {
throw new SSHRuntimeException("Read OpenSSH Version 1 Key failed", e);
} finally {
IOUtils.closeQuietly(reader);
}
@@ -135,88 +157,143 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
int nrKeys = keyBuffer.readUInt32AsInt(); // int number of keys N; Should be 1
if (nrKeys != 1) {
throw new IOException("We don't support having more than 1 key in the file (yet).");
final String message = String.format("OpenSSH Private Key number of keys not supported [%d]", nrKeys);
throw new IOException(message);
}
PublicKey publicKey = pubKey;
if (publicKey == null) {
publicKey = readPublicKey(new PlainBuffer(keyBuffer.readBytes()));
}
else {
} else {
keyBuffer.readBytes();
}
PlainBuffer privateKeyBuffer = new PlainBuffer(keyBuffer.readBytes()); // string (possibly) encrypted, padded list of private keys
if ("none".equals(cipherName)) {
logger.debug("Reading unencrypted keypair");
final byte[] privateKeyEncoded = keyBuffer.readBytes();
final PlainBuffer privateKeyBuffer = new PlainBuffer(privateKeyEncoded);
if (NONE_CIPHER.equals(cipherName)) {
return readUnencrypted(privateKeyBuffer, publicKey);
} else {
logger.info("Keypair is encrypted with: " + cipherName + ", " + kdfName + ", " + Arrays.toString(kdfOptions));
final byte[] encryptedPrivateKey = readEncryptedPrivateKey(privateKeyEncoded, keyBuffer);
while (true) {
PlainBuffer decryptionBuffer = new PlainBuffer(privateKeyBuffer);
PlainBuffer decrypted = decryptBuffer(decryptionBuffer, cipherName, kdfName, kdfOptions);
final byte[] encrypted = encryptedPrivateKey.clone();
try {
final PlainBuffer decrypted = decryptPrivateKey(encrypted, privateKeyEncoded.length, cipherName, kdfName, kdfOptions);
return readUnencrypted(decrypted, publicKey);
} catch (KeyDecryptionFailedException e) {
if (pwdf == null || !pwdf.shouldRetry(resource))
throw e;
}
}
// throw new IOException("Cannot read encrypted keypair with " + cipherName + " yet.");
}
}
private PlainBuffer decryptBuffer(PlainBuffer privateKeyBuffer, String cipherName, String kdfName, byte[] kdfOptions) throws IOException {
Cipher cipher = createCipher(cipherName);
initializeCipher(kdfName, kdfOptions, cipher);
byte[] array = privateKeyBuffer.array();
cipher.update(array, 0, privateKeyBuffer.available());
return new PlainBuffer(array);
private byte[] readEncryptedPrivateKey(final byte[] privateKeyEncoded, final PlainBuffer inputBuffer) throws Buffer.BufferException {
final byte[] encryptedPrivateKey;
final int bufferRemaining = inputBuffer.available();
if (bufferRemaining == 0) {
encryptedPrivateKey = privateKeyEncoded;
} else {
// Read Authentication Tag for AES-GCM or ChaCha20-Poly1305
final byte[] authenticationTag = new byte[bufferRemaining];
inputBuffer.readRawBytes(authenticationTag);
final int encryptedBufferLength = privateKeyEncoded.length + authenticationTag.length;
final PlainBuffer encryptedBuffer = new PlainBuffer(encryptedBufferLength);
encryptedBuffer.putRawBytes(privateKeyEncoded);
encryptedBuffer.putRawBytes(authenticationTag);
encryptedPrivateKey = new byte[encryptedBufferLength];
encryptedBuffer.readRawBytes(encryptedPrivateKey);
}
return encryptedPrivateKey;
}
private void initializeCipher(String kdfName, byte[] kdfOptions, Cipher cipher) throws Buffer.BufferException {
private PlainBuffer decryptPrivateKey(final byte[] privateKey, final int privateKeyLength, final String cipherName, final String kdfName, final byte[] kdfOptions) throws IOException {
try {
final Cipher cipher = createCipher(cipherName);
initializeCipher(kdfName, kdfOptions, cipher);
cipher.update(privateKey, 0, privateKeyLength);
} catch (final SSHRuntimeException e) {
final String message = String.format("OpenSSH Private Key decryption failed with cipher [%s]", cipherName);
throw new KeyDecryptionFailedException(new EncryptionException(message, e));
}
final PlainBuffer decryptedPrivateKey = new PlainBuffer(privateKeyLength);
decryptedPrivateKey.putRawBytes(privateKey, 0, privateKeyLength);
return decryptedPrivateKey;
}
private void initializeCipher(final String kdfName, final byte[] kdfOptions, final Cipher cipher) throws Buffer.BufferException {
if (kdfName.equals(BCRYPT)) {
PlainBuffer opts = new PlainBuffer(kdfOptions);
final PlainBuffer bufferedOptions = new PlainBuffer(kdfOptions);
byte[] passphrase = new byte[0];
if (pwdf != null) {
CharBuffer charBuffer = CharBuffer.wrap(pwdf.reqPassword(null));
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
final CharBuffer charBuffer = CharBuffer.wrap(pwdf.reqPassword(null));
final ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(charBuffer);
passphrase = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
Arrays.fill(charBuffer.array(), '\u0000');
Arrays.fill(byteBuffer.array(), (byte) 0);
}
byte[] keyiv = new byte[cipher.getIVSize()+ cipher.getBlockSize()];
new BCrypt().pbkdf(passphrase, opts.readBytes(), opts.readUInt32AsInt(), keyiv);
final int ivSize = cipher.getIVSize();
final int blockSize = cipher.getBlockSize();
final int parameterSize = ivSize + blockSize;
final byte[] keyIvParameters = new byte[parameterSize];
final byte[] salt = bufferedOptions.readBytes();
final int iterations = bufferedOptions.readUInt32AsInt();
new BCrypt().pbkdf(passphrase, salt, iterations, keyIvParameters);
Arrays.fill(passphrase, (byte) 0);
byte[] key = Arrays.copyOfRange(keyiv, 0, cipher.getBlockSize());
byte[] iv = Arrays.copyOfRange(keyiv, cipher.getBlockSize(), cipher.getIVSize() + cipher.getBlockSize());
final byte[] key = Arrays.copyOfRange(keyIvParameters, 0, blockSize);
final byte[] iv = Arrays.copyOfRange(keyIvParameters, blockSize, parameterSize);
cipher.init(Cipher.Mode.Decrypt, key, iv);
} else {
throw new IllegalStateException("No support for KDF '" + kdfName + "'.");
final String message = String.format("OpenSSH Private Key encryption KDF not supported [%s]", kdfName);
throw new IllegalStateException(message);
}
}
private Cipher createCipher(String cipherName) {
if (cipherName.equals(BlockCiphers.AES256CTR().getName())) {
return BlockCiphers.AES256CTR().create();
} else if (cipherName.equals(BlockCiphers.AES256CBC().getName())) {
return BlockCiphers.AES256CBC().create();
} else if (cipherName.equals(BlockCiphers.AES128CBC().getName())) {
return BlockCiphers.AES128CBC().create();
private Cipher createCipher(final String cipherName) {
final Cipher cipher;
if (SUPPORTED_CIPHERS.containsKey(cipherName)) {
final Factory.Named<Cipher> cipherFactory = SUPPORTED_CIPHERS.get(cipherName);
cipher = cipherFactory.create();
} else {
final String message = String.format("OpenSSH Key encryption cipher not supported [%s]", cipherName);
throw new IllegalStateException(message);
}
throw new IllegalStateException("Cipher '" + cipherName + "' not currently implemented for openssh-key-v1 format");
return cipher;
}
private PublicKey readPublicKey(final PlainBuffer plainBuffer) throws Buffer.BufferException, GeneralSecurityException {
return KeyType.fromString(plainBuffer.readString()).readPubKeyFromBuffer(plainBuffer);
}
private String readKeyFile(final BufferedReader reader) throws IOException {
StringBuilder sb = new StringBuilder();
private String readEncodedKey(final BufferedReader reader) throws IOException {
final StringBuilder builder = new StringBuilder();
boolean footerFound = false;
String line = reader.readLine();
while (!line.startsWith(END)) {
sb.append(line);
while (line != null) {
if (line.startsWith(END)) {
footerFound = true;
break;
}
builder.append(line);
line = reader.readLine();
}
return sb.toString();
if (footerFound) {
return builder.toString();
} else {
final String message = String.format("File footer not found [%s%s]", END, OPENSSH_PRIVATE_KEY);
throw new IOException(message);
}
}
private boolean checkHeader(final BufferedReader reader) throws IOException {
@@ -239,12 +316,12 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
int checkInt1 = keyBuffer.readUInt32AsInt(); // uint32 checkint1
int checkInt2 = keyBuffer.readUInt32AsInt(); // uint32 checkint2
if (checkInt1 != checkInt2) {
throw new KeyDecryptionFailedException();
throw new KeyDecryptionFailedException(new EncryptionException("OpenSSH Private Key integer comparison failed"));
}
// The private key section contains both the public key and the private key
String keyType = keyBuffer.readString(); // string keytype
KeyType kt = KeyType.fromString(keyType);
logger.info("Read key type: {}", keyType, kt);
KeyPair kp;
switch (kt) {
case ED25519:

View File

@@ -200,4 +200,8 @@ public interface Config {
* See {@link #isVerifyHostKeyCertificates()}.
*/
void setVerifyHostKeyCertificates(boolean value);
int getMaxCircularBufferSize();
void setMaxCircularBufferSize(int maxCircularBufferSize);
}

View File

@@ -49,6 +49,8 @@ public class ConfigImpl
private boolean waitForServerIdentBeforeSendingClientIdent = false;
private LoggerFactory loggerFactory;
private boolean verifyHostKeyCertificates = true;
// HF-982: default to 16MB buffers.
private int maxCircularBufferSize = 16 * 1024 * 1024;
@Override
public List<Factory.Named<Cipher>> getCipherFactories() {
@@ -175,6 +177,16 @@ public class ConfigImpl
return loggerFactory;
}
@Override
public int getMaxCircularBufferSize() {
return maxCircularBufferSize;
}
@Override
public void setMaxCircularBufferSize(int maxCircularBufferSize) {
this.maxCircularBufferSize = maxCircularBufferSize;
}
@Override
public void setLoggerFactory(LoggerFactory loggerFactory) {
this.loggerFactory = loggerFactory;

View File

@@ -28,7 +28,6 @@ import net.schmizz.sshj.connection.channel.forwarded.RemotePortForwarder.Forward
import net.schmizz.sshj.connection.channel.forwarded.X11Forwarder;
import net.schmizz.sshj.connection.channel.forwarded.X11Forwarder.X11Channel;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.sftp.SFTPEngine;
import net.schmizz.sshj.sftp.StatefulSFTPClient;
import net.schmizz.sshj.transport.Transport;
import net.schmizz.sshj.transport.TransportException;
@@ -733,7 +732,7 @@ public class SSHClient
throws IOException {
checkConnected();
checkAuthenticated();
return new SFTPClient(new SFTPEngine(this).init());
return new SFTPClient(this);
}
/**
@@ -746,7 +745,7 @@ public class SSHClient
throws IOException {
checkConnected();
checkAuthenticated();
return new StatefulSFTPClient(new SFTPEngine(this).init());
return new StatefulSFTPClient(this);
}
/**

View File

@@ -0,0 +1,194 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.common;
public class CircularBuffer<T extends CircularBuffer<T>> {
public static class CircularBufferException
extends SSHException {
public CircularBufferException(String message) {
super(message);
}
}
public static final class PlainCircularBuffer
extends CircularBuffer<PlainCircularBuffer> {
public PlainCircularBuffer(int size, int maxSize) {
super(size, maxSize);
}
}
/**
* Maximum size of the internal array (one plus the maximum capacity of the buffer).
*/
private final int maxSize;
/**
* Internal array for the data. All bytes minus one can be used to avoid empty vs full ambiguity when rpos == wpos.
*/
private byte[] data;
/**
* Next read position. Wraps around the end of the internal array. When it reaches wpos, the buffer becomes empty.
* Can take the value data.length, which is equivalent to 0.
*/
private int rpos;
/**
* Next write position. Wraps around the end of the internal array. If it is equal to rpos, then the buffer is
* empty; the code does not allow wpos to reach rpos from the left. This implies that the buffer can store up to
* data.length - 1 bytes. Can take the value data.length, which is equivalent to 0.
*/
private int wpos;
/**
* Determines the size to which to grow the internal array.
*/
private int getNextSize(int currentSize) {
// Use next power of 2.
int nextSize = 1;
while (nextSize < currentSize) {
nextSize <<= 1;
if (nextSize <= 0) {
return maxSize;
}
}
return Math.min(nextSize, maxSize); // limit to max size
}
/**
* Creates a new circular buffer of the given size. The capacity of the buffer is one less than the size/
*/
public CircularBuffer(int size, int maxSize) {
this.maxSize = maxSize;
if (size > maxSize) {
throw new IllegalArgumentException(
String.format("Initial requested size %d larger than maximum size %d", size, maxSize));
}
int initialSize = getNextSize(size);
this.data = new byte[initialSize];
this.rpos = 0;
this.wpos = 0;
}
/**
* Data available in the buffer for reading.
*/
public int available() {
int available = wpos - rpos;
return available >= 0 ? available : available + data.length; // adjust if wpos is left of rpos
}
private void ensureAvailable(int a)
throws CircularBufferException {
if (available() < a) {
throw new CircularBufferException("Underflow");
}
}
/**
* Returns how many more bytes this buffer can receive.
*/
public int maxPossibleRemainingCapacity() {
// Remaining capacity is one less than remaining space to ensure that wpos does not reach rpos from the left.
int remaining = rpos - wpos - 1;
if (remaining < 0) {
remaining += data.length; // adjust if rpos is left of wpos
}
// Add the maximum amount the internal array can grow.
return remaining + maxSize - data.length;
}
/**
* If the internal array does not have room for "capacity" more bytes, resizes the array to make that room.
*/
void ensureCapacity(int capacity) throws CircularBufferException {
int available = available();
int remaining = data.length - available;
// If capacity fits exactly in the remaining space, expand it; otherwise, wpos would reach rpos from the left.
if (remaining <= capacity) {
int neededSize = available + capacity + 1;
int nextSize = getNextSize(neededSize);
if (nextSize < neededSize) {
throw new CircularBufferException("Attempted overflow");
}
byte[] tmp = new byte[nextSize];
// Copy data to the beginning of the new array.
if (wpos >= rpos) {
System.arraycopy(data, rpos, tmp, 0, available);
wpos -= rpos; // wpos must be relative to the new rpos, which will be 0
} else {
int tail = data.length - rpos;
System.arraycopy(data, rpos, tmp, 0, tail); // segment right of rpos
System.arraycopy(data, 0, tmp, tail, wpos); // segment left of wpos
wpos += tail; // wpos must be relative to the new rpos, which will be 0
}
rpos = 0;
data = tmp;
}
}
/**
* Reads data from this buffer into the provided array.
*/
public void readRawBytes(byte[] destination, int offset, int length) throws CircularBufferException {
ensureAvailable(length);
int rposNext = rpos + length;
if (rposNext <= data.length) {
System.arraycopy(data, rpos, destination, offset, length);
} else {
int tail = data.length - rpos;
System.arraycopy(data, rpos, destination, offset, tail); // segment right of rpos
rposNext = length - tail; // rpos wraps around the end of the buffer
System.arraycopy(data, 0, destination, offset + tail, rposNext); // remainder
}
// This can make rpos equal data.length, which has the same effect as wpos being 0.
rpos = rposNext;
}
/**
* Writes data to this buffer from the provided array.
*/
@SuppressWarnings("unchecked")
public T putRawBytes(byte[] source, int offset, int length) throws CircularBufferException {
ensureCapacity(length);
int wposNext = wpos + length;
if (wposNext <= data.length) {
System.arraycopy(source, offset, data, wpos, length);
} else {
int tail = data.length - wpos;
System.arraycopy(source, offset, data, wpos, tail); // segment right of wpos
wposNext = length - tail; // wpos wraps around the end of the buffer
System.arraycopy(source, offset + tail, data, 0, wposNext); // remainder
}
// This can make wpos equal data.length, which has the same effect as wpos being 0.
wpos = wposNext;
return (T) this;
}
// Used only for testing.
int length() {
return data.length;
}
@Override
public String toString() {
return "CircularBuffer [rpos=" + rpos + ", wpos=" + wpos + ", size=" + data.length + "]";
}
}

View File

@@ -164,8 +164,7 @@ public abstract class AbstractChannel
}
@Override
public void handle(Message msg, SSHPacket buf)
throws ConnectionException, TransportException {
public void handle(Message msg, SSHPacket buf) throws SSHException {
switch (msg) {
case CHANNEL_DATA:
@@ -354,7 +353,7 @@ public abstract class AbstractChannel
}
protected void gotExtendedData(SSHPacket buf)
throws ConnectionException, TransportException {
throws SSHException {
throw new ConnectionException(DisconnectReason.PROTOCOL_ERROR,
"Extended data not supported on " + type + " channel");
}
@@ -375,7 +374,7 @@ public abstract class AbstractChannel
}
protected void receiveInto(ChannelInputStream stream, SSHPacket buf)
throws ConnectionException, TransportException {
throws SSHException {
final int len;
try {
len = buf.readUInt32AsInt();

View File

@@ -38,7 +38,7 @@ public final class ChannelInputStream
private final Channel chan;
private final Transport trans;
private final Window.Local win;
private final Buffer.PlainBuffer buf;
private final CircularBuffer.PlainCircularBuffer buf;
private final byte[] b = new byte[1];
private boolean eof;
@@ -46,10 +46,11 @@ public final class ChannelInputStream
public ChannelInputStream(Channel chan, Transport trans, Window.Local win) {
this.chan = chan;
log = chan.getLoggerFactory().getLogger(getClass());
this.log = chan.getLoggerFactory().getLogger(getClass());
this.trans = trans;
this.win = win;
buf = new Buffer.PlainBuffer(chan.getLocalMaxPacketSize());
this.buf = new CircularBuffer.PlainCircularBuffer(
chan.getLocalMaxPacketSize(), trans.getConfig().getMaxCircularBufferSize());
}
@Override
@@ -113,48 +114,44 @@ public final class ChannelInputStream
len = buf.available();
}
buf.readRawBytes(b, off, len);
if (buf.rpos() > win.getMaxPacketSize() && buf.available() == 0) {
buf.clear();
}
}
if (!chan.getAutoExpand()) {
checkWindow();
if (!chan.getAutoExpand()) {
checkWindow();
}
}
return len;
}
public void receive(byte[] data, int offset, int len)
throws ConnectionException, TransportException {
public void receive(byte[] data, int offset, int len) throws SSHException {
if (eof) {
throw new ConnectionException("Getting data on EOF'ed stream");
}
synchronized (buf) {
buf.putRawBytes(data, offset, len);
buf.notifyAll();
}
// Potential fix for #203 (window consumed below 0).
// This seems to be a race condition if we receive more data, while we're already sending a SSH_MSG_CHANNEL_WINDOW_ADJUST
// And the window has not expanded yet.
synchronized (win) {
// Potential fix for #203 (window consumed below 0).
// This seems to be a race condition if we receive more data, while we're already sending a SSH_MSG_CHANNEL_WINDOW_ADJUST
// And the window has not expanded yet.
win.consume(len);
}
if (chan.getAutoExpand()) {
checkWindow();
if (chan.getAutoExpand()) {
checkWindow();
}
}
}
private void checkWindow()
throws TransportException {
synchronized (win) {
final long adjustment = win.neededAdjustment();
if (adjustment > 0) {
log.debug("Sending SSH_MSG_CHANNEL_WINDOW_ADJUST to #{} for {} bytes", chan.getRecipient(), adjustment);
trans.write(new SSHPacket(Message.CHANNEL_WINDOW_ADJUST)
.putUInt32FromInt(chan.getRecipient()).putUInt32(adjustment));
win.expand(adjustment);
}
private void checkWindow() throws TransportException {
/*
* Window must fit in remaining buffer capacity. We already expect win.size() amount of data to arrive. The
* difference between that and the remaining capacity is the maximum adjustment we can make to the window.
*/
final long maxAdjustment = buf.maxPossibleRemainingCapacity() - win.getSize();
final long adjustment = Math.min(win.neededAdjustment(), maxAdjustment);
if (adjustment > 0) {
log.debug("Sending SSH_MSG_CHANNEL_WINDOW_ADJUST to #{} for {} bytes", chan.getRecipient(), adjustment);
trans.write(new SSHPacket(Message.CHANNEL_WINDOW_ADJUST)
.putUInt32FromInt(chan.getRecipient()).putUInt32(adjustment));
win.expand(adjustment);
}
}

View File

@@ -210,7 +210,7 @@ public class SessionChannel
@Override
protected void gotExtendedData(SSHPacket buf)
throws ConnectionException, TransportException {
throws SSHException {
try {
final int dataTypeCode = buf.readUInt32AsInt();
if (dataTypeCode == 1)

View File

@@ -15,6 +15,7 @@
*/
package net.schmizz.sshj.sftp;
import net.schmizz.sshj.connection.channel.direct.SessionFactory;
import net.schmizz.sshj.xfer.FilePermission;
import net.schmizz.sshj.xfer.LocalDestFile;
import net.schmizz.sshj.xfer.LocalSourceFile;
@@ -39,6 +40,13 @@ public class SFTPClient
this.xfer = new SFTPFileTransfer(engine);
}
public SFTPClient(SessionFactory sessionFactory) throws IOException {
this.engine = new SFTPEngine(sessionFactory);
this.engine.init();
log = engine.getLoggerFactory().getLogger(getClass());
this.xfer = new SFTPFileTransfer(engine);
}
public SFTPEngine getSFTPEngine() {
return engine;
}
@@ -232,7 +240,7 @@ public class SFTPClient
throws IOException {
xfer.download(source, dest);
}
public void get(String source, String dest, long byteOffset)
throws IOException {
xfer.download(source, dest, byteOffset);
@@ -252,7 +260,7 @@ public class SFTPClient
throws IOException {
xfer.download(source, dest);
}
public void get(String source, LocalDestFile dest, long byteOffset)
throws IOException {
xfer.download(source, dest, byteOffset);
@@ -262,7 +270,7 @@ public class SFTPClient
throws IOException {
xfer.upload(source, dest);
}
public void put(LocalSourceFile source, String dest, long byteOffset)
throws IOException {
xfer.upload(source, dest, byteOffset);

View File

@@ -81,7 +81,23 @@ public class SFTPEngine
public SFTPEngine init()
throws IOException {
transmit(new SFTPPacket<Request>(PacketType.INIT).putUInt32(MAX_SUPPORTED_VERSION));
return init(MAX_SUPPORTED_VERSION);
}
/**
* Introduced for internal use by testcases.
* @param requestedVersion
* @throws IOException
*/
protected SFTPEngine init(int requestedVersion)
throws IOException {
if (requestedVersion > MAX_SUPPORTED_VERSION)
throw new SFTPException("You requested an unsupported protocol version: " + requestedVersion + " (requested) > " + MAX_SUPPORTED_VERSION + " (supported)");
if (requestedVersion < MAX_SUPPORTED_VERSION)
log.debug("Client version {} is smaller than MAX_SUPPORTED_VERSION {}", requestedVersion, MAX_SUPPORTED_VERSION);
transmit(new SFTPPacket<Request>(PacketType.INIT).putUInt32(requestedVersion));
final SFTPPacket<Response> response = reader.readPacket();
@@ -91,7 +107,7 @@ public class SFTPEngine
operativeVersion = response.readUInt32AsInt();
log.debug("Server version {}", operativeVersion);
if (MAX_SUPPORTED_VERSION < operativeVersion)
if (requestedVersion < operativeVersion)
throw new SFTPException("Server reported incompatible protocol version: " + operativeVersion);
while (response.available() > 0)
@@ -234,16 +250,75 @@ public class SFTPEngine
public void rename(String oldPath, String newPath, Set<RenameFlags> flags)
throws IOException {
if (operativeVersion < 1)
if (operativeVersion < 1) {
throw new SFTPException("RENAME is not supported in SFTPv" + operativeVersion);
}
final Request request = newRequest(PacketType.RENAME).putString(oldPath, sub.getRemoteCharset()).putString(newPath, sub.getRemoteCharset());
// SFTP Version 5 introduced rename flags according to Section 6.5 of the specification
if (operativeVersion >= 5) {
long renameFlagMask = 0L;
for (RenameFlags flag : flags) {
renameFlagMask = renameFlagMask | flag.longValue();
// request variables to be determined
PacketType type = PacketType.RENAME; // Default
long renameFlagMask = 0L;
String serverExtension = null;
if (!flags.isEmpty()) {
// SFTP Version 5 introduced rename flags according to Section 6.5 of the specification
if (operativeVersion >= 5) {
for (RenameFlags flag : flags) {
renameFlagMask = renameFlagMask | flag.longValue();
}
}
// Try to find a fallback solution if flags are not supported by the server.
// "posix-rename@openssh.com" provides ATOMIC and OVERWRITE behaviour.
// From the SFTP-spec, Section 6.5:
// "If SSH_FXP_RENAME_OVERWRITE is specified, the server MAY perform an atomic rename even if it is
// not requested."
// So, if overwrite is allowed we can always use the posix-rename as a fallback.
else if (flags.contains(RenameFlags.OVERWRITE) &&
supportsServerExtension("posix-rename","openssh.com")) {
type = PacketType.EXTENDED;
serverExtension = "posix-rename@openssh.com";
}
// Because the OVERWRITE flag changes the behaviour in a possibly unintended way, it has to be
// explicitly requested for the above fallback to be applicable.
// Tell this to the developer if ATOMIC is requested without OVERWRITE.
else if (flags.contains(RenameFlags.ATOMIC) &&
!flags.contains(RenameFlags.OVERWRITE) &&
!flags.contains(RenameFlags.NATIVE) && // see next case below
supportsServerExtension("posix-rename","openssh.com")) {
throw new SFTPException("RENAME-FLAGS are not supported in SFTPv" + operativeVersion + " but " +
"the \"posix-rename@openssh.com\" extension could be used as fallback if OVERWRITE " +
"behaviour is acceptable (needs to be activated via RenameFlags.OVERWRITE).");
}
// From the SFTP-spec, Section 6.5:
// "If flags includes SSH_FXP_RENAME_NATIVE, the server is free to do the rename operation in whatever
// fashion it deems appropriate. Other flag values are considered hints as to desired behavior, but not
// requirements."
else if (flags.contains(RenameFlags.NATIVE)) {
log.debug("Flags are not supported but NATIVE-flag allows to ignore other requested flags: " +
flags.toString());
}
// finally: let the user know that the server does not support what was asked
else {
throw new SFTPException("RENAME-FLAGS are not supported in SFTPv" + operativeVersion + " and no " +
"supported server extension could be found to achieve a similar result.");
}
}
// build and send request
final Request request = newRequest(type);
if (serverExtension != null) {
request.putString(serverExtension);
}
request.putString(oldPath, sub.getRemoteCharset())
.putString(newPath, sub.getRemoteCharset());
if (renameFlagMask != 0L) {
request.putUInt32(renameFlagMask);
}

View File

@@ -15,6 +15,7 @@
*/
package net.schmizz.sshj.sftp;
import net.schmizz.sshj.connection.channel.direct.SessionFactory;
import net.schmizz.sshj.xfer.LocalDestFile;
import net.schmizz.sshj.xfer.LocalSourceFile;
@@ -34,6 +35,12 @@ public class StatefulSFTPClient
log.debug("Start dir = {}", cwd);
}
public StatefulSFTPClient(SessionFactory sessionFactory) throws IOException {
super(sessionFactory);
this.cwd = getSFTPEngine().canonicalize(".");
log.debug("Start dir = {}", cwd);
}
private synchronized String cwdify(String path) {
return engine.getPathHelper().adjustForParent(cwd, path);
}

View File

@@ -51,6 +51,14 @@ abstract class Converter {
return seq;
}
void resetSequenceNumber() {
seq = -1;
}
boolean isSequenceNumberAtMax() {
return seq == 0xffffffffL;
}
void setAlgorithms(Cipher cipher, MAC mac, Compression compression) {
this.cipher = cipher;
this.mac = mac;

View File

@@ -60,6 +60,10 @@ final class KeyExchanger
private final AtomicBoolean kexOngoing = new AtomicBoolean();
private final AtomicBoolean initialKex = new AtomicBoolean(true);
private final AtomicBoolean strictKex = new AtomicBoolean();
/** What we are expecting from the next packet */
private Expected expected = Expected.KEXINIT;
@@ -123,6 +127,14 @@ final class KeyExchanger
return kexOngoing.get();
}
boolean isStrictKex() {
return strictKex.get();
}
boolean isInitialKex() {
return initialKex.get();
}
/**
* Starts key exchange by sending a {@code SSH_MSG_KEXINIT} packet. Key exchange needs to be done once mandatorily
* after initializing the {@link Transport} for it to be usable and may be initiated at any later point e.g. if
@@ -183,7 +195,7 @@ final class KeyExchanger
throws TransportException {
log.debug("Sending SSH_MSG_KEXINIT");
List<String> knownHostAlgs = findKnownHostAlgs(transport.getRemoteHost(), transport.getRemotePort());
clientProposal = new Proposal(transport.getConfig(), knownHostAlgs);
clientProposal = new Proposal(transport.getConfig(), knownHostAlgs, initialKex.get());
transport.write(clientProposal.getPacket());
kexInitSent.set();
}
@@ -202,6 +214,9 @@ final class KeyExchanger
throws TransportException {
log.debug("Sending SSH_MSG_NEWKEYS");
transport.write(new SSHPacket(Message.NEWKEYS));
if (strictKex.get()) {
transport.getEncoder().resetSequenceNumber();
}
}
/**
@@ -234,6 +249,10 @@ final class KeyExchanger
private void setKexDone() {
kexOngoing.set(false);
initialKex.set(false);
if (strictKex.get()) {
transport.getDecoder().resetSequenceNumber();
}
kexInitSent.clear();
done.set();
}
@@ -242,6 +261,7 @@ final class KeyExchanger
throws TransportException {
buf.rpos(buf.rpos() - 1);
final Proposal serverProposal = new Proposal(buf);
gotStrictKexInfo(serverProposal);
negotiatedAlgs = clientProposal.negotiate(serverProposal);
log.debug("Negotiated algorithms: {}", negotiatedAlgs);
for(AlgorithmsVerifier v: algorithmVerifiers) {
@@ -265,6 +285,18 @@ final class KeyExchanger
}
}
private void gotStrictKexInfo(Proposal serverProposal) throws TransportException {
if (initialKex.get() && serverProposal.isStrictKeyExchangeSupportedByServer()) {
strictKex.set(true);
log.debug("Enabling strict key exchange extension");
if (transport.getDecoder().getSequenceNumber() != 0) {
throw new TransportException(DisconnectReason.KEY_EXCHANGE_FAILED,
"SSH_MSG_KEXINIT was not first package during strict key exchange"
);
}
}
}
/**
* Private method used while putting new keys into use that will resize the key used to initialize the cipher to the
* needed length.

View File

@@ -37,8 +37,11 @@ class Proposal {
private final List<String> s2cComp;
private final SSHPacket packet;
public Proposal(Config config, List<String> knownHostAlgs) {
public Proposal(Config config, List<String> knownHostAlgs, boolean initialKex) {
kex = Factory.Named.Util.getNames(config.getKeyExchangeFactories());
if (initialKex) {
kex.add("kex-strict-c-v00@openssh.com");
}
sig = filterKnownHostKeyAlgorithms(Factory.Named.Util.getNames(config.getKeyAlgorithms()), knownHostAlgs);
c2sCipher = s2cCipher = Factory.Named.Util.getNames(config.getCipherFactories());
c2sMAC = s2cMAC = Factory.Named.Util.getNames(config.getMACFactories());
@@ -91,6 +94,10 @@ class Proposal {
return kex;
}
public boolean isStrictKeyExchangeSupportedByServer() {
return kex.contains("kex-strict-s-v00@openssh.com");
}
public List<String> getHostKeyAlgorithms() {
return sig;
}

View File

@@ -426,7 +426,7 @@ public final class TransportImpl
assert m != Message.KEXINIT;
kexer.waitForDone();
}
} else if (encoder.getSequenceNumber() == 0) // We get here every 2**32th packet
} else if (encoder.isSequenceNumberAtMax()) // We get here every 2**32th packet
kexer.startKex(true);
final long seq = encoder.encode(payload);
@@ -479,9 +479,20 @@ public final class TransportImpl
log.trace("Received packet {}", msg);
if (kexer.isInitialKex()) {
if (decoder.isSequenceNumberAtMax()) {
throw new TransportException(DisconnectReason.KEY_EXCHANGE_FAILED,
"Sequence number of decoder is about to wrap during initial key exchange");
}
if (kexer.isStrictKex() && !isKexerPacket(msg) && msg != Message.DISCONNECT) {
throw new TransportException(DisconnectReason.KEY_EXCHANGE_FAILED,
"Unexpected packet type during initial strict key exchange");
}
}
if (msg.geq(50)) { // not a transport layer packet
service.handle(msg, buf);
} else if (msg.in(20, 21) || msg.in(30, 49)) { // kex packet
} else if (isKexerPacket(msg)) {
kexer.handle(msg, buf);
} else {
switch (msg) {
@@ -513,6 +524,10 @@ public final class TransportImpl
}
}
private static boolean isKexerPacket(Message msg) {
return msg.in(20, 21) || msg.in(30, 49);
}
private void gotDebug(SSHPacket buf)
throws TransportException {
try {

View File

@@ -22,7 +22,6 @@ import java.util.zip.Inflater;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.DisconnectReason;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.transport.compression.Compression;
public class ZlibCompression implements Compression {
@@ -71,10 +70,14 @@ public class ZlibCompression implements Compression {
public void compress(Buffer buffer) {
deflater.setInput(buffer.array(), buffer.rpos(), buffer.available());
buffer.wpos(buffer.rpos());
do {
while (true) {
final int len = deflater.deflate(tempBuf, 0, BUF_SIZE, Deflater.SYNC_FLUSH);
buffer.putRawBytes(tempBuf, 0, len);
} while (!deflater.needsInput());
if(len > 0) {
buffer.putRawBytes(tempBuf, 0, len);
} else {
return;
}
}
}
@Override

View File

@@ -41,6 +41,7 @@ import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
@@ -468,7 +469,8 @@ public class OpenSSHKnownHosts
}
private String getKeyString(PublicKey pk) {
return Base64.getEncoder().encodeToString(pk.getEncoded());
final Buffer.PlainBuffer buf = new Buffer.PlainBuffer().putPublicKey(pk);
return Base64.getEncoder().encodeToString(Arrays.copyOfRange(buf.array(), buf.rpos(), buf.available()));
}
protected String getHostPart() {

View File

@@ -1,59 +0,0 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hierynomus.sshj.transport.verification
import spock.lang.Specification
import spock.lang.Unroll
class KnownHostMatchersSpec extends Specification {
@Unroll
def "should #yesno match host #host with pattern #pattern"() {
given:
def matcher = KnownHostMatchers.createMatcher(pattern)
expect:
match == matcher.match(host)
where:
pattern | host | match
"aaa.bbb.com" | "aaa.bbb.com" | true
"aaa.bbb.com" | "aaa.ccc.com" | false
"*.bbb.com" | "aaa.bbb.com" | true
"*.bbb.com" | "aaa.ccc.com" | false
"aaa.*.com" | "aaa.bbb.com" | true
"aaa.*.com" | "aaa.ccc.com" | true
"aaa.bbb.*" | "aaa.bbb.com" | true
"aaa.bbb.*" | "aaa.ccc.com" | false
"!*.bbb.com" | "aaa.bbb.com" | false
"!*.bbb.com" | "aaa.ccc.com" | true
"aaa.bbb.com,!*.ccc.com" | "xxx.yyy.com" | true
"aaa.bbb.com,!*.ccc.com" | "aaa.bbb.com" | true
"aaa.bbb.com,!*.ccc.com" | "aaa.ccc.com" | false
"aaa.b??.com" | "aaa.bbb.com" | true
"aaa.b??.com" | "aaa.bcd.com" | true
"aaa.b??.com" | "aaa.ccd.com" | false
"aaa.b??.com" | "aaa.bccd.com" | false
"|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg=" | "192.168.1.61" | true
"|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg=" | "192.168.2.61" | false
"[aaa.bbb.com]:2222" | "aaa.bbb.com" | false
"[aaa.bbb.com]:2222" | "[aaa.bbb.com]:2222" | true
"[aaa.?bb.com]:2222" | "[aaa.dbb.com]:2222" | true
"[aaa.?xb.com]:2222" | "[aaa.dbb.com]:2222" | false
"[*.bbb.com]:2222" | "[aaa.bbb.com]:2222" | true
yesno = match ? "" : "no"
}
}

View File

@@ -1,221 +0,0 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hierynomus.sshj.transport.verification
import net.schmizz.sshj.common.Buffer
import net.schmizz.sshj.transport.verification.OpenSSHKnownHosts
import net.schmizz.sshj.util.KeyUtil
import spock.lang.Specification
import spock.lang.TempDir
import spock.lang.Unroll
import java.nio.file.Files
import java.security.PublicKey
class OpenSSHKnownHostsSpec extends Specification {
@TempDir def temp
def "should parse and verify hashed host entry"() {
given:
def f = knownHosts("|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ==");
final PublicKey key = KeyUtil
.newRSAPublicKey(
"e8ff4797075a861db9d2319960a836b2746ada3da514955d2921f2c6a6c9895cbd557f604e43772b6303e3cab2ad82d83b21acdef4edb72524f9c2bef893335115acacfe2989bcbb2e978e4fedc8abc090363e205d975c1fdc35e55ba4daa4b5d5ab7a22c40f547a4a0fd1c683dfff10551c708ff8c34ea4e175cb9bf2313865308fa23601e5a610e2f76838be7ded3b4d3a2c49d2d40fa20db51d1cc8ab20d330bb0dadb88b1a12853f0ecb7c7632947b098dcf435a54566bcf92befd55e03ee2a57d17524cd3d59d6e800c66059067e5eb6edb81946b3286950748240ec9afa4389f9b62bc92f94ec0fba9e64d6dc2f455f816016a4c5f3d507382ed5d3365",
"23");
when:
OpenSSHKnownHosts openSSHKnownHosts = new OpenSSHKnownHosts(f)
then:
openSSHKnownHosts.verify("192.168.1.61", 22, key)
!openSSHKnownHosts.verify("192.168.1.2", 22, key)
}
def "should parse and verify v1 host entry"() {
given:
def f = knownHosts("test.com,1.1.1.1 2048 35 22017496617994656680820635966392838863613340434802393112245951008866692373218840197754553998457793202561151141246686162285550121243768846314646395880632789308110750881198697743542374668273149584280424505890648953477691795864456749782348425425954366277600319096366690719901119774784695056100331902394094537054256611668966698242432417382422091372756244612839068092471592121759862971414741954991375710930168229171638843329213652899594987626853020377726482288618521941129157643483558764875338089684351824791983007780922947554898825663693324944982594850256042689880090306493029526546183035567296830604572253312294059766327")
def key = KeyUtil.newRSAPublicKey("ae6983ed63a33afc69fe0b88b4ba14393120a0b66e1460916a8390ff109139cd14f4e1701ab5c5feeb479441fe2091d04c0ba7d3fa1756b80ed103657ab53b5d7daa38af22f59f9cbfc16892d4ef1f8fd3ae49663c295be1f568a160d54328fbc2c0598f48d32296b1b9942336234952c440cda1bfac904e3391db98e52f9b1de229adc18fc34a9a569717aa9a5b1145e73b8a8394354028d02054ca760243fb8fc1575490607dd098e698e02b5d8bdf22d55ec958245222ef4c65b8836b9f13674a2d2895a587bfd4423b4eeb6d3ef98451640e3d63d2fc6a761ffd34446abab028494caf36d67ffd65298d69f19f2d90bae4c207b671db563a08f1bb9bf237",
"23")
when:
OpenSSHKnownHosts knownHosts = new OpenSSHKnownHosts(f)
then:
knownHosts.verify("test.com", 22, key)
}
def "should check all host entries for key"() {
given:
def f = knownHosts("""
host1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCiYp2IDgzDFhl8T4TRLIhEljvEixz1YN0XWh4dYh0REGK9T4QKiyb28EztPMdcOtz1uyX5rUGYXX9hj99S4SiU=
host1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTjA7hduYGmvV9smEEsIdGLdghSPD7kL8QarIIOkeXmBh+LTtT/T1K+Ot/rmXCZsP8hoUXxbvN+Tks440Ci0ck=
""")
def pk = new Buffer.PlainBuffer(Base64.getDecoder().decode("AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTjA7hduYGmvV9smEEsIdGLdghSPD7kL8QarIIOkeXmBh+LTtT/T1K+Ot/rmXCZsP8hoUXxbvN+Tks440Ci0ck=")).readPublicKey()
when:
def knownhosts = new OpenSSHKnownHosts(f)
then:
knownhosts.verify("host1", 22, pk)
}
def "should not fail on bad base64 entry"() {
given:
def f = knownHosts("""
host1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTIDgzDFhl8T4TRLIhEljvEixz1YN0XWh4dYh0REGK9T4QKiyb28EztPMdcOtz1uyX5rUGYXX9hj99S4SiU=
host1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTjA7hduYGmvV9smEEsIdGLdghSPD7kL8QarIIOkeXmBh+LTtT/T1K+Ot/rmXCZsP8hoUXxbvN+Tks440Ci0ck=
""")
def pk = new Buffer.PlainBuffer(Base64.getDecoder().decode("AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTjA7hduYGmvV9smEEsIdGLdghSPD7kL8QarIIOkeXmBh+LTtT/T1K+Ot/rmXCZsP8hoUXxbvN+Tks440Ci0ck=")).readPublicKey()
when:
def knownhosts = new OpenSSHKnownHosts(f)
then:
knownhosts.verify("host1", 22, pk)
}
def "should mark bad line and not fail"() {
given:
def f = knownHosts("M36Lo+Ik5ukNugvvoNFlpnyiHMmtKxt3FpyEfYuryXjNqMNWHn/ARVnpUIl5jRLTB7WBzyLYMG7X5nuoFL9zYqKGtHxChbDunxMVbspw5WXI9VN+qxcLwmITmpEvI9ApyS/Ox2ZyN7zw==\n")
when:
def knownhosts = new OpenSSHKnownHosts(f)
then:
knownhosts.entries().size() == 1
knownhosts.entries().get(0) instanceof OpenSSHKnownHosts.BadHostEntry
}
@Unroll
def "should add comment for #type line"() {
given:
def f = knownHosts(s)
when:
def knownHosts = new OpenSSHKnownHosts(f)
then:
knownHosts.entries().size() == 1
knownHosts.entries().get(0) instanceof OpenSSHKnownHosts.CommentEntry
where:
type << ["newline", "comment"]
s << ["\n", "#comment\n"]
}
@Unroll
def "should contain comment at end of line"() {
given:
def f = knownHosts(host)
when:
OpenSSHKnownHosts knownHosts = new OpenSSHKnownHosts(f)
then:
knownHosts.entries().size() == 1
def entry = knownHosts.entries().get(0)
entry instanceof OpenSSHKnownHosts.HostEntry
entry.comment == comment
where:
host << [
"|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ== this is a comment",
"test.com,1.1.1.1 2048 35 22017496617994656680820635966392838863613340434802393112245951008866692373218840197754553998457793202561151141246686162285550121243768846314646395880632789308110750881198697743542374668273149584280424505890648953477691795864456749782348425425954366277600319096366690719901119774784695056100331902394094537054256611668966698242432417382422091372756244612839068092471592121759862971414741954991375710930168229171638843329213652899594987626853020377726482288618521941129157643483558764875338089684351824791983007780922947554898825663693324944982594850256042689880090306493029526546183035567296830604572253312294059766327 single",
"schmizz.net,69.163.155.180 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ==",
"schmizz.net,69.163.155.180 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ== ",
"schmizz.net,69.163.155.180 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ== extra space"
]
comment << [
"this is a comment",
"single",
null,
null,
"extra space"
]
}
@Unroll
def "should match any host name from multi-host line"() {
given:
def f = knownHosts("schmizz.net,69.163.155.180 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ==")
def pk = new Buffer.PlainBuffer(Base64.getDecoder().decode("AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ==")).readPublicKey()
when:
def knownHosts = new OpenSSHKnownHosts(f)
then:
knownHosts.verify(h, 22, pk)
where:
h << ["schmizz.net", "69.163.155.180"]
}
def "should produce meaningful toString()"() {
given:
def f = knownHosts("schmizz.net,69.163.155.180 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ==")
when:
def knownhosts = new OpenSSHKnownHosts(f)
def toStringValue = knownhosts.toString()
then:
toStringValue == "OpenSSHKnownHosts{khFile='" + f + "'}"
}
def "should forgive redundant spaces like OpenSSH does"() {
given:
def key = "AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG"
def f = knownHosts("""
|host1 ssh-ed25519 $key
|
| host2 ssh-ed25519 $key ,./gargage\\.,
|\t\t\t\t\t
|\t@revoked host3\tssh-ed25519\t \t$key\t
""".stripMargin())
def pk = new Buffer.PlainBuffer(Base64.getDecoder().decode(key)).readPublicKey()
when:
def knownhosts = new OpenSSHKnownHosts(f)
then:
["host1", "host2", "host3"].forEach {
knownhosts.verify(it, 22, pk)
}
}
def "should not throw errors while parsing corrupted records"() {
given:
def key = "AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG"
def f = knownHosts(
"\n" // empty line
+ " \n" // blank line
+ "bad-host1\n" // absent key type and key contents
+ "bad-host2 ssh-ed25519\n" // absent key contents
+ " bad-host3 ssh-ed25519\n" // absent key contents, with leading spaces
+ "@revoked bad-host5 ssh-ed25519\n" // absent key contents, with marker
+ "good-host ssh-ed25519 $key" // the only good host at the end
)
when:
def knownhosts = new OpenSSHKnownHosts(f)
then:
knownhosts.verify("good-host", 22, new Buffer.PlainBuffer(Base64.getDecoder().decode(key)).readPublicKey())
}
def knownHosts(String s) {
def f = Files.createFile(temp.resolve("known_hosts")).toFile()
f.write(s)
return f
}
}

View File

@@ -0,0 +1,188 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hierynomus.sshj.connection.channel.forwarded;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.forwarded.RemotePortForwarder.Forward;
import net.schmizz.sshj.connection.channel.forwarded.SocketForwardingConnectListener;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RemotePFPerformanceTest {
private static final Logger log = LoggerFactory.getLogger(RemotePFPerformanceTest.class);
@Test
@Disabled
public void startPF() throws IOException, InterruptedException {
DefaultConfig config = new DefaultConfig();
config.setMaxCircularBufferSize(16 * 1024 * 1024);
SSHClient client = new SSHClient(config);
client.loadKnownHosts();
client.addHostKeyVerifier("5c:0c:8e:9d:1c:50:a9:ba:a7:05:f6:b1:2b:0b:5f:ba");
client.getConnection().getKeepAlive().setKeepAliveInterval(5);
client.connect("localhost");
client.getConnection().getKeepAlive().setKeepAliveInterval(5);
Object consumerReadyMonitor = new Object();
ConsumerThread consumerThread = new ConsumerThread(consumerReadyMonitor);
ProducerThread producerThread = new ProducerThread();
try {
client.authPassword(System.getenv().get("USERNAME"), System.getenv().get("PASSWORD"));
/*
* We make _server_ listen on port 8080, which forwards all connections to us as a channel, and we further
* forward all such channels to google.com:80
*/
client.getRemotePortForwarder().bind(
// where the server should listen
new Forward(8888),
// what we do with incoming connections that are forwarded to us
new SocketForwardingConnectListener(new InetSocketAddress("localhost", 12345)));
consumerThread.start();
synchronized (consumerReadyMonitor) {
consumerReadyMonitor.wait();
}
producerThread.start();
// Wait for consumer to finish receiving data.
synchronized (consumerReadyMonitor) {
consumerReadyMonitor.wait();
}
} finally {
producerThread.interrupt();
consumerThread.interrupt();
client.disconnect();
}
}
private static class ConsumerThread extends Thread {
private final Object consumerReadyMonitor;
private ConsumerThread(Object consumerReadyMonitor) {
super("Consumer");
this.consumerReadyMonitor = consumerReadyMonitor;
}
@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
synchronized (consumerReadyMonitor) {
consumerReadyMonitor.notifyAll();
}
try (Socket acceptedSocket = serverSocket.accept()) {
InputStream in = acceptedSocket.getInputStream();
int numRead;
byte[] buf = new byte[40000];
//byte[] buf = new byte[255 * 4 * 1000];
byte expectedNext = 1;
while ((numRead = in.read(buf)) != 0) {
if (Thread.interrupted()) {
log.info("Consumer thread interrupted");
return;
}
log.info(String.format("Read %d characters; values from %d to %d", numRead, buf[0], buf[numRead - 1]));
if (buf[numRead - 1] == 0) {
verifyData(buf, numRead - 1, expectedNext);
break;
}
expectedNext = verifyData(buf, numRead, expectedNext);
// Slow down consumer to test buffering.
Thread.sleep(Long.parseLong(System.getenv().get("DELAY_MS")));
}
log.info("Consumer read end of stream value: " + numRead);
synchronized (consumerReadyMonitor) {
consumerReadyMonitor.notifyAll();
}
}
} catch (Exception e) {
synchronized (consumerReadyMonitor) {
consumerReadyMonitor.notifyAll();
}
e.printStackTrace();
}
}
private byte verifyData(byte[] buf, int numRead, byte expectedNext) {
for (int i = 0; i < numRead; ++i) {
if (buf[i] != expectedNext) {
fail("Expected buf[" + i + "]=" + buf[i] + " to be " + expectedNext);
}
if (++expectedNext == 0) {
expectedNext = 1;
}
}
return expectedNext;
}
}
private static class ProducerThread extends Thread {
private ProducerThread() {
super("Producer");
}
@Override
public void run() {
try (Socket clientSocket = new Socket("127.0.0.1", 8888);
OutputStream writer = clientSocket.getOutputStream()) {
byte[] buf = getData();
assertEquals(buf[0], 1);
assertEquals(buf[buf.length - 1], -1);
for (int i = 0; i < 1000; ++i) {
writer.write(buf);
if (Thread.interrupted()) {
log.info("Consumer thread interrupted");
return;
}
log.info(String.format("Wrote %d characters; values from %d to %d", buf.length, buf[0], buf[buf.length - 1]));
}
writer.write(0); // end of stream value
log.info("Producer finished sending data");
} catch (Exception e) {
e.printStackTrace();
}
}
private byte[] getData() {
byte[] buf = new byte[255 * 4 * 1000];
byte nextValue = 1;
for (int i = 0; i < buf.length; ++i) {
buf[i] = nextValue++;
// reserve 0 for end of stream
if (nextValue == 0) {
nextValue = 1;
}
}
return buf;
}
}
}

View File

@@ -70,6 +70,28 @@ public class ChachaPolyCipherTest {
}
}
@Test
public void testEncryptDecryptWithoutAAD() {
final Cipher encryptionCipher = FACTORY.create();
final byte[] key = new byte[encryptionCipher.getBlockSize()];
Arrays.fill(key, (byte) 1);
encryptionCipher.init(Cipher.Mode.Encrypt, key, new byte[0]);
final byte[] plaintextBytes = PLAINTEXT.getBytes(StandardCharsets.UTF_8);
final byte[] message = new byte[plaintextBytes.length + POLY_TAG_LENGTH];
System.arraycopy(plaintextBytes, 0, message, 0, plaintextBytes.length);
encryptionCipher.update(message, 0, plaintextBytes.length);
final Cipher decryptionCipher = FACTORY.create();
decryptionCipher.init(Cipher.Mode.Decrypt, key, new byte[0]);
decryptionCipher.update(message, 0, plaintextBytes.length);
final byte[] decrypted = Arrays.copyOfRange(message, 0, plaintextBytes.length);
final String decoded = new String(decrypted, StandardCharsets.UTF_8);
assertEquals(PLAINTEXT, decoded);
}
@Test
public void testCheckOnUpdateParameters() {
Cipher cipher = FACTORY.create();

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hierynomus.sshj.transport.verification;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class KnownHostMatchersTest {
@MethodSource("com.hierynomus.sshj.transport.verification.KnownHostMatchersTest#patterns")
@ParameterizedTest
public void shouldMatchHostnameToPattern(String pattern, String hostname, boolean match) throws Exception {
KnownHostMatchers.HostMatcher matcher = KnownHostMatchers.createMatcher(pattern);
assertEquals(match, matcher.match(hostname));
}
public static Stream<Arguments> patterns() {
return Stream.of(
Arguments.of("aaa.bbb.com", "aaa.bbb.com", true),
Arguments.of("aaa.bbb.com", "aaa.ccc.com", false),
Arguments.of("*.bbb.com" , "aaa.bbb.com", true),
Arguments.of("*.bbb.com" , "aaa.ccc.com", false),
Arguments.of("aaa.*.com" , "aaa.bbb.com", true),
Arguments.of("aaa.*.com" , "aaa.ccc.com", true),
Arguments.of("aaa.bbb.*", "aaa.bbb.com", true),
Arguments.of("aaa.bbb.*", "aaa.ccc.com", false),
Arguments.of("!*.bbb.com", "aaa.bbb.com", false),
Arguments.of("!*.bbb.com", "aaa.ccc.com", true),
Arguments.of("aaa.bbb.com,!*.ccc.com", "xxx.yyy.com", true),
Arguments.of("aaa.bbb.com,!*.ccc.com", "aaa.bbb.com", true),
Arguments.of("aaa.bbb.com,!*.ccc.com", "aaa.ccc.com", false),
Arguments.of("aaa.b??.com", "aaa.bbb.com", true),
Arguments.of("aaa.b??.com", "aaa.bcd.com", true),
Arguments.of("aaa.b??.com", "aaa.ccd.com", false),
Arguments.of("aaa.b??.com", "aaa.bccd.com", false),
Arguments.of("|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg=", "192.168.1.61", true),
Arguments.of("|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg=", "192.168.2.61", false),
Arguments.of("[aaa.bbb.com]:2222", "aaa.bbb.com", false),
Arguments.of("[aaa.bbb.com]:2222", "[aaa.bbb.com]:2222", true),
Arguments.of("[aaa.?bb.com]:2222", "[aaa.dbb.com]:2222", true),
Arguments.of("[aaa.?xb.com]:2222", "[aaa.dbb.com]:2222", false),
Arguments.of("[*.bbb.com]:2222", "[aaa.bbb.com]:2222", true)
);
}
}

View File

@@ -0,0 +1,221 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hierynomus.sshj.transport.verification;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.assertj.core.api.Assertions.*;
import java.io.File;
import java.io.IOException;
import java.lang.module.ModuleDescriptor.Opens;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.PublicKey;
import java.security.Security;
import java.util.Base64;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.SecurityUtils;
import net.schmizz.sshj.transport.verification.OpenSSHKnownHosts;
import net.schmizz.sshj.util.KeyUtil;
public class OpenSSHKnownHostsTest {
@TempDir
public File tempDir;
@BeforeAll
public static void setup() {
SecurityUtils.registerSecurityProvider("org.bouncycastle.jce.provider.BouncyCastleProvider");
}
@Test
public void shouldParseAndVerifyHashedHostEntry() throws Exception {
File knownHosts = knownHosts(
"|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ==");
PublicKey k = KeyUtil.newRSAPublicKey(
"e8ff4797075a861db9d2319960a836b2746ada3da514955d2921f2c6a6c9895cbd557f604e43772b6303e3cab2ad82d83b21acdef4edb72524f9c2bef893335115acacfe2989bcbb2e978e4fedc8abc090363e205d975c1fdc35e55ba4daa4b5d5ab7a22c40f547a4a0fd1c683dfff10551c708ff8c34ea4e175cb9bf2313865308fa23601e5a610e2f76838be7ded3b4d3a2c49d2d40fa20db51d1cc8ab20d330bb0dadb88b1a12853f0ecb7c7632947b098dcf435a54566bcf92befd55e03ee2a57d17524cd3d59d6e800c66059067e5eb6edb81946b3286950748240ec9afa4389f9b62bc92f94ec0fba9e64d6dc2f455f816016a4c5f3d507382ed5d3365",
"23");
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
assertTrue(ohk.verify("192.168.1.61", 22, k));
assertFalse(ohk.verify("192.168.1.2", 22, k));
ohk.write();
for (OpenSSHKnownHosts.KnownHostEntry entry : ohk.entries()) {
assertEquals("|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ==",
entry.getLine());
}
}
@Test
public void shouldParseAndVerifyV1HostEntry() throws Exception {
File knownHosts = knownHosts(
"test.com,1.1.1.1 2048 35 22017496617994656680820635966392838863613340434802393112245951008866692373218840197754553998457793202561151141246686162285550121243768846314646395880632789308110750881198697743542374668273149584280424505890648953477691795864456749782348425425954366277600319096366690719901119774784695056100331902394094537054256611668966698242432417382422091372756244612839068092471592121759862971414741954991375710930168229171638843329213652899594987626853020377726482288618521941129157643483558764875338089684351824791983007780922947554898825663693324944982594850256042689880090306493029526546183035567296830604572253312294059766327");
PublicKey k = KeyUtil.newRSAPublicKey(
"ae6983ed63a33afc69fe0b88b4ba14393120a0b66e1460916a8390ff109139cd14f4e1701ab5c5feeb479441fe2091d04c0ba7d3fa1756b80ed103657ab53b5d7daa38af22f59f9cbfc16892d4ef1f8fd3ae49663c295be1f568a160d54328fbc2c0598f48d32296b1b9942336234952c440cda1bfac904e3391db98e52f9b1de229adc18fc34a9a569717aa9a5b1145e73b8a8394354028d02054ca760243fb8fc1575490607dd098e698e02b5d8bdf22d55ec958245222ef4c65b8836b9f13674a2d2895a587bfd4423b4eeb6d3ef98451640e3d63d2fc6a761ffd34446abab028494caf36d67ffd65298d69f19f2d90bae4c207b671db563a08f1bb9bf237",
"23");
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
assertTrue(ohk.verify("test.com", 22, k));
}
@Test
public void shouldTestAllHostEntriesForKey() throws Exception {
File knownHosts = knownHosts(
"host1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCiYp2IDgzDFhl8T4TRLIhEljvEixz1YN0XWh4dYh0REGK9T4QKiyb28EztPMdcOtz1uyX5rUGYXX9hj99S4SiU=\n"
+
"host1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTjA7hduYGmvV9smEEsIdGLdghSPD7kL8QarIIOkeXmBh+LTtT/T1K+Ot/rmXCZsP8hoUXxbvN+Tks440Ci0ck=\n");
PublicKey k = new Buffer.PlainBuffer(Base64.getDecoder().decode(
"AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTjA7hduYGmvV9smEEsIdGLdghSPD7kL8QarIIOkeXmBh+LTtT/T1K+Ot/rmXCZsP8hoUXxbvN+Tks440Ci0ck="))
.readPublicKey();
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
assertTrue(ohk.verify("host1", 22, k));
}
@Test
public void shouldNotFailOnBadBase64Entry() throws Exception {
File knownHosts = knownHosts(
"host1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTIDgzDFhl8T4TRLIhEljvEixz1YN0XWh4dYh0REGK9T4QKiyb28EztPMdcOtz1uyX5rUGYXX9hj99S4SiU=\n"
+
"host1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTjA7hduYGmvV9smEEsIdGLdghSPD7kL8QarIIOkeXmBh+LTtT/T1K+Ot/rmXCZsP8hoUXxbvN+Tks440Ci0ck=\n");
PublicKey k = new Buffer.PlainBuffer(Base64.getDecoder().decode(
"AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTjA7hduYGmvV9smEEsIdGLdghSPD7kL8QarIIOkeXmBh+LTtT/T1K+Ot/rmXCZsP8hoUXxbvN+Tks440Ci0ck="))
.readPublicKey();
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
assertTrue(ohk.verify("host1", 22, k));
}
@Test
public void shouldMarkBadLineAndNotFail() throws Exception {
File knownHosts = knownHosts(
"M36Lo+Ik5ukNugvvoNFlpnyiHMmtKxt3FpyEfYuryXjNqMNWHn/ARVnpUIl5jRLTB7WBzyLYMG7X5nuoFL9zYqKGtHxChbDunxMVbspw5WXI9VN+qxcLwmITmpEvI9ApyS/Ox2ZyN7zw==\n");
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
assertEquals(1, ohk.entries().size());
assertInstanceOf(OpenSSHKnownHosts.BadHostEntry.class, ohk.entries().get(0));
}
@Test
public void shouldAddCommentForSpecificLines() throws Exception {
File knownHosts = knownHosts("#comment\n\n");
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
assertEquals(2, ohk.entries().size());
assertInstanceOf(OpenSSHKnownHosts.CommentEntry.class, ohk.entries().get(0));
assertInstanceOf(OpenSSHKnownHosts.CommentEntry.class, ohk.entries().get(1));
}
@Test
public void shouldNotVerifyRevokedEntries() throws Exception {
File knownHosts = knownHosts("host1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG\n" +
"@revoked revoked-host ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG\n");
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
PublicKey k = new Buffer.PlainBuffer(Base64.getDecoder().decode(
"AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG"))
.readPublicKey();
assertTrue(ohk.verify("host1", 22, k));
assertFalse(ohk.verify("revoked-host", 22, k));
}
@Test
public void shouldForgiveRedundantSpacesLikeOpenSSH() throws Exception {
File knownHosts = knownHosts(
"host1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG\n" +
"\n" +
" host2 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG ,./gargage\\.,\n" +
"\t\t\t\t\t\t\n" +
"\t host3\tssh-ed25519\t \tAAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG\t\n");
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
PublicKey pk = new Buffer.PlainBuffer(
Base64.getDecoder().decode("AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG"))
.readPublicKey();
assertTrue(ohk.verify("host1", 22, pk));
assertTrue(ohk.verify("host2", 22, pk));
assertTrue(ohk.verify("host3", 22, pk));
}
@Test
public void shouldNotThrowErrorsWhileParsingCorruptRecords() throws Exception {
File knownHosts = knownHosts(
"\n" // empty line
+ " \n" // blank line
+ "bad-host1\n" // absent key type and key contents
+ "bad-host2 ssh-ed25519\n" // absent key contents
+ " bad-host3 ssh-ed25519\n" // absent key contents, with leading spaces
+ "@revoked bad-host5 ssh-ed25519\n" // absent key contents, with marker
+ "good-host ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG" // the only good host at the end
);
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
assertTrue(ohk.verify("good-host", 22,
new Buffer.PlainBuffer(Base64.getDecoder()
.decode("AAAAC3NzaC1lZDI1NTE5AAAAIIRsJi92NJJTQwXHZiRiARoEy4n1jYsNTQePHFTSl7tG"))
.readPublicKey()));
}
@Test
public void shouldMatchAnyHostFromMultiHostLine() throws Exception {
File knownHosts = knownHosts(
"schmizz.net,69.163.155.180 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ==");
PublicKey k = new Buffer.PlainBuffer(Base64.getDecoder().decode(
"AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ=="))
.readPublicKey();
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
assertTrue(ohk.verify("schmizz.net", 22, k));
assertTrue(ohk.verify("69.163.155.180", 22, k));
}
@ParameterizedTest
@MethodSource("com.hierynomus.sshj.transport.verification.OpenSSHKnownHostsTest#commentedHostEntries")
public void shouldRetainCommentAtEndOfLine(String entry, String comment) throws Exception {
File knownHosts = knownHosts(entry);
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
assertEquals(1, ohk.entries().size());
assertThat(ohk.entries().get(0)).extracting("comment").isEqualTo(comment);
}
public static Stream<Arguments> commentedHostEntries() {
return Stream.of(
Arguments.of("|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ== this is a comment", "this is a comment"),
Arguments.of("test.com,1.1.1.1 2048 35 22017496617994656680820635966392838863613340434802393112245951008866692373218840197754553998457793202561151141246686162285550121243768846314646395880632789308110750881198697743542374668273149584280424505890648953477691795864456749782348425425954366277600319096366690719901119774784695056100331902394094537054256611668966698242432417382422091372756244612839068092471592121759862971414741954991375710930168229171638843329213652899594987626853020377726482288618521941129157643483558764875338089684351824791983007780922947554898825663693324944982594850256042689880090306493029526546183035567296830604572253312294059766327 single",
"single"),
Arguments.of("schmizz.net,69.163.155.180 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ==", null),
Arguments.of("schmizz.net,69.163.155.180 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ== ", null),
Arguments.of("schmizz.net,69.163.155.180 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6P9Hlwdahh250jGZYKg2snRq2j2lFJVdKSHyxqbJiVy9VX9gTkN3K2MD48qyrYLYOyGs3vTttyUk+cK++JMzURWsrP4piby7LpeOT+3Iq8CQNj4gXZdcH9w15Vuk2qS11at6IsQPVHpKD9HGg9//EFUccI/4w06k4XXLm/IxOGUwj6I2AeWmEOL3aDi+fe07TTosSdLUD6INtR0cyKsg0zC7Da24ixoShT8Oy3x2MpR7CY3PQ1pUVmvPkr79VeA+4qV9F1JM09WdboAMZgWQZ+XrbtuBlGsyhpUHSCQOya+kOJ+bYryS+U7A+6nmTW3C9FX4FgFqTF89UHOC7V0zZQ== extra space", "extra space")
);
}
private File knownHosts(String contents) throws IOException {
File knownHosts = new File(tempDir, "known_hosts");
Files.write(knownHosts.toPath(), contents.getBytes(StandardCharsets.UTF_8));
return knownHosts;
}
}

View File

@@ -0,0 +1,221 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.common;
import static org.junit.jupiter.api.Assertions.*;
import net.schmizz.sshj.common.CircularBuffer.CircularBufferException;
import net.schmizz.sshj.common.CircularBuffer.PlainCircularBuffer;
import org.junit.jupiter.api.Test;
public class CircularBufferTest {
@Test
public void shouldStoreDataCorrectlyWithoutResizing() throws CircularBufferException {
PlainCircularBuffer buffer = new PlainCircularBuffer(256, Integer.MAX_VALUE);
byte[] dataToWrite = getData(500);
buffer.putRawBytes(dataToWrite, 0, 100);
buffer.putRawBytes(dataToWrite, 100, 100);
byte[] dataToRead = new byte[500];
buffer.readRawBytes(dataToRead, 0, 80);
buffer.readRawBytes(dataToRead, 80, 80);
buffer.putRawBytes(dataToWrite, 200, 100);
buffer.readRawBytes(dataToRead, 160, 80);
buffer.putRawBytes(dataToWrite, 300, 100);
buffer.readRawBytes(dataToRead, 240, 80);
buffer.putRawBytes(dataToWrite, 400, 100);
buffer.readRawBytes(dataToRead, 320, 80);
buffer.readRawBytes(dataToRead, 400, 100);
assertEquals(256, buffer.length());
assertArrayEquals(dataToWrite, dataToRead);
}
@Test
public void shouldStoreDataCorrectlyWithResizing() throws CircularBufferException {
PlainCircularBuffer buffer = new PlainCircularBuffer(64, Integer.MAX_VALUE);
byte[] dataToWrite = getData(500);
buffer.putRawBytes(dataToWrite, 0, 100);
buffer.putRawBytes(dataToWrite, 100, 100);
byte[] dataToRead = new byte[500];
buffer.readRawBytes(dataToRead, 0, 80);
buffer.readRawBytes(dataToRead, 80, 80);
buffer.putRawBytes(dataToWrite, 200, 100);
buffer.readRawBytes(dataToRead, 160, 80);
buffer.putRawBytes(dataToWrite, 300, 100);
buffer.readRawBytes(dataToRead, 240, 80);
buffer.putRawBytes(dataToWrite, 400, 100);
buffer.readRawBytes(dataToRead, 320, 80);
buffer.readRawBytes(dataToRead, 400, 100);
assertEquals(256, buffer.length());
assertArrayEquals(dataToWrite, dataToRead);
}
@Test
public void shouldNotOverflowWhenWritingFullLengthToTheEnd() throws CircularBufferException {
PlainCircularBuffer buffer = new PlainCircularBuffer(64, Integer.MAX_VALUE);
byte[] dataToWrite = getData(64);
buffer.putRawBytes(dataToWrite, 0, dataToWrite.length); // should write to the end
assertEquals(64, buffer.available());
assertEquals(64 * 2, buffer.length());
}
@Test
public void shouldNotOverflowWhenWritingFullLengthWrapsAround() throws CircularBufferException {
PlainCircularBuffer buffer = new PlainCircularBuffer(64, Integer.MAX_VALUE);
// Move 1 byte forward.
buffer.putRawBytes(new byte[1], 0, 1);
buffer.readRawBytes(new byte[1], 0, 1);
// Force writes to wrap around.
byte[] dataToWrite = getData(64);
buffer.putRawBytes(dataToWrite, 0, dataToWrite.length); // should wrap around the end
assertEquals(64, buffer.available());
assertEquals(64 * 2, buffer.length());
}
@Test
public void shouldAllowWritingMaxCapacityFromZero() throws CircularBufferException {
PlainCircularBuffer buffer = new PlainCircularBuffer(64, 64);
// Max capacity is always one less than the buffer size.
int maxCapacity = buffer.maxPossibleRemainingCapacity();
assertEquals(buffer.length() - 1, maxCapacity);
byte[] dataToWrite = getData(maxCapacity);
buffer.putRawBytes(dataToWrite, 0, dataToWrite.length);
assertEquals(dataToWrite.length, buffer.available());
assertEquals(64, buffer.length());
}
@Test
public void shouldAllowWritingMaxRemainingCapacity() throws CircularBufferException {
PlainCircularBuffer buffer = new PlainCircularBuffer(64, 64);
final int initiallyWritten = 10;
buffer.putRawBytes(new byte[initiallyWritten], 0, initiallyWritten);
// Max remaining capacity is always one less than the remaining buffer size.
int maxRemainingCapacity = buffer.maxPossibleRemainingCapacity();
assertEquals(buffer.length() - 1 - initiallyWritten, maxRemainingCapacity);
byte[] dataToWrite = getData(maxRemainingCapacity);
buffer.putRawBytes(dataToWrite, 0, dataToWrite.length);
assertEquals(dataToWrite.length + initiallyWritten, buffer.available());
assertEquals(64, buffer.length());
}
@Test
public void shouldAllowWritingMaxRemainingCapacityAfterWrappingAround() throws CircularBufferException {
PlainCircularBuffer buffer = new PlainCircularBuffer(64, 64);
// Cause the internal write pointer to wrap around and be left of the read pointer.
final int initiallyWritten = 40;
buffer.putRawBytes(new byte[initiallyWritten], 0, initiallyWritten);
buffer.readRawBytes(new byte[initiallyWritten], 0, initiallyWritten);
buffer.putRawBytes(new byte[initiallyWritten], 0, initiallyWritten);
// Max remaining capacity is always one less than the remaining buffer size.
int maxRemainingCapacity = buffer.maxPossibleRemainingCapacity();
assertEquals(buffer.length() - 1 - initiallyWritten, maxRemainingCapacity);
byte[] dataToWrite = getData(maxRemainingCapacity);
buffer.putRawBytes(dataToWrite, 0, dataToWrite.length);
assertEquals(dataToWrite.length + initiallyWritten, buffer.available());
assertEquals(64, buffer.length());
}
@Test
public void shouldOverflowWhenWritingOverMaxRemainingCapacity() throws CircularBufferException {
PlainCircularBuffer buffer = new PlainCircularBuffer(64, 64);
final int initiallyWritten = 10;
buffer.putRawBytes(new byte[initiallyWritten], 0, initiallyWritten);
// Max remaining capacity is always one less than the remaining buffer size.
int maxRemainingCapacity = buffer.maxPossibleRemainingCapacity();
assertEquals(buffer.length() - 1 - initiallyWritten, maxRemainingCapacity);
byte[] dataToWrite = getData(maxRemainingCapacity + 1);
assertThrows(CircularBufferException.class, () -> buffer.putRawBytes(dataToWrite, 0, dataToWrite.length));
}
@Test
public void shouldThrowWhenReadingEmptyBuffer() {
PlainCircularBuffer buffer = new PlainCircularBuffer(64, Integer.MAX_VALUE);
assertThrows(CircularBufferException.class, () -> buffer.readRawBytes(new byte[1], 0, 1));
}
@Test
public void shouldThrowWhenReadingMoreThanAvailable() throws CircularBufferException {
PlainCircularBuffer buffer = new PlainCircularBuffer(64, Integer.MAX_VALUE);
buffer.putRawBytes(new byte[1], 0, 1);
assertThrows(CircularBufferException.class, () -> buffer.readRawBytes(new byte[2], 0, 2));
}
@Test
public void shouldThrowOnAboveMaximumInitialSize() {
assertThrows(IllegalArgumentException.class, () -> new PlainCircularBuffer(65, 64));
}
@Test
public void shouldThrowOnMaximumInitialSize() {
assertThrows(IllegalArgumentException.class, () -> new PlainCircularBuffer(Integer.MAX_VALUE, 64));
}
@Test
public void shouldAllowFullCapacity() throws CircularBufferException {
int maxSize = 1024;
PlainCircularBuffer buffer = new PlainCircularBuffer(256, maxSize);
buffer.ensureCapacity(maxSize - 1);
assertEquals(maxSize - 1, buffer.maxPossibleRemainingCapacity());
}
@Test
public void shouldThrowOnTooLargeRequestedCapacity() {
int maxSize = 1024;
PlainCircularBuffer buffer = new PlainCircularBuffer(256, maxSize);
assertThrows(CircularBufferException.class, () -> buffer.ensureCapacity(maxSize));
}
private static byte[] getData(int length) {
byte[] data = new byte[length];
byte nextValue = 0;
for (int i = 0; i < length; ++i) {
data[i] = nextValue++;
}
return data;
}
}

View File

@@ -25,7 +25,6 @@ import net.schmizz.sshj.userauth.password.PasswordFinder;
import net.schmizz.sshj.userauth.password.PasswordUtils;
import net.schmizz.sshj.userauth.password.Resource;
import net.schmizz.sshj.util.KeyUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -226,6 +225,22 @@ public class OpenSSHKeyFileTest {
assertThat(aPrivate.getAlgorithm(), equalTo("EdDSA"));
}
@Test
public void shouldHandlePrivateKeyMissingHeader() {
OpenSSHKeyV1KeyFile keyFile = new OpenSSHKeyV1KeyFile();
keyFile.init(new File("src/test/resources/keyformats/pkcs8"));
final IOException exception = assertThrows(IOException.class, keyFile::getPrivate);
assertTrue(exception.getMessage().contains("header not found"));
}
@Test
public void shouldHandlePrivateKeyMissingFooter() {
final OpenSSHKeyV1KeyFile keyFile = new OpenSSHKeyV1KeyFile();
keyFile.init(new File("src/test/resources/keytypes/test_ed25519_missing_footer"));
final IOException exception = assertThrows(IOException.class, keyFile::getPrivate);
assertTrue(exception.getMessage().contains("footer not found"));
}
@Test
public void shouldLoadProtectedED25519PrivateKeyAes256CTR() throws IOException {
checkOpenSSHKeyV1("src/test/resources/keytypes/ed25519_protected", "sshjtest", false);
@@ -245,7 +260,18 @@ public class OpenSSHKeyFileTest {
}
@Test
public void shouldFailOnIncorrectPassphraseAfterRetries() throws IOException {
public void shouldLoadProtectedEd25519PrivateKeyAES256GCM() throws IOException {
checkOpenSSHKeyV1("src/test/resources/keytypes/ed25519_aes256-gcm", "sshjtest", false);
checkOpenSSHKeyV1("src/test/resources/keytypes/ed25519_aes256-gcm", "sshjtest", true);
}
@Test
public void shouldLoadProtectedEd25519PrivateKeyChaCha20Poly1305() throws IOException {
checkOpenSSHKeyV1("src/test/resources/keytypes/ed25519_chacha20-poly1305", "sshjtest", false);
}
@Test
public void shouldFailOnIncorrectPassphraseAfterRetries() {
assertThrows(KeyDecryptionFailedException.class, () -> {
OpenSSHKeyV1KeyFile keyFile = new OpenSSHKeyV1KeyFile();
keyFile.init(new File("src/test/resources/keytypes/ed25519_aes256cbc.pem"), new PasswordFinder() {

View File

@@ -0,0 +1,237 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.sftp;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.ByteArrayUtils;
import org.apache.sshd.common.util.io.IoUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.io.*;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Testing of remote file rename using different combinations of net.schmizz.sshj.sftp.RenameFlags with
* possible workarounds for SFTP protocol versions lower than 5 that do not natively support these flags.
*/
public class RemoteFileRenameTest {
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@TempDir
public File temp;
@Test
public void shouldOverwriteFileWhenRequested() throws IOException {
// create source file
final byte[] sourceBytes = generateBytes(32);
File sourceFile = newTempFile("shouldOverwriteFileWhenRequested-source.bin", sourceBytes);
// create target file
final byte[] targetBytes = generateBytes(32);
File targetFile = newTempFile("shouldOverwriteFileWhenRequested-target.bin", targetBytes);
// rename with overwrite
Set<RenameFlags> flags = EnumSet.of(RenameFlags.OVERWRITE);
SFTPEngine sftp = sftpInit();
sftp.rename(sourceFile.getPath(), targetFile.getPath(), flags);
// check if rename was successful
assertThat("The source file should not exist anymore", !sourceFile.exists());
assertThat("The contents of the target file should be equal to the contents previously written " +
"to the source file", fileContentEquals(targetFile, sourceBytes));
}
@Test
public void shouldNotOverwriteFileWhenNotRequested() throws IOException {
// create source file
final byte[] sourceBytes = generateBytes(32);
File sourceFile = newTempFile("shouldNotOverwriteFileWhenNotRequested-source.bin", sourceBytes);
// create target file
final byte[] targetBytes = generateBytes(32);
File targetFile = newTempFile("shouldNotOverwriteFileWhenNotRequested-target.bin", targetBytes);
// rename without overwrite -> should fail
Boolean exceptionThrown = false;
Set<RenameFlags> flags = new HashSet<>();
SFTPEngine sftp = sftpInit();
try {
sftp.rename(sourceFile.getPath(), targetFile.getPath(), flags);
}
catch (SFTPException e) {
exceptionThrown = true;
}
// check if rename failed as it should
assertThat("The source file should still exist", sourceFile.exists());
assertThat("The contents of the target file should be equal to the contents previously written to it",
fileContentEquals(targetFile, targetBytes));
assertThat("An appropriate exception should have been thrown", exceptionThrown);
}
@Test
public void shouldUseAtomicRenameWhenRequestedWithOverwriteOnInsufficientProtocolVersion() throws IOException {
// create source file
final byte[] sourceBytes = generateBytes(32);
File sourceFile = newTempFile("shouldUseAtomicRenameWhenRequestedWithOverwriteOnInsufficientProtocolVersion-source.bin", sourceBytes);
// create target file
final byte[] targetBytes = generateBytes(32);
File targetFile = newTempFile("shouldUseAtomicRenameWhenRequestedWithOverwriteOnInsufficientProtocolVersion-target.bin", targetBytes);
// atomic rename with overwrite -> should work
Set<RenameFlags> flags = EnumSet.of(RenameFlags.OVERWRITE, RenameFlags.ATOMIC);
int version = Math.min(SFTPEngine.MAX_SUPPORTED_VERSION, 4); // choose a supported version smaller than 5
SFTPEngine sftp = sftpInit(version);
sftp.rename(sourceFile.getPath(), targetFile.getPath(), flags);
assertThat("The connection should use the requested protocol version", sftp.getOperativeProtocolVersion() == version);
assertThat("The source file should not exist anymore", !sourceFile.exists());
assertThat("The contents of the target file should be equal to the contents previously written " +
"to the source file", fileContentEquals(targetFile, sourceBytes));
}
@Test
public void shouldIgnoreAtomicFlagWhenRequestedWithNativeOnInsufficientProtocolVersion() throws IOException {
// create source file
final byte[] sourceBytes = generateBytes(32);
File sourceFile = newTempFile("shouldIgnoreAtomicFlagWhenRequestedWithNativeOnInsufficientProtocolVersion-source.bin", sourceBytes);
// create target file
final byte[] targetBytes = generateBytes(32);
File targetFile = newTempFile("shouldIgnoreAtomicFlagWhenRequestedWithNativeOnInsufficientProtocolVersion-target.bin", targetBytes);
// atomic flag should be ignored with native
// -> should fail because target exists and overwrite behaviour is not requested
Boolean exceptionThrown = false;
Set<RenameFlags> flags = EnumSet.of(RenameFlags.NATIVE, RenameFlags.ATOMIC);
int version = Math.min(SFTPEngine.MAX_SUPPORTED_VERSION, 4); // choose a supported version smaller than 5
SFTPEngine sftp = sftpInit(version);
try {
sftp.rename(sourceFile.getPath(), targetFile.getPath(), flags);
}
catch (SFTPException e) {
exceptionThrown = true;
}
assertThat("The connection should use the requested protocol version", sftp.getOperativeProtocolVersion() == version);
assertThat("The source file should still exist", sourceFile.exists());
assertThat("The contents of the target file should be equal to the contents previously written to it",
fileContentEquals(targetFile, targetBytes));
assertThat("An appropriate exception should have been thrown", exceptionThrown);
}
@Test
public void shouldFailAtomicRenameWithoutOverwriteOnInsufficientProtocolVersion() throws IOException {
// create source file
final byte[] sourceBytes = generateBytes(32);
File sourceFile = newTempFile("shouldFailAtomicRenameWithoutOverwriteOnInsufficientProtocolVersion-source.bin", sourceBytes);
// create target file
File targetFile = new File(temp, "shouldFailAtomicRenameWithoutOverwriteOnInsufficientProtocolVersion-target.bin");
// atomic rename without overwrite -> should fail
Boolean exceptionThrown = false;
Set<RenameFlags> flags = EnumSet.of(RenameFlags.ATOMIC);
int version = Math.min(SFTPEngine.MAX_SUPPORTED_VERSION, 4); // choose a supported version smaller than 5
SFTPEngine sftp = sftpInit(version);
try {
sftp.rename(sourceFile.getPath(), targetFile.getPath(), flags);
}
catch (SFTPException e) {
exceptionThrown = true;
}
// check if rename failed as it should (for version < 5)
assertThat("The connection should use the requested protocol version", sftp.getOperativeProtocolVersion() == version);
assertThat("The source file should still exist", sourceFile.exists());
assertThat("The target file should not exist", !targetFile.exists());
assertThat("An appropriate exception should have been thrown", exceptionThrown);
}
@Test
public void shouldDoAtomicRenameOnSufficientProtocolVersion() throws IOException {
// This test will be relevant as soon as sshj supports SFTP protocol version >= 5
if (SFTPEngine.MAX_SUPPORTED_VERSION >= 5) {
// create source file
final byte[] sourceBytes = generateBytes(32);
File sourceFile = newTempFile("shouldDoAtomicRenameOnSufficientProtocolVersion-source.bin", sourceBytes);
// create target file
File targetFile = new File(temp, "shouldDoAtomicRenameOnSufficientProtocolVersion-target.bin");
// atomic rename without overwrite -> should work on version >= 5
Set<RenameFlags> flags = EnumSet.of(RenameFlags.ATOMIC);
SFTPEngine sftp = sftpInit();
sftp.rename(sourceFile.getPath(), targetFile.getPath(), flags);
// check if rename worked as it should (for version >= 5)
assertThat("The connection should use the requested protocol version", sftp.getOperativeProtocolVersion() >= 5);
assertThat("The source file should not exist anymore", !sourceFile.exists());
assertThat("The target file should exist", targetFile.exists());
}
else {
// Ignored - cannot test because client does not support protocol version >= 5
}
}
private byte[] generateBytes(Integer size) {
byte[] randomBytes = new byte[size];
Random rnd = new Random();
rnd.nextBytes(randomBytes);
return randomBytes;
}
private File newTempFile(String name, byte[] content) throws IOException {
File tmpFile = new File(temp, name);
try (OutputStream fStream = new FileOutputStream(tmpFile)) {
IoUtils.copy(new ByteArrayInputStream(content), fStream);
}
return tmpFile;
}
private boolean fileContentEquals(File testFile, byte[] testBytes) throws IOException {
return ByteArrayUtils.equals(
IoUtils.toByteArray(new FileInputStream(testFile)), 0,
testBytes, 0,
testBytes.length);
}
private SFTPEngine sftpInit() throws IOException {
return sftpInit(SFTPEngine.MAX_SUPPORTED_VERSION);
}
private SFTPEngine sftpInit(int version) throws IOException {
SSHClient ssh = fixture.setupConnectedDefaultClient();
ssh.authPassword("test", "test");
SFTPEngine sftp = new SFTPEngine(ssh).init(version);
return sftp;
}
}

View File

@@ -112,7 +112,7 @@ public class KeyExchangeRepeatTest {
}
private SSHPacket getKexinitPacket() {
SSHPacket kexinitPacket = new Proposal(config, Collections.emptyList()).getPacket();
SSHPacket kexinitPacket = new Proposal(config, Collections.emptyList(), false).getPacket();
kexinitPacket.rpos(kexinitPacket.rpos() + 1);
return kexinitPacket;
}

View File

@@ -0,0 +1,236 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.transport;
import java.math.BigInteger;
import java.util.Collections;
import java.util.List;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.common.DisconnectReason;
import net.schmizz.sshj.common.Factory;
import net.schmizz.sshj.common.Message;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.kex.KeyExchange;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class KeyExchangerStrictKeyExchangeTest {
private TransportImpl transport;
private DefaultConfig config;
private KeyExchanger keyExchanger;
@BeforeEach
void setUp() throws Exception {
KeyExchange kex = mock(KeyExchange.class, Mockito.RETURNS_DEEP_STUBS);
transport = mock(TransportImpl.class, Mockito.RETURNS_DEEP_STUBS);
config = new DefaultConfig() {
@Override
protected void initKeyExchangeFactories() {
setKeyExchangeFactories(Collections.singletonList(new Factory.Named<>() {
@Override
public KeyExchange create() {
return kex;
}
@Override
public String getName() {
return "mock-kex";
}
}));
}
};
when(transport.getConfig()).thenReturn(config);
when(transport.getServerID()).thenReturn("some server id");
when(transport.getClientID()).thenReturn("some client id");
when(kex.next(any(), any())).thenReturn(true);
when(kex.getH()).thenReturn(new byte[0]);
when(kex.getK()).thenReturn(BigInteger.ZERO);
when(kex.getHash().digest()).thenReturn(new byte[10]);
keyExchanger = new KeyExchanger(transport);
keyExchanger.addHostKeyVerifier(new PromiscuousVerifier());
}
@Test
void initialConditions() {
assertThat(keyExchanger.isKexDone()).isFalse();
assertThat(keyExchanger.isKexOngoing()).isFalse();
assertThat(keyExchanger.isStrictKex()).isFalse();
assertThat(keyExchanger.isInitialKex()).isTrue();
}
@Test
void startInitialKex() throws Exception {
ArgumentCaptor<SSHPacket> sshPacketCaptor = ArgumentCaptor.forClass(SSHPacket.class);
when(transport.write(sshPacketCaptor.capture())).thenReturn(0L);
keyExchanger.startKex(false);
assertThat(keyExchanger.isKexDone()).isFalse();
assertThat(keyExchanger.isKexOngoing()).isTrue();
assertThat(keyExchanger.isStrictKex()).isFalse();
assertThat(keyExchanger.isInitialKex()).isTrue();
SSHPacket sshPacket = sshPacketCaptor.getValue();
List<String> kex = new Proposal(sshPacket).getKeyExchangeAlgorithms();
assertThat(kex).endsWith("kex-strict-c-v00@openssh.com");
}
@Test
void receiveKexInitWithoutServerFlag() throws Exception {
keyExchanger.startKex(false);
keyExchanger.handle(Message.KEXINIT, getKexInitPacket(false));
assertThat(keyExchanger.isKexDone()).isFalse();
assertThat(keyExchanger.isKexOngoing()).isTrue();
assertThat(keyExchanger.isStrictKex()).isFalse();
assertThat(keyExchanger.isInitialKex()).isTrue();
}
@Test
void finishNonStrictKex() throws Exception {
keyExchanger.startKex(false);
keyExchanger.handle(Message.KEXINIT, getKexInitPacket(false));
keyExchanger.handle(Message.KEXDH_31, new SSHPacket(Message.KEXDH_31));
keyExchanger.handle(Message.NEWKEYS, new SSHPacket(Message.NEWKEYS));
assertThat(keyExchanger.isKexDone()).isTrue();
assertThat(keyExchanger.isKexOngoing()).isFalse();
assertThat(keyExchanger.isStrictKex()).isFalse();
assertThat(keyExchanger.isInitialKex()).isFalse();
verify(transport.getEncoder(), never()).resetSequenceNumber();
verify(transport.getDecoder(), never()).resetSequenceNumber();
}
@Test
void receiveKexInitWithServerFlag() throws Exception {
keyExchanger.startKex(false);
keyExchanger.handle(Message.KEXINIT, getKexInitPacket(true));
assertThat(keyExchanger.isKexDone()).isFalse();
assertThat(keyExchanger.isKexOngoing()).isTrue();
assertThat(keyExchanger.isStrictKex()).isTrue();
assertThat(keyExchanger.isInitialKex()).isTrue();
}
@Test
void strictKexInitIsNotFirstPacket() throws Exception {
when(transport.getDecoder().getSequenceNumber()).thenReturn(1L);
keyExchanger.startKex(false);
assertThatExceptionOfType(TransportException.class).isThrownBy(
() -> keyExchanger.handle(Message.KEXINIT, getKexInitPacket(true))
).satisfies(e -> {
assertThat(e.getDisconnectReason()).isEqualTo(DisconnectReason.KEY_EXCHANGE_FAILED);
assertThat(e.getMessage()).isEqualTo("SSH_MSG_KEXINIT was not first package during strict key exchange");
});
}
@Test
void finishStrictKex() throws Exception {
keyExchanger.startKex(false);
keyExchanger.handle(Message.KEXINIT, getKexInitPacket(true));
verify(transport.getEncoder(), never()).resetSequenceNumber();
keyExchanger.handle(Message.KEXDH_31, new SSHPacket(Message.KEXDH_31));
verify(transport.getEncoder()).resetSequenceNumber();
verify(transport.getDecoder(), never()).resetSequenceNumber();
keyExchanger.handle(Message.NEWKEYS, new SSHPacket(Message.NEWKEYS));
verify(transport.getDecoder()).resetSequenceNumber();
assertThat(keyExchanger.isKexDone()).isTrue();
assertThat(keyExchanger.isKexOngoing()).isFalse();
assertThat(keyExchanger.isStrictKex()).isTrue();
assertThat(keyExchanger.isInitialKex()).isFalse();
}
@Test
void noClientFlagInSecondStrictKex() throws Exception {
keyExchanger.startKex(false);
keyExchanger.handle(Message.KEXINIT, getKexInitPacket(true));
keyExchanger.handle(Message.KEXDH_31, new SSHPacket(Message.KEXDH_31));
keyExchanger.handle(Message.NEWKEYS, new SSHPacket(Message.NEWKEYS));
ArgumentCaptor<SSHPacket> sshPacketCaptor = ArgumentCaptor.forClass(SSHPacket.class);
when(transport.write(sshPacketCaptor.capture())).thenReturn(0L);
when(transport.isAuthenticated()).thenReturn(true);
keyExchanger.startKex(false);
assertThat(keyExchanger.isKexDone()).isFalse();
assertThat(keyExchanger.isKexOngoing()).isTrue();
assertThat(keyExchanger.isStrictKex()).isTrue();
assertThat(keyExchanger.isInitialKex()).isFalse();
SSHPacket sshPacket = sshPacketCaptor.getValue();
List<String> kex = new Proposal(sshPacket).getKeyExchangeAlgorithms();
assertThat(kex).doesNotContain("kex-strict-c-v00@openssh.com");
}
@Test
void serverFlagIsIgnoredInSecondKex() throws Exception {
keyExchanger.startKex(false);
keyExchanger.handle(Message.KEXINIT, getKexInitPacket(false));
keyExchanger.handle(Message.KEXDH_31, new SSHPacket(Message.KEXDH_31));
keyExchanger.handle(Message.NEWKEYS, new SSHPacket(Message.NEWKEYS));
ArgumentCaptor<SSHPacket> sshPacketCaptor = ArgumentCaptor.forClass(SSHPacket.class);
when(transport.write(sshPacketCaptor.capture())).thenReturn(0L);
when(transport.isAuthenticated()).thenReturn(true);
keyExchanger.startKex(false);
keyExchanger.handle(Message.KEXINIT, getKexInitPacket(true));
assertThat(keyExchanger.isKexDone()).isFalse();
assertThat(keyExchanger.isKexOngoing()).isTrue();
assertThat(keyExchanger.isStrictKex()).isFalse();
assertThat(keyExchanger.isInitialKex()).isFalse();
SSHPacket sshPacket = sshPacketCaptor.getValue();
List<String> kex = new Proposal(sshPacket).getKeyExchangeAlgorithms();
assertThat(kex).doesNotContain("kex-strict-c-v00@openssh.com");
}
private SSHPacket getKexInitPacket(boolean withServerFlag) {
SSHPacket kexinitPacket = new Proposal(config, Collections.emptyList(), true).getPacket();
if (withServerFlag) {
int finalWpos = kexinitPacket.wpos();
kexinitPacket.wpos(22);
kexinitPacket.putString("mock-kex,kex-strict-s-v00@openssh.com");
kexinitPacket.wpos(finalWpos);
}
kexinitPacket.rpos(kexinitPacket.rpos() + 1);
return kexinitPacket;
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.transport;
import java.lang.reflect.Field;
import net.schmizz.sshj.Config;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.common.DisconnectReason;
import net.schmizz.sshj.common.Message;
import net.schmizz.sshj.common.SSHPacket;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.EnumSource.Mode;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class TransportImplStrictKeyExchangeTest {
private final Config config = new DefaultConfig();
private final Transport transport = new TransportImpl(config);
private final KeyExchanger kexer = mock(KeyExchanger.class);
private final Decoder decoder = mock(Decoder.class);
@BeforeEach
void setUp() throws Exception {
Field kexerField = TransportImpl.class.getDeclaredField("kexer");
kexerField.setAccessible(true);
kexerField.set(transport, kexer);
Field decoderField = TransportImpl.class.getDeclaredField("decoder");
decoderField.setAccessible(true);
decoderField.set(transport, decoder);
}
@Test
void throwExceptionOnWrapDuringInitialKex() {
when(kexer.isInitialKex()).thenReturn(true);
when(decoder.isSequenceNumberAtMax()).thenReturn(true);
assertThatExceptionOfType(TransportException.class).isThrownBy(
() -> transport.handle(Message.KEXINIT, new SSHPacket(Message.KEXINIT))
).satisfies(e -> {
assertThat(e.getDisconnectReason()).isEqualTo(DisconnectReason.KEY_EXCHANGE_FAILED);
assertThat(e.getMessage()).isEqualTo("Sequence number of decoder is about to wrap during initial key exchange");
});
}
@ParameterizedTest
@EnumSource(value = Message.class, mode = Mode.EXCLUDE, names = {
"DISCONNECT", "KEXINIT", "NEWKEYS", "KEXDH_INIT", "KEXDH_31", "KEX_DH_GEX_INIT", "KEX_DH_GEX_REPLY", "KEX_DH_GEX_REQUEST"
})
void forbidUnexpectedPacketsDuringStrictKeyExchange(Message message) {
when(kexer.isInitialKex()).thenReturn(true);
when(decoder.isSequenceNumberAtMax()).thenReturn(false);
when(kexer.isStrictKex()).thenReturn(true);
assertThatExceptionOfType(TransportException.class).isThrownBy(
() -> transport.handle(message, new SSHPacket(message))
).satisfies(e -> {
assertThat(e.getDisconnectReason()).isEqualTo(DisconnectReason.KEY_EXCHANGE_FAILED);
assertThat(e.getMessage()).isEqualTo("Unexpected packet type during initial strict key exchange");
});
}
@ParameterizedTest
@EnumSource(value = Message.class, mode = Mode.INCLUDE, names = {
"KEXINIT", "NEWKEYS", "KEXDH_INIT", "KEXDH_31", "KEX_DH_GEX_INIT", "KEX_DH_GEX_REPLY", "KEX_DH_GEX_REQUEST"
})
void expectedPacketsDuringStrictKeyExchangeAreHandled(Message message) throws Exception {
when(kexer.isInitialKex()).thenReturn(true);
when(decoder.isSequenceNumberAtMax()).thenReturn(false);
when(kexer.isStrictKex()).thenReturn(true);
SSHPacket sshPacket = new SSHPacket(message);
assertThatCode(
() -> transport.handle(message, sshPacket)
).doesNotThrowAnyException();
verify(kexer).handle(message, sshPacket);
}
@Test
void disconnectIsAllowedDuringStrictKeyExchange() {
when(kexer.isInitialKex()).thenReturn(true);
when(decoder.isSequenceNumberAtMax()).thenReturn(false);
when(kexer.isStrictKex()).thenReturn(true);
SSHPacket sshPacket = new SSHPacket();
sshPacket.putUInt32(DisconnectReason.SERVICE_NOT_AVAILABLE.toInt());
sshPacket.putString("service is down for maintenance");
assertThatExceptionOfType(TransportException.class).isThrownBy(
() -> transport.handle(Message.DISCONNECT, sshPacket)
).satisfies(e -> {
assertThat(e.getDisconnectReason()).isEqualTo(DisconnectReason.SERVICE_NOT_AVAILABLE);
assertThat(e.getMessage()).isEqualTo("service is down for maintenance");
});
}
}

View File

@@ -0,0 +1,9 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAAFmFlczI1Ni1nY21Ab3BlbnNzaC5jb20AAAAGYmNyeXB0AA
AAGAAAABDpxH70vULcphyZoyd8Roc8AAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAA
ID3cbY1HvyY8fXNrcESSpXm/3nGKpjxNjrlD+U5oMVmxAAAAoGXyMyKfXmGAVGLI3jbwk5
gqrHAEFI5HHuYfW1DAAjSlj41paovl9tk7jZLIGslLUrUkN8Ac6ACNYuCWQZPgPr5mXHDx
x+8GpdYPrgamB74lVwEPwk1BVjJRYUDRJ0SWyHagybITJhutq7yH+hZS+S05q2EeVee4Cn
ZqESfmPZwdHg41IkdVTrZcLzadjPrcqrGzg1P7T9zl9hLD2QfBmO+XN2FPM+ufOGxpHHyJ
SY/c
-----END OPENSSH PRIVATE KEY-----

View File

@@ -0,0 +1 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID3cbY1HvyY8fXNrcESSpXm/3nGKpjxNjrlD+U5oMVmx

View File

@@ -0,0 +1,9 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAAHWNoYWNoYTIwLXBvbHkxMzA1QG9wZW5zc2guY29tAAAABm
JjcnlwdAAAABgAAAAQilqbRL4q3X9kEqWdTsD5/gAAABAAAAABAAAAMwAAAAtzc2gtZWQy
NTUxOQAAACCpvtXUZPONb1XDjLkHmP5mQrGryGaQsA68Nb+OAjaaEgAAAJh+Repmt76g31
jlD1ITaJU298ZU3rFWgA/Hs3xnOTNPjhMMu9nzfoZAu0fraE1MBVaEgNKRpw7SG+2eDBOo
3fvN3lF15i7Q8YHZd9alfcUg3FrvBzjd0Edx4AQxbSueibPFaqnwmVk/YzDiQHwlyWfA1x
HbqxrbJf1S0i8Bt5OjLK6woGk0/lfWJmy82xIa1sa3ONkPVjaJncm/f2SKV7t2k1UP9/jx
dLA=
-----END OPENSSH PRIVATE KEY-----

View File

@@ -0,0 +1 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKm+1dRk841vVcOMuQeY/mZCsavIZpCwDrw1v44CNpoS

View File

@@ -0,0 +1,6 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACAwHSYkZJATPMgvLHkxKAJ9j38Gyyq5HGoWdMcT6FiAiQAAAJDimgR84poE
fAAAAAtzc2gtZWQyNTUxOQAAACAwHSYkZJATPMgvLHkxKAJ9j38Gyyq5HGoWdMcT6FiAiQ
AAAECmsckQycWnfGQK6XtQpaMGODbAkMQOdJNK6XJSipB7dDAdJiRkkBM8yC8seTEoAn2P
fwbLKrkcahZ0xxPoWICJAAAACXJvb3RAc3NoagECAwQ=