mirror of
https://github.com/hierynomus/sshj.git
synced 2025-12-06 07:10:53 +03:00
Compare commits
22 Commits
v0.38.0
...
88655bdf68
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88655bdf68 | ||
|
|
5ff27ec597 | ||
|
|
2d3e045190 | ||
|
|
01a26fd9fd | ||
|
|
38770b33d9 | ||
|
|
31ed35407c | ||
|
|
f4f8071020 | ||
|
|
f525ed0e5b | ||
|
|
93046f315e | ||
|
|
54376b7622 | ||
|
|
f0e92c920f | ||
|
|
09e2ca512e | ||
|
|
607e80591c | ||
|
|
079cb08fb0 | ||
|
|
cf340c2a09 | ||
|
|
586a66420e | ||
|
|
624fe839cb | ||
|
|
81d77d277c | ||
|
|
70af58d199 | ||
|
|
c0d1519ee2 | ||
|
|
03f8b2224d | ||
|
|
f94444bc53 |
8
.github/workflows/gradle.yml
vendored
8
.github/workflows/gradle.yml
vendored
@@ -14,9 +14,9 @@ jobs:
|
||||
name: Build with Java 11
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Java 11
|
||||
uses: actions/setup-java@v3
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: 11
|
||||
@@ -31,9 +31,9 @@ jobs:
|
||||
name: Integration test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
|
||||
- uses: actions/setup-java@v3
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: 11
|
||||
|
||||
8
.github/workflows/release.yml
vendored
8
.github/workflows/release.yml
vendored
@@ -13,11 +13,11 @@ jobs:
|
||||
name: Build with Java 12
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Set up JDK 12
|
||||
uses: actions/setup-java@v2
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: 12
|
||||
@@ -30,10 +30,10 @@ jobs:
|
||||
needs: [java12]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-java@v2
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: 12
|
||||
|
||||
@@ -115,7 +115,7 @@ SSHJ 0.38.0 (2024-01-02)::
|
||||
* 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
|
||||
* Moved tests 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)::
|
||||
|
||||
27
build.gradle
27
build.gradle
@@ -9,7 +9,7 @@ plugins {
|
||||
id 'pl.allegro.tech.build.axion-release' version '1.15.3'
|
||||
id "com.github.hierynomus.license" version "0.16.1"
|
||||
id "com.bmuschko.docker-remote-api" version "9.2.1"
|
||||
id 'ru.vyarus.github-info' version '1.5.0'
|
||||
id 'ru.vyarus.github-info' version '2.0.0'
|
||||
id "io.github.gradle-nexus.publish-plugin" version "1.3.0"
|
||||
}
|
||||
|
||||
@@ -22,6 +22,11 @@ repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
github {
|
||||
user 'hierynomus'
|
||||
license 'Apache'
|
||||
}
|
||||
|
||||
scmVersion {
|
||||
tag {
|
||||
prefix = 'v'
|
||||
@@ -41,11 +46,11 @@ compileJava {
|
||||
|
||||
configurations.implementation.transitive = false
|
||||
|
||||
def bouncycastleVersion = "1.75"
|
||||
def sshdVersion = "2.10.0"
|
||||
def bouncycastleVersion = "1.80"
|
||||
def sshdVersion = "2.14.0"
|
||||
|
||||
dependencies {
|
||||
implementation "org.slf4j:slf4j-api:2.0.7"
|
||||
implementation "org.slf4j:slf4j-api:2.0.16"
|
||||
implementation "org.bouncycastle:bcprov-jdk18on:$bouncycastleVersion"
|
||||
implementation "org.bouncycastle:bcpkix-jdk18on:$bouncycastleVersion"
|
||||
implementation "com.hierynomus:asn-one:0.6.0"
|
||||
@@ -59,7 +64,6 @@ license {
|
||||
java = 'SLASHSTAR_STYLE'
|
||||
}
|
||||
excludes([
|
||||
'**/sshj/common/Base64.java',
|
||||
'**/com/hierynomus/sshj/userauth/keyprovider/bcrypt/*.java',
|
||||
'**/files/test_file_*.txt',
|
||||
])
|
||||
@@ -86,7 +90,7 @@ testing {
|
||||
configureEach {
|
||||
useJUnitJupiter()
|
||||
dependencies {
|
||||
implementation "org.slf4j:slf4j-api:2.0.7"
|
||||
implementation "org.slf4j:slf4j-api:2.0.16"
|
||||
implementation 'org.spockframework:spock-core:2.3-groovy-3.0'
|
||||
implementation "org.mockito:mockito-core:4.11.0"
|
||||
implementation "org.assertj:assertj-core:3.24.2"
|
||||
@@ -94,7 +98,7 @@ testing {
|
||||
implementation "org.apache.sshd:sshd-core:$sshdVersion"
|
||||
implementation "org.apache.sshd:sshd-sftp:$sshdVersion"
|
||||
implementation "org.apache.sshd:sshd-scp:$sshdVersion"
|
||||
implementation "ch.qos.logback:logback-classic:1.3.8"
|
||||
implementation "ch.qos.logback:logback-classic:1.3.15"
|
||||
implementation 'org.glassfish.grizzly:grizzly-http-server:3.0.1'
|
||||
}
|
||||
|
||||
@@ -130,8 +134,8 @@ testing {
|
||||
integrationTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation 'org.testcontainers:testcontainers:1.18.3'
|
||||
implementation 'org.testcontainers:junit-jupiter:1.18.3'
|
||||
implementation 'org.testcontainers:testcontainers:1.20.4'
|
||||
implementation 'org.testcontainers:junit-jupiter:1.20.4'
|
||||
}
|
||||
|
||||
sources {
|
||||
@@ -203,11 +207,6 @@ sourcesJar {
|
||||
}
|
||||
}
|
||||
|
||||
github {
|
||||
user 'hierynomus'
|
||||
license 'Apache'
|
||||
}
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
maven(MavenPublication) {
|
||||
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Binary file not shown.
4
gradle/wrapper/gradle-wrapper.properties
vendored
4
gradle/wrapper/gradle-wrapper.properties
vendored
@@ -1,5 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
|
||||
43
gradlew
vendored
43
gradlew
vendored
@@ -15,6 +15,8 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
@@ -55,7 +57,7 @@
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
@@ -80,13 +82,11 @@ do
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
@@ -133,22 +133,29 @@ location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
@@ -193,11 +200,15 @@ if "$cygwin" || "$msys" ; then
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
@@ -205,6 +216,12 @@ set -- \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
|
||||
33
gradlew.bat
vendored
33
gradlew.bat
vendored
@@ -13,6 +13,8 @@
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@@ -26,6 +28,7 @@ if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
@@ -56,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
@@ -75,13 +78,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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 static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
import com.hierynomus.sshj.SshdContainer;
|
||||
|
||||
import net.schmizz.sshj.SSHClient;
|
||||
import net.schmizz.sshj.sftp.FileAttributes;
|
||||
import net.schmizz.sshj.sftp.SFTPClient;
|
||||
|
||||
@Testcontainers
|
||||
public class SftpIntegrationTest {
|
||||
@Container
|
||||
private static SshdContainer sshd = new SshdContainer();
|
||||
|
||||
@Test
|
||||
public void shouldCheckFileExistsForNonExistingFile_GH894() throws Throwable {
|
||||
try (SSHClient client = sshd.getConnectedClient()) {
|
||||
client.authPublickey("sshj", "src/test/resources/id_rsa");
|
||||
try (SFTPClient sftp = client.newSFTPClient()) {
|
||||
String file = "/home/sshj/i_do_not_exist.txt";
|
||||
FileAttributes exists = sftp.statExistence(file);
|
||||
assertNull(exists);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,15 +18,26 @@ package com.hierynomus.sshj.transport.kex;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
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.keepalive.KeepAlive;
|
||||
import net.schmizz.keepalive.KeepAliveProvider;
|
||||
import net.schmizz.sshj.Config;
|
||||
import net.schmizz.sshj.DefaultConfig;
|
||||
import net.schmizz.sshj.SSHClient;
|
||||
import net.schmizz.sshj.common.Message;
|
||||
import net.schmizz.sshj.common.SSHPacket;
|
||||
import net.schmizz.sshj.connection.ConnectionImpl;
|
||||
import net.schmizz.sshj.transport.TransportException;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
@@ -62,14 +73,27 @@ class StrictKeyExchangeTest {
|
||||
watchedLoggers.add(logger);
|
||||
}
|
||||
|
||||
@Test
|
||||
void strictKeyExchange() throws Throwable {
|
||||
try (SSHClient client = sshd.getConnectedClient()) {
|
||||
private static Stream<Arguments> strictKeyExchange() {
|
||||
Config defaultConfig = new DefaultConfig();
|
||||
Config heartbeaterConfig = new DefaultConfig();
|
||||
heartbeaterConfig.setKeepAliveProvider(new KeepAliveProvider() {
|
||||
@Override
|
||||
public KeepAlive provide(ConnectionImpl connection) {
|
||||
return new HotLoopHeartbeater(connection);
|
||||
}
|
||||
});
|
||||
return Stream.of(defaultConfig, heartbeaterConfig).map(Arguments::of);
|
||||
}
|
||||
|
||||
@MethodSource
|
||||
@ParameterizedTest
|
||||
void strictKeyExchange(Config config) throws Throwable {
|
||||
try (SSHClient client = sshd.getConnectedClient(config)) {
|
||||
client.authPublickey("sshj", "src/itest/resources/keyfiles/id_rsa_opensshv1");
|
||||
assertTrue(client.isAuthenticated());
|
||||
}
|
||||
List<String> keyExchangerLogs = getLogs("KeyExchanger");
|
||||
assertThat(keyExchangerLogs).containsSequence(
|
||||
assertThat(keyExchangerLogs).contains(
|
||||
"Initiating key exchange",
|
||||
"Sending SSH_MSG_KEXINIT",
|
||||
"Received SSH_MSG_KEXINIT",
|
||||
@@ -78,7 +102,7 @@ class StrictKeyExchangeTest {
|
||||
List<String> decoderLogs = getLogs("Decoder").stream()
|
||||
.map(log -> log.split(":")[0])
|
||||
.collect(Collectors.toList());
|
||||
assertThat(decoderLogs).containsExactly(
|
||||
assertThat(decoderLogs).startsWith(
|
||||
"Received packet #0",
|
||||
"Received packet #1",
|
||||
"Received packet #2",
|
||||
@@ -90,7 +114,7 @@ class StrictKeyExchangeTest {
|
||||
List<String> encoderLogs = getLogs("Encoder").stream()
|
||||
.map(log -> log.split(":")[0])
|
||||
.collect(Collectors.toList());
|
||||
assertThat(encoderLogs).containsExactly(
|
||||
assertThat(encoderLogs).startsWith(
|
||||
"Encoding packet #0",
|
||||
"Encoding packet #1",
|
||||
"Encoding packet #2",
|
||||
@@ -108,4 +132,22 @@ class StrictKeyExchangeTest {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static class HotLoopHeartbeater extends KeepAlive {
|
||||
|
||||
HotLoopHeartbeater(ConnectionImpl conn) {
|
||||
super(conn, "sshj-Heartbeater");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doKeepAlive() throws TransportException {
|
||||
conn.getTransport().write(new SSHPacket(Message.IGNORE));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
*/
|
||||
package com.hierynomus.sshj.common;
|
||||
|
||||
import org.bouncycastle.openssl.EncryptionException;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
@@ -32,7 +30,7 @@ public class KeyDecryptionFailedException extends IOException {
|
||||
super(MESSAGE);
|
||||
}
|
||||
|
||||
public KeyDecryptionFailedException(EncryptionException cause) {
|
||||
public KeyDecryptionFailedException(IOException cause) {
|
||||
super(MESSAGE, cause);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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.sftp.RemoteResourceSelector.Result;
|
||||
import net.schmizz.sshj.sftp.RemoteResourceFilter;
|
||||
|
||||
public class RemoteResourceFilterConverter {
|
||||
|
||||
public static RemoteResourceSelector selectorFrom(RemoteResourceFilter filter) {
|
||||
if (filter == null) {
|
||||
return RemoteResourceSelector.ALL;
|
||||
}
|
||||
|
||||
return resource -> filter.accept(resource) ? Result.ACCEPT : Result.CONTINUE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* 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 net.schmizz.sshj.sftp.RemoteResourceInfo;
|
||||
|
||||
public interface RemoteResourceSelector {
|
||||
public static RemoteResourceSelector ALL = new RemoteResourceSelector() {
|
||||
@Override
|
||||
public Result select(RemoteResourceInfo resource) {
|
||||
return Result.ACCEPT;
|
||||
}
|
||||
};
|
||||
|
||||
enum Result {
|
||||
/**
|
||||
* Accept the remote resource and add it to the result.
|
||||
*/
|
||||
ACCEPT,
|
||||
|
||||
/**
|
||||
* Do not add the remote resource to the result and continue with the next.
|
||||
*/
|
||||
CONTINUE,
|
||||
|
||||
/**
|
||||
* Do not add the remote resource to the result and stop further execution.
|
||||
*/
|
||||
BREAK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether the remote resource should be included in the result and whether execution should continue.
|
||||
*/
|
||||
Result select(RemoteResourceInfo resource);
|
||||
}
|
||||
@@ -15,6 +15,8 @@
|
||||
*/
|
||||
package com.hierynomus.sshj.transport.verification;
|
||||
|
||||
import net.schmizz.sshj.common.Base64DecodingException;
|
||||
import net.schmizz.sshj.common.Base64Decoder;
|
||||
import net.schmizz.sshj.common.IOUtils;
|
||||
import net.schmizz.sshj.common.SSHException;
|
||||
import net.schmizz.sshj.transport.mac.MAC;
|
||||
@@ -26,9 +28,13 @@ import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.hierynomus.sshj.transport.mac.Macs;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class KnownHostMatchers {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(KnownHostMatchers.class);
|
||||
|
||||
public static HostMatcher createMatcher(String hostEntry) throws SSHException {
|
||||
if (hostEntry.contains(",")) {
|
||||
return new AnyHostMatcher(hostEntry);
|
||||
@@ -80,17 +86,22 @@ public class KnownHostMatchers {
|
||||
|
||||
@Override
|
||||
public boolean match(String hostname) throws IOException {
|
||||
try {
|
||||
return hash.equals(hashHost(hostname));
|
||||
} catch (Base64DecodingException err) {
|
||||
log.warn("Hostname [{}] not matched: salt decoding failed", hostname, err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String hashHost(String host) throws IOException {
|
||||
private String hashHost(String host) throws IOException, Base64DecodingException {
|
||||
sha1.init(getSaltyBytes());
|
||||
return "|1|" + salt + "|" + Base64.getEncoder().encodeToString(sha1.doFinal(host.getBytes(IOUtils.UTF8)));
|
||||
}
|
||||
|
||||
private byte[] getSaltyBytes() {
|
||||
private byte[] getSaltyBytes() throws IOException, Base64DecodingException {
|
||||
if (saltyBytes == null) {
|
||||
saltyBytes = Base64.getDecoder().decode(salt);
|
||||
saltyBytes = Base64Decoder.decode(salt);
|
||||
}
|
||||
return saltyBytes;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
*/
|
||||
package com.hierynomus.sshj.userauth.keyprovider;
|
||||
|
||||
import net.schmizz.sshj.common.Base64DecodingException;
|
||||
import net.schmizz.sshj.common.Base64Decoder;
|
||||
import net.schmizz.sshj.common.Buffer;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
|
||||
@@ -23,7 +25,6 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Base64;
|
||||
|
||||
public class OpenSSHKeyFileUtil {
|
||||
private OpenSSHKeyFileUtil() {
|
||||
@@ -54,9 +55,10 @@ public class OpenSSHKeyFileUtil {
|
||||
if (!keydata.isEmpty()) {
|
||||
String[] parts = keydata.trim().split("\\s+");
|
||||
if (parts.length >= 2) {
|
||||
byte[] decodedPublicKey = Base64Decoder.decode(parts[1]);
|
||||
return new ParsedPubKey(
|
||||
KeyType.fromString(parts[0]),
|
||||
new Buffer.PlainBuffer(Base64.getDecoder().decode(parts[1])).readPublicKey()
|
||||
new Buffer.PlainBuffer(decodedPublicKey).readPublicKey()
|
||||
);
|
||||
} else {
|
||||
throw new IOException("Got line with only one column");
|
||||
@@ -64,6 +66,8 @@ public class OpenSSHKeyFileUtil {
|
||||
}
|
||||
}
|
||||
throw new IOException("Public key file is blank");
|
||||
} catch (Base64DecodingException err) {
|
||||
throw new IOException("Public key decoding failed", err);
|
||||
} finally {
|
||||
br.close();
|
||||
}
|
||||
|
||||
@@ -20,48 +20,37 @@ 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 com.hierynomus.sshj.userauth.keyprovider.bcrypt.BCrypt;
|
||||
import net.i2p.crypto.eddsa.EdDSAPrivateKey;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec;
|
||||
import net.schmizz.sshj.common.Buffer;
|
||||
import net.schmizz.sshj.common.*;
|
||||
import net.schmizz.sshj.common.Buffer.PlainBuffer;
|
||||
import net.schmizz.sshj.common.ByteArrayUtils;
|
||||
import net.schmizz.sshj.common.IOUtils;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.common.SSHRuntimeException;
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
import net.schmizz.sshj.transport.cipher.Cipher;
|
||||
import net.schmizz.sshj.userauth.keyprovider.BaseFileKeyProvider;
|
||||
import net.schmizz.sshj.userauth.keyprovider.FileKeyProvider;
|
||||
import net.schmizz.sshj.userauth.keyprovider.KeyFormat;
|
||||
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 net.schmizz.sshj.userauth.password.PasswordFinder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.*;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.*;
|
||||
import java.security.spec.ECPrivateKeySpec;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyPair;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
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
|
||||
* The format is described in the following document: <a href="https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key">Key Protocol</a>
|
||||
*/
|
||||
public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
|
||||
private static final String BEGIN = "-----BEGIN ";
|
||||
@@ -89,6 +78,12 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
|
||||
|
||||
private PublicKey pubKey;
|
||||
|
||||
@Override
|
||||
public PublicKey getPublic()
|
||||
throws IOException {
|
||||
return pubKey != null ? pubKey : super.getPublic();
|
||||
}
|
||||
|
||||
public static class Factory
|
||||
implements net.schmizz.sshj.common.Factory.Named<FileKeyProvider> {
|
||||
|
||||
@@ -106,16 +101,41 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
|
||||
protected final Logger log = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@Override
|
||||
public void init(File location) {
|
||||
public void init(File location, PasswordFinder pwdf) {
|
||||
File pubKey = OpenSSHKeyFileUtil.getPublicKeyFile(location);
|
||||
if (pubKey != null)
|
||||
if (pubKey != null) {
|
||||
try {
|
||||
initPubKey(new FileReader(pubKey));
|
||||
} catch (IOException e) {
|
||||
// let super provide both public & private key
|
||||
log.warn("Error reading public key file: {}", e.toString());
|
||||
}
|
||||
super.init(location);
|
||||
}
|
||||
super.init(location, pwdf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(String privateKey, String publicKey, PasswordFinder pwdf) {
|
||||
if (pubKey != null) {
|
||||
try {
|
||||
initPubKey(new StringReader(publicKey));
|
||||
} catch (IOException e) {
|
||||
log.warn("Error reading public key file: {}", e.toString());
|
||||
}
|
||||
}
|
||||
super.init(privateKey, null, pwdf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(Reader privateKey, Reader publicKey, PasswordFinder pwdf) {
|
||||
if (pubKey != null) {
|
||||
try {
|
||||
initPubKey(publicKey);
|
||||
} catch (IOException e) {
|
||||
log.warn("Error reading public key file: {}", e.toString());
|
||||
}
|
||||
}
|
||||
super.init(privateKey, null, pwdf);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -124,7 +144,7 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
|
||||
try {
|
||||
if (checkHeader(reader)) {
|
||||
final String encodedPrivateKey = readEncodedKey(reader);
|
||||
byte[] decodedPrivateKey = Base64.getDecoder().decode(encodedPrivateKey);
|
||||
byte[] decodedPrivateKey = Base64Decoder.decode(encodedPrivateKey);
|
||||
final PlainBuffer bufferedPrivateKey = new PlainBuffer(decodedPrivateKey);
|
||||
return readDecodedKeyPair(bufferedPrivateKey);
|
||||
} else {
|
||||
@@ -133,6 +153,8 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
|
||||
}
|
||||
} catch (final GeneralSecurityException e) {
|
||||
throw new SSHRuntimeException("Read OpenSSH Version 1 Key failed", e);
|
||||
} catch (Base64DecodingException e) {
|
||||
throw new SSHRuntimeException("Private Key decoding failed", e);
|
||||
} finally {
|
||||
IOUtils.closeQuietly(reader);
|
||||
}
|
||||
@@ -217,7 +239,7 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
|
||||
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));
|
||||
throw new KeyDecryptionFailedException(new IOException(message, e));
|
||||
}
|
||||
final PlainBuffer decryptedPrivateKey = new PlainBuffer(privateKeyLength);
|
||||
decryptedPrivateKey.putRawBytes(privateKey, 0, privateKeyLength);
|
||||
@@ -316,7 +338,7 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
|
||||
int checkInt1 = keyBuffer.readUInt32AsInt(); // uint32 checkint1
|
||||
int checkInt2 = keyBuffer.readUInt32AsInt(); // uint32 checkint2
|
||||
if (checkInt1 != checkInt2) {
|
||||
throw new KeyDecryptionFailedException(new EncryptionException("OpenSSH Private Key integer comparison failed"));
|
||||
throw new KeyDecryptionFailedException(new IOException("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
|
||||
@@ -338,13 +360,13 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
|
||||
kp = new KeyPair(publicKey, privateKey);
|
||||
break;
|
||||
case ECDSA256:
|
||||
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, "P-256"));
|
||||
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, ECDSACurve.SECP256R1));
|
||||
break;
|
||||
case ECDSA384:
|
||||
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, "P-384"));
|
||||
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, ECDSACurve.SECP384R1));
|
||||
break;
|
||||
case ECDSA521:
|
||||
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, "P-521"));
|
||||
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, ECDSACurve.SECP521R1));
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -361,13 +383,10 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
|
||||
return kp;
|
||||
}
|
||||
|
||||
private PrivateKey createECDSAPrivateKey(KeyType kt, PlainBuffer buffer, String name) throws GeneralSecurityException, Buffer.BufferException {
|
||||
private PrivateKey createECDSAPrivateKey(KeyType kt, PlainBuffer buffer, ECDSACurve ecdsaCurve) throws GeneralSecurityException, Buffer.BufferException {
|
||||
kt.readPubKeyFromBuffer(buffer); // Public key
|
||||
BigInteger s = new BigInteger(1, buffer.readBytes());
|
||||
X9ECParameters ecParams = NISTNamedCurves.getByName(name);
|
||||
ECNamedCurveSpec ecCurveSpec = new ECNamedCurveSpec(name, ecParams.getCurve(), ecParams.getG(), ecParams.getN());
|
||||
ECPrivateKeySpec pks = new ECPrivateKeySpec(s, ecCurveSpec);
|
||||
return SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA).generatePrivate(pks);
|
||||
final BigInteger s = new BigInteger(1, buffer.readBytes());
|
||||
return ECDSAKeyFactory.getPrivateKey(s, ecdsaCurve);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -104,7 +104,8 @@ public class Promise<V, T extends Throwable> {
|
||||
lock.lock();
|
||||
try {
|
||||
pendingEx = null;
|
||||
deliver(null);
|
||||
log.debug("Clearing <<{}>>", name);
|
||||
val = null;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
@@ -804,12 +804,12 @@ public class SSHClient
|
||||
throws IOException {
|
||||
super.onConnect();
|
||||
trans.init(getRemoteHostname(), getRemotePort(), getInputStream(), getOutputStream());
|
||||
doKex();
|
||||
final KeepAlive keepAliveThread = conn.getKeepAlive();
|
||||
if (keepAliveThread.isEnabled()) {
|
||||
ThreadNameProvider.setThreadName(conn.getKeepAlive(), trans);
|
||||
keepAliveThread.start();
|
||||
}
|
||||
doKex();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -65,7 +65,9 @@ public abstract class SocketClient {
|
||||
this.hostname = hostname;
|
||||
this.port = port;
|
||||
socket = socketFactory.createSocket();
|
||||
if (! socket.isConnected()) {
|
||||
socket.connect(makeInetSocketAddress(hostname, port), connectTimeout);
|
||||
}
|
||||
onConnect();
|
||||
}
|
||||
}
|
||||
@@ -104,7 +106,9 @@ public abstract class SocketClient {
|
||||
public void connect(InetAddress host, int port) throws IOException {
|
||||
this.port = port;
|
||||
socket = socketFactory.createSocket();
|
||||
if (! socket.isConnected()) {
|
||||
socket.connect(new InetSocketAddress(host, port), connectTimeout);
|
||||
}
|
||||
onConnect();
|
||||
}
|
||||
|
||||
|
||||
47
src/main/java/net/schmizz/sshj/common/Base64Decoder.java
Normal file
47
src/main/java/net/schmizz/sshj/common/Base64Decoder.java
Normal file
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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 java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* <p>Wraps {@link java.util.Base64.Decoder} in order to wrap unchecked {@code IllegalArgumentException} thrown by
|
||||
* the default Java Base64 decoder here and there.</p>
|
||||
*
|
||||
* <p>Please use this class instead of {@link java.util.Base64.Decoder}.</p>
|
||||
*/
|
||||
public class Base64Decoder {
|
||||
private Base64Decoder() {
|
||||
}
|
||||
|
||||
public static byte[] decode(byte[] source) throws Base64DecodingException {
|
||||
try {
|
||||
return Base64.getDecoder().decode(source);
|
||||
} catch (IllegalArgumentException err) {
|
||||
throw new Base64DecodingException(err);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] decode(String src) throws Base64DecodingException {
|
||||
try {
|
||||
return Base64.getDecoder().decode(src);
|
||||
} catch (IllegalArgumentException err) {
|
||||
throw new Base64DecodingException(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* A checked wrapper for all {@link IllegalArgumentException}, thrown by {@link java.util.Base64.Decoder}.
|
||||
*
|
||||
* @see Base64Decoder
|
||||
*/
|
||||
public class Base64DecodingException extends Exception {
|
||||
public Base64DecodingException(IllegalArgumentException cause) {
|
||||
super("Failed to decode base64: " + cause.getMessage(), cause);
|
||||
}
|
||||
}
|
||||
45
src/main/java/net/schmizz/sshj/common/ECDSACurve.java
Normal file
45
src/main/java/net/schmizz/sshj/common/ECDSACurve.java
Normal file
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* Enumeration of supported ECDSA Curves with corresponding algorithm parameter names
|
||||
*/
|
||||
public enum ECDSACurve {
|
||||
/** NIST P-256 */
|
||||
SECP256R1("secp256r1"),
|
||||
|
||||
/** NIST P-384 */
|
||||
SECP384R1("secp384r1"),
|
||||
|
||||
/** NIST P-521 */
|
||||
SECP521R1("secp521r1");
|
||||
|
||||
private final String curveName;
|
||||
|
||||
ECDSACurve(final String curveName) {
|
||||
this.curveName = curveName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Curve Name for use with Java Cryptography Architecture components
|
||||
*
|
||||
* @return Curve Name
|
||||
*/
|
||||
public String getCurveName() {
|
||||
return curveName;
|
||||
}
|
||||
}
|
||||
86
src/main/java/net/schmizz/sshj/common/ECDSAKeyFactory.java
Normal file
86
src/main/java/net/schmizz/sshj/common/ECDSAKeyFactory.java
Normal file
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* 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 com.hierynomus.sshj.common.KeyAlgorithm;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.AlgorithmParameters;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.ECGenParameterSpec;
|
||||
import java.security.spec.ECParameterSpec;
|
||||
import java.security.spec.ECPoint;
|
||||
import java.security.spec.ECPrivateKeySpec;
|
||||
import java.security.spec.ECPublicKeySpec;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Factory for generating Elliptic Curve Keys using Java Security components for NIST Curves
|
||||
*/
|
||||
public class ECDSAKeyFactory {
|
||||
|
||||
private ECDSAKeyFactory() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Elliptic Curve Private Key for private key value and Curve Name
|
||||
*
|
||||
* @param privateKeyInteger Private Key
|
||||
* @param ecdsaCurve Elliptic Curve
|
||||
* @return Elliptic Curve Private Key
|
||||
* @throws GeneralSecurityException Thrown on failure to create parameter specification
|
||||
*/
|
||||
public static PrivateKey getPrivateKey(final BigInteger privateKeyInteger, final ECDSACurve ecdsaCurve) throws GeneralSecurityException {
|
||||
Objects.requireNonNull(privateKeyInteger, "Private Key integer required");
|
||||
Objects.requireNonNull(ecdsaCurve, "Curve required");
|
||||
|
||||
final ECParameterSpec parameterSpec = getParameterSpec(ecdsaCurve);
|
||||
final ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(privateKeyInteger, parameterSpec);
|
||||
|
||||
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA);
|
||||
return keyFactory.generatePrivate(privateKeySpec);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Elliptic Curve Public Key for public key value and Curve Name
|
||||
*
|
||||
* @param point Public Key point
|
||||
* @param ecdsaCurve Elliptic Curve
|
||||
* @return Elliptic Curve Public Key
|
||||
* @throws GeneralSecurityException Thrown on failure to create parameter specification
|
||||
*/
|
||||
public static PublicKey getPublicKey(final ECPoint point, final ECDSACurve ecdsaCurve) throws GeneralSecurityException {
|
||||
Objects.requireNonNull(point, "Elliptic Curve Point required");
|
||||
Objects.requireNonNull(ecdsaCurve, "Curve required");
|
||||
|
||||
final ECParameterSpec parameterSpec = getParameterSpec(ecdsaCurve);
|
||||
final ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(point, parameterSpec);
|
||||
|
||||
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA);
|
||||
return keyFactory.generatePublic(publicKeySpec);
|
||||
}
|
||||
|
||||
private static ECParameterSpec getParameterSpec(final ECDSACurve ecdsaCurve) throws GeneralSecurityException {
|
||||
final ECGenParameterSpec genParameterSpec = new ECGenParameterSpec(ecdsaCurve.getCurveName());
|
||||
final AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(KeyAlgorithm.EC_KEYSTORE);
|
||||
algorithmParameters.init(genParameterSpec);
|
||||
return algorithmParameters.getParameterSpec(ECParameterSpec.class);
|
||||
}
|
||||
}
|
||||
@@ -17,21 +17,16 @@ package net.schmizz.sshj.common;
|
||||
|
||||
import com.hierynomus.sshj.common.KeyAlgorithm;
|
||||
import com.hierynomus.sshj.secg.SecgUtils;
|
||||
import org.bouncycastle.asn1.nist.NISTNamedCurves;
|
||||
import org.bouncycastle.asn1.x9.X9ECParameters;
|
||||
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.Key;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PublicKey;
|
||||
import java.security.interfaces.ECKey;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.security.spec.ECPoint;
|
||||
import java.security.spec.ECPublicKeySpec;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@@ -42,13 +37,13 @@ class ECDSAVariationsAdapter {
|
||||
|
||||
private final static Logger log = LoggerFactory.getLogger(ECDSAVariationsAdapter.class);
|
||||
|
||||
public final static Map<String, String> SUPPORTED_CURVES = new HashMap<String, String>();
|
||||
public final static Map<String, String> NIST_CURVES_NAMES = new HashMap<String, String>();
|
||||
public final static Map<String, String> SUPPORTED_CURVES = new HashMap<>();
|
||||
public final static Map<String, ECDSACurve> NIST_CURVES = new HashMap<>();
|
||||
|
||||
static {
|
||||
NIST_CURVES_NAMES.put("256", "p-256");
|
||||
NIST_CURVES_NAMES.put("384", "p-384");
|
||||
NIST_CURVES_NAMES.put("521", "p-521");
|
||||
NIST_CURVES.put("256", ECDSACurve.SECP256R1);
|
||||
NIST_CURVES.put("384", ECDSACurve.SECP384R1);
|
||||
NIST_CURVES.put("521", ECDSACurve.SECP521R1);
|
||||
|
||||
SUPPORTED_CURVES.put("256", "nistp256");
|
||||
SUPPORTED_CURVES.put("384", "nistp384");
|
||||
@@ -72,21 +67,15 @@ class ECDSAVariationsAdapter {
|
||||
algorithm, curveName, keyLen, x04, Arrays.toString(x), Arrays.toString(y)));
|
||||
}
|
||||
|
||||
if (!SUPPORTED_CURVES.values().contains(curveName)) {
|
||||
if (!SUPPORTED_CURVES.containsValue(curveName)) {
|
||||
throw new GeneralSecurityException(String.format("Unknown curve %s", curveName));
|
||||
}
|
||||
|
||||
BigInteger bigX = new BigInteger(1, x);
|
||||
BigInteger bigY = new BigInteger(1, y);
|
||||
|
||||
String name = NIST_CURVES_NAMES.get(variation);
|
||||
X9ECParameters ecParams = NISTNamedCurves.getByName(name);
|
||||
ECNamedCurveSpec ecCurveSpec = new ECNamedCurveSpec(name, ecParams.getCurve(), ecParams.getG(), ecParams.getN());
|
||||
ECPoint p = new ECPoint(bigX, bigY);
|
||||
ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(p, ecCurveSpec);
|
||||
|
||||
KeyFactory keyFactory = KeyFactory.getInstance(KeyAlgorithm.ECDSA);
|
||||
return keyFactory.generatePublic(publicKeySpec);
|
||||
final BigInteger bigX = new BigInteger(1, x);
|
||||
final BigInteger bigY = new BigInteger(1, y);
|
||||
final ECPoint point = new ECPoint(bigX, bigY);
|
||||
final ECDSACurve ecdsaCurve = NIST_CURVES.get(variation);
|
||||
return ECDSAKeyFactory.getPublicKey(point, ecdsaCurve);
|
||||
} catch (Exception ex) {
|
||||
throw new GeneralSecurityException(ex);
|
||||
}
|
||||
@@ -96,7 +85,7 @@ class ECDSAVariationsAdapter {
|
||||
final ECPublicKey ecdsa = (ECPublicKey) pk;
|
||||
byte[] encoded = SecgUtils.getEncoded(ecdsa.getW(), ecdsa.getParams().getCurve());
|
||||
|
||||
buf.putString("nistp" + Integer.toString(fieldSizeFromKey(ecdsa)))
|
||||
buf.putString("nistp" + (fieldSizeFromKey(ecdsa)))
|
||||
.putBytes(encoded);
|
||||
}
|
||||
|
||||
|
||||
@@ -225,7 +225,9 @@ public class SessionChannel
|
||||
|
||||
@Override
|
||||
public void notifyError(SSHException error) {
|
||||
if (err != null) {
|
||||
err.notifyError(error);
|
||||
}
|
||||
super.notifyError(error);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
package net.schmizz.sshj.sftp;
|
||||
|
||||
import com.hierynomus.sshj.sftp.RemoteResourceSelector;
|
||||
import net.schmizz.sshj.sftp.Response.StatusCode;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -22,6 +23,8 @@ import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.hierynomus.sshj.sftp.RemoteResourceFilterConverter.selectorFrom;
|
||||
|
||||
public class RemoteDirectory
|
||||
extends RemoteResource {
|
||||
|
||||
@@ -31,37 +34,55 @@ public class RemoteDirectory
|
||||
|
||||
public List<RemoteResourceInfo> scan(RemoteResourceFilter filter)
|
||||
throws IOException {
|
||||
List<RemoteResourceInfo> rri = new LinkedList<RemoteResourceInfo>();
|
||||
// TODO: Remove GOTO!
|
||||
loop:
|
||||
for (; ; ) {
|
||||
final Response res = requester.request(newRequest(PacketType.READDIR))
|
||||
.retrieve(requester.getTimeoutMs(), TimeUnit.MILLISECONDS);
|
||||
switch (res.getType()) {
|
||||
return scan(selectorFrom(filter));
|
||||
}
|
||||
|
||||
public List<RemoteResourceInfo> scan(RemoteResourceSelector selector)
|
||||
throws IOException {
|
||||
if (selector == null) {
|
||||
selector = RemoteResourceSelector.ALL;
|
||||
}
|
||||
|
||||
List<RemoteResourceInfo> remoteResourceInfos = new LinkedList<>();
|
||||
|
||||
while (true) {
|
||||
final Response response = requester.request(newRequest(PacketType.READDIR))
|
||||
.retrieve(requester.getTimeoutMs(), TimeUnit.MILLISECONDS);
|
||||
|
||||
switch (response.getType()) {
|
||||
case NAME:
|
||||
final int count = res.readUInt32AsInt();
|
||||
final int count = response.readUInt32AsInt();
|
||||
for (int i = 0; i < count; i++) {
|
||||
final String name = res.readString(requester.sub.getRemoteCharset());
|
||||
res.readString(); // long name - IGNORED - shdve never been in the protocol
|
||||
final FileAttributes attrs = res.readFileAttributes();
|
||||
final String name = response.readString(requester.sub.getRemoteCharset());
|
||||
response.readString(); // long name - IGNORED - shdve never been in the protocol
|
||||
final FileAttributes attrs = response.readFileAttributes();
|
||||
final PathComponents comps = requester.getPathHelper().getComponents(path, name);
|
||||
final RemoteResourceInfo inf = new RemoteResourceInfo(comps, attrs);
|
||||
if (!(".".equals(name) || "..".equals(name)) && (filter == null || filter.accept(inf))) {
|
||||
rri.add(inf);
|
||||
|
||||
if (".".equals(name) || "..".equals(name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final RemoteResourceSelector.Result selectionResult = selector.select(inf);
|
||||
switch (selectionResult) {
|
||||
case ACCEPT:
|
||||
remoteResourceInfos.add(inf);
|
||||
break;
|
||||
case CONTINUE:
|
||||
continue;
|
||||
case BREAK:
|
||||
return remoteResourceInfos;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case STATUS:
|
||||
res.ensureStatusIs(StatusCode.EOF);
|
||||
break loop;
|
||||
response.ensureStatusIs(StatusCode.EOF);
|
||||
return remoteResourceInfos;
|
||||
|
||||
default:
|
||||
throw new SFTPException("Unexpected packet: " + res.getType());
|
||||
throw new SFTPException("Unexpected packet: " + response.getType());
|
||||
}
|
||||
}
|
||||
return rri;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
package net.schmizz.sshj.sftp;
|
||||
|
||||
import com.hierynomus.sshj.sftp.RemoteResourceSelector;
|
||||
import net.schmizz.sshj.connection.channel.direct.SessionFactory;
|
||||
import net.schmizz.sshj.xfer.FilePermission;
|
||||
import net.schmizz.sshj.xfer.LocalDestFile;
|
||||
@@ -25,6 +26,8 @@ import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
import static com.hierynomus.sshj.sftp.RemoteResourceFilterConverter.selectorFrom;
|
||||
|
||||
public class SFTPClient
|
||||
implements Closeable {
|
||||
|
||||
@@ -57,16 +60,18 @@ public class SFTPClient
|
||||
|
||||
public List<RemoteResourceInfo> ls(String path)
|
||||
throws IOException {
|
||||
return ls(path, null);
|
||||
return ls(path, RemoteResourceSelector.ALL);
|
||||
}
|
||||
|
||||
public List<RemoteResourceInfo> ls(String path, RemoteResourceFilter filter)
|
||||
throws IOException {
|
||||
final RemoteDirectory dir = engine.openDir(path);
|
||||
try {
|
||||
return dir.scan(filter);
|
||||
} finally {
|
||||
dir.close();
|
||||
return ls(path, selectorFrom(filter));
|
||||
}
|
||||
|
||||
public List<RemoteResourceInfo> ls(String path, RemoteResourceSelector selector)
|
||||
throws IOException {
|
||||
try (RemoteDirectory dir = engine.openDir(path)) {
|
||||
return dir.scan(selector == null ? RemoteResourceSelector.ALL : selector);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ public class SFTPEngine
|
||||
|
||||
protected final PathHelper pathHelper;
|
||||
|
||||
private final Session session;
|
||||
protected final Session.Subsystem sub;
|
||||
protected final PacketReader reader;
|
||||
protected final OutputStream out;
|
||||
@@ -63,7 +64,7 @@ public class SFTPEngine
|
||||
|
||||
public SFTPEngine(SessionFactory ssh, String pathSep)
|
||||
throws SSHException {
|
||||
Session session = ssh.startSession();
|
||||
session = ssh.startSession();
|
||||
loggerFactory = session.getLoggerFactory();
|
||||
log = loggerFactory.getLogger(getClass());
|
||||
sub = session.startSubsystem("sftp");
|
||||
@@ -346,6 +347,7 @@ public class SFTPEngine
|
||||
throws IOException {
|
||||
sub.close();
|
||||
reader.interrupt();
|
||||
session.close();
|
||||
}
|
||||
|
||||
protected LoggerFactory getLoggerFactory() {
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
package net.schmizz.sshj.sftp;
|
||||
|
||||
import com.hierynomus.sshj.sftp.RemoteResourceSelector;
|
||||
import net.schmizz.sshj.connection.channel.direct.SessionFactory;
|
||||
import net.schmizz.sshj.xfer.LocalDestFile;
|
||||
import net.schmizz.sshj.xfer.LocalSourceFile;
|
||||
@@ -23,6 +24,8 @@ import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static com.hierynomus.sshj.sftp.RemoteResourceFilterConverter.selectorFrom;
|
||||
|
||||
public class StatefulSFTPClient
|
||||
extends SFTPClient {
|
||||
|
||||
@@ -57,7 +60,7 @@ public class StatefulSFTPClient
|
||||
|
||||
public synchronized List<RemoteResourceInfo> ls()
|
||||
throws IOException {
|
||||
return ls(cwd, null);
|
||||
return ls(cwd, RemoteResourceSelector.ALL);
|
||||
}
|
||||
|
||||
public synchronized List<RemoteResourceInfo> ls(RemoteResourceFilter filter)
|
||||
@@ -70,20 +73,21 @@ public class StatefulSFTPClient
|
||||
return super.canonicalize(cwd);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RemoteResourceInfo> ls(String path)
|
||||
throws IOException {
|
||||
return ls(path, null);
|
||||
return ls(path, RemoteResourceSelector.ALL);
|
||||
}
|
||||
|
||||
public List<RemoteResourceInfo> ls(String path, RemoteResourceFilter filter)
|
||||
throws IOException {
|
||||
return ls(path, selectorFrom(filter));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RemoteResourceInfo> ls(String path, RemoteResourceFilter filter)
|
||||
public List<RemoteResourceInfo> ls(String path, RemoteResourceSelector selector)
|
||||
throws IOException {
|
||||
final RemoteDirectory dir = getSFTPEngine().openDir(cwdify(path));
|
||||
try {
|
||||
return dir.scan(filter);
|
||||
} finally {
|
||||
dir.close();
|
||||
try (RemoteDirectory dir = getSFTPEngine().openDir(cwdify(path))) {
|
||||
return dir.scan(selector == null ? RemoteResourceSelector.ALL : selector);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -420,9 +420,9 @@ public final class TransportImpl
|
||||
try {
|
||||
|
||||
if (kexer.isKexOngoing()) {
|
||||
// Only transport layer packets (1 to 49) allowed except SERVICE_REQUEST
|
||||
// Only transport layer packets (1 to 49) allowed except SERVICE_REQUEST and IGNORE
|
||||
final Message m = Message.fromByte(payload.array()[payload.rpos()]);
|
||||
if (!m.in(1, 49) || m == Message.SERVICE_REQUEST) {
|
||||
if (!m.in(1, 49) || m == Message.SERVICE_REQUEST || m == Message.IGNORE) {
|
||||
assert m != Message.KEXINIT;
|
||||
kexer.waitForDone();
|
||||
}
|
||||
|
||||
@@ -34,13 +34,14 @@ public class Curve25519DH extends DHBase {
|
||||
|
||||
private static final String ALGORITHM = "X25519";
|
||||
|
||||
private static final int ENCODED_ALGORITHM_ID_KEY_LENGTH = 44;
|
||||
|
||||
private static final int ALGORITHM_ID_LENGTH = 12;
|
||||
|
||||
private static final int KEY_LENGTH = 32;
|
||||
|
||||
private final byte[] algorithmId = new byte[ALGORITHM_ID_LENGTH];
|
||||
private int encodedKeyLength;
|
||||
|
||||
private int algorithmIdLength;
|
||||
|
||||
// Algorithm Identifier is set on Key Agreement Initialization
|
||||
private byte[] algorithmId = new byte[KEY_LENGTH];
|
||||
|
||||
public Curve25519DH() {
|
||||
super(ALGORITHM, ALGORITHM);
|
||||
@@ -81,23 +82,24 @@ public class Curve25519DH extends DHBase {
|
||||
private void setPublicKey(final PublicKey publicKey) {
|
||||
final byte[] encoded = publicKey.getEncoded();
|
||||
|
||||
// Set key and algorithm identifier lengths based on initialized Public Key
|
||||
encodedKeyLength = encoded.length;
|
||||
algorithmIdLength = encodedKeyLength - KEY_LENGTH;
|
||||
algorithmId = new byte[algorithmIdLength];
|
||||
|
||||
// Encoded public key consists of the algorithm identifier and public key
|
||||
if (encoded.length == ENCODED_ALGORITHM_ID_KEY_LENGTH) {
|
||||
final byte[] publicKeyEncoded = new byte[KEY_LENGTH];
|
||||
System.arraycopy(encoded, ALGORITHM_ID_LENGTH, publicKeyEncoded, 0, KEY_LENGTH);
|
||||
System.arraycopy(encoded, algorithmIdLength, publicKeyEncoded, 0, KEY_LENGTH);
|
||||
setE(publicKeyEncoded);
|
||||
|
||||
// Save Algorithm Identifier byte array
|
||||
System.arraycopy(encoded, 0, algorithmId, 0, ALGORITHM_ID_LENGTH);
|
||||
} else {
|
||||
throw new IllegalArgumentException(String.format("X25519 unsupported public key length [%d]", encoded.length));
|
||||
}
|
||||
System.arraycopy(encoded, 0, algorithmId, 0, algorithmIdLength);
|
||||
}
|
||||
|
||||
private KeySpec getPeerPublicKeySpec(final byte[] peerPublicKey) {
|
||||
final byte[] encodedKeySpec = new byte[ENCODED_ALGORITHM_ID_KEY_LENGTH];
|
||||
System.arraycopy(algorithmId, 0, encodedKeySpec, 0, ALGORITHM_ID_LENGTH);
|
||||
System.arraycopy(peerPublicKey, 0, encodedKeySpec, ALGORITHM_ID_LENGTH, KEY_LENGTH);
|
||||
final byte[] encodedKeySpec = new byte[encodedKeyLength];
|
||||
System.arraycopy(algorithmId, 0, encodedKeySpec, 0, algorithmIdLength);
|
||||
System.arraycopy(peerPublicKey, 0, encodedKeySpec, algorithmIdLength, KEY_LENGTH);
|
||||
return new X509EncodedKeySpec(encodedKeySpec);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,13 +18,7 @@ package net.schmizz.sshj.transport.verification;
|
||||
import com.hierynomus.sshj.common.KeyAlgorithm;
|
||||
import com.hierynomus.sshj.transport.verification.KnownHostMatchers;
|
||||
import com.hierynomus.sshj.userauth.certificate.Certificate;
|
||||
import net.schmizz.sshj.common.Buffer;
|
||||
import net.schmizz.sshj.common.IOUtils;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
import net.schmizz.sshj.common.SSHException;
|
||||
import net.schmizz.sshj.common.SSHRuntimeException;
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
import net.schmizz.sshj.common.*;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
@@ -290,10 +284,10 @@ public class OpenSSHKnownHosts
|
||||
if (type != KeyType.UNKNOWN) {
|
||||
final String sKey = split[i++];
|
||||
try {
|
||||
byte[] keyBytes = Base64.getDecoder().decode(sKey);
|
||||
byte[] keyBytes = Base64Decoder.decode(sKey);
|
||||
key = new Buffer.PlainBuffer(keyBytes).readPublicKey();
|
||||
} catch (IOException ioe) {
|
||||
log.warn("Error decoding Base64 key bytes", ioe);
|
||||
} catch (IOException | Base64DecodingException exception) {
|
||||
log.warn("Error decoding Base64 key bytes", exception);
|
||||
return new BadHostEntry(line);
|
||||
}
|
||||
} else if (isBits(sType)) {
|
||||
|
||||
@@ -34,38 +34,47 @@ public abstract class BaseFileKeyProvider implements FileKeyProvider {
|
||||
|
||||
@Override
|
||||
public void init(Reader location) {
|
||||
assert location != null;
|
||||
resource = new PrivateKeyReaderResource(location);
|
||||
this.init(location, (PasswordFinder) null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(Reader location, PasswordFinder pwdf) {
|
||||
init(location);
|
||||
this.init(location, null, pwdf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(Reader privateKey, Reader publicKey) {
|
||||
this.init(privateKey, publicKey, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(Reader privateKey, Reader publicKey, PasswordFinder pwdf) {
|
||||
assert publicKey == null;
|
||||
this.resource = new PrivateKeyReaderResource(privateKey);
|
||||
this.pwdf = pwdf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(File location) {
|
||||
assert location != null;
|
||||
resource = new PrivateKeyFileResource(location.getAbsoluteFile());
|
||||
this.init(location, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(File location, PasswordFinder pwdf) {
|
||||
init(location);
|
||||
this.resource = new PrivateKeyFileResource(location.getAbsoluteFile());
|
||||
this.pwdf = pwdf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(String privateKey, String publicKey) {
|
||||
assert privateKey != null;
|
||||
assert publicKey == null;
|
||||
resource = new PrivateKeyStringResource(privateKey);
|
||||
this.init(privateKey, publicKey, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(String privateKey, String publicKey, PasswordFinder pwdf) {
|
||||
init(privateKey, publicKey);
|
||||
assert privateKey != null;
|
||||
assert publicKey == null;
|
||||
this.resource = new PrivateKeyStringResource(privateKey);
|
||||
this.pwdf = pwdf;
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,10 @@ public interface FileKeyProvider
|
||||
|
||||
void init(Reader location);
|
||||
|
||||
void init(Reader privateKey, Reader publicKey);
|
||||
|
||||
void init(Reader privateKey, Reader publicKey, PasswordFinder pwdf);
|
||||
|
||||
void init(Reader location, PasswordFinder pwdf);
|
||||
|
||||
void init(String privateKey, String publicKey);
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
package net.schmizz.sshj.userauth.keyprovider;
|
||||
|
||||
import com.hierynomus.sshj.userauth.keyprovider.OpenSSHKeyFileUtil;
|
||||
import net.schmizz.sshj.userauth.password.PasswordFinder;
|
||||
|
||||
import java.io.*;
|
||||
import java.security.PublicKey;
|
||||
@@ -54,21 +55,22 @@ public class OpenSSHKeyFile
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(File location) {
|
||||
public void init(File location, PasswordFinder pwdf) {
|
||||
// try cert key location first
|
||||
File pubKey = OpenSSHKeyFileUtil.getPublicKeyFile(location);
|
||||
if (pubKey != null)
|
||||
if (pubKey != null) {
|
||||
try {
|
||||
initPubKey(new FileReader(pubKey));
|
||||
} catch (IOException e) {
|
||||
// let super provide both public & private key
|
||||
log.warn("Error reading public key file: {}", e.toString());
|
||||
}
|
||||
super.init(location);
|
||||
}
|
||||
super.init(location, pwdf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(String privateKey, String publicKey) {
|
||||
public void init(String privateKey, String publicKey, PasswordFinder pwdf) {
|
||||
if (publicKey != null) {
|
||||
try {
|
||||
initPubKey(new StringReader(publicKey));
|
||||
@@ -77,7 +79,20 @@ public class OpenSSHKeyFile
|
||||
log.warn("Error reading public key: {}", e.toString());
|
||||
}
|
||||
}
|
||||
super.init(privateKey, null);
|
||||
super.init(privateKey, null, pwdf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(Reader privateKey, Reader publicKey, PasswordFinder pwdf) {
|
||||
if (publicKey != null) {
|
||||
try {
|
||||
initPubKey(publicKey);
|
||||
} catch (IOException e) {
|
||||
// let super provide both public & private key
|
||||
log.warn("Error reading public key: {}", e.toString());
|
||||
}
|
||||
}
|
||||
super.init(privateKey, null, pwdf);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,15 +22,10 @@ import net.i2p.crypto.eddsa.spec.EdDSANamedCurveSpec;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec;
|
||||
import net.schmizz.sshj.common.Buffer;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
import net.schmizz.sshj.common.*;
|
||||
import net.schmizz.sshj.userauth.password.PasswordUtils;
|
||||
import org.bouncycastle.asn1.nist.NISTNamedCurves;
|
||||
import org.bouncycastle.asn1.x9.X9ECParameters;
|
||||
import org.bouncycastle.crypto.generators.Argon2BytesGenerator;
|
||||
import org.bouncycastle.crypto.params.Argon2Parameters;
|
||||
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
@@ -42,7 +37,6 @@ import java.math.BigInteger;
|
||||
import java.security.*;
|
||||
import java.security.spec.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -176,29 +170,26 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
|
||||
EdDSAPrivateKeySpec privateSpec = new EdDSAPrivateKeySpec(privateKeyReader.readBytes(), ed25519);
|
||||
return new KeyPair(new EdDSAPublicKey(publicSpec), new EdDSAPrivateKey(privateSpec));
|
||||
}
|
||||
final String ecdsaCurve;
|
||||
final ECDSACurve ecdsaCurve;
|
||||
switch (keyType) {
|
||||
case ECDSA256:
|
||||
ecdsaCurve = "P-256";
|
||||
ecdsaCurve = ECDSACurve.SECP256R1;
|
||||
break;
|
||||
case ECDSA384:
|
||||
ecdsaCurve = "P-384";
|
||||
ecdsaCurve = ECDSACurve.SECP384R1;
|
||||
break;
|
||||
case ECDSA521:
|
||||
ecdsaCurve = "P-521";
|
||||
ecdsaCurve = ECDSACurve.SECP521R1;
|
||||
break;
|
||||
default:
|
||||
ecdsaCurve = null;
|
||||
break;
|
||||
}
|
||||
if (ecdsaCurve != null) {
|
||||
BigInteger s = new BigInteger(1, privateKeyReader.readBytes());
|
||||
X9ECParameters ecParams = NISTNamedCurves.getByName(ecdsaCurve);
|
||||
ECNamedCurveSpec ecCurveSpec = new ECNamedCurveSpec(ecdsaCurve, ecParams.getCurve(), ecParams.getG(),
|
||||
ecParams.getN());
|
||||
ECPrivateKeySpec pks = new ECPrivateKeySpec(s, ecCurveSpec);
|
||||
final BigInteger s = new BigInteger(1, privateKeyReader.readBytes());
|
||||
|
||||
try {
|
||||
PrivateKey privateKey = SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA).generatePrivate(pks);
|
||||
final PrivateKey privateKey = ECDSAKeyFactory.getPrivateKey(s, ecdsaCurve);
|
||||
return new KeyPair(keyType.readPubKeyFromBuffer(publicKeyReader), privateKey);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IOException(e.getMessage(), e);
|
||||
@@ -240,8 +231,9 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
|
||||
if (this.keyFileVersion == null) {
|
||||
throw new IOException("Invalid key file format: missing \"PuTTY-User-Key-File-?\" entry");
|
||||
}
|
||||
try {
|
||||
// Retrieve keys from payload
|
||||
publicKey = Base64.getDecoder().decode(payload.get("Public-Lines"));
|
||||
publicKey = Base64Decoder.decode(payload.get("Public-Lines"));
|
||||
if (this.isEncrypted()) {
|
||||
final char[] passphrase;
|
||||
if (pwdf != null) {
|
||||
@@ -250,7 +242,7 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
|
||||
passphrase = "".toCharArray();
|
||||
}
|
||||
try {
|
||||
privateKey = this.decrypt(Base64.getDecoder().decode(payload.get("Private-Lines")), passphrase);
|
||||
privateKey = this.decrypt(Base64Decoder.decode(payload.get("Private-Lines")), passphrase);
|
||||
Mac mac;
|
||||
if (this.keyFileVersion <= 2) {
|
||||
mac = this.prepareVerifyMacV2(passphrase);
|
||||
@@ -262,7 +254,11 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
|
||||
PasswordUtils.blankOut(passphrase);
|
||||
}
|
||||
} else {
|
||||
privateKey = Base64.getDecoder().decode(payload.get("Private-Lines"));
|
||||
privateKey = Base64Decoder.decode(payload.get("Private-Lines"));
|
||||
}
|
||||
}
|
||||
catch (Base64DecodingException e) {
|
||||
throw new IOException("PuTTY key decoding failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,9 +45,20 @@ public class SCPDownloadClient extends AbstractSCPClient {
|
||||
|
||||
public synchronized int copy(String sourcePath, LocalDestFile targetFile, ScpCommandLine.EscapeMode escapeMode)
|
||||
throws IOException {
|
||||
ScpCommandLine commandLine = ScpCommandLine.with(ScpCommandLine.Arg.SOURCE)
|
||||
.and(ScpCommandLine.Arg.QUIET)
|
||||
.and(ScpCommandLine.Arg.PRESERVE_TIMES)
|
||||
.and(ScpCommandLine.Arg.RECURSIVE, recursiveMode)
|
||||
.and(ScpCommandLine.Arg.LIMIT, String.valueOf(bandwidthLimit), (bandwidthLimit > 0));
|
||||
return copy(sourcePath, targetFile, escapeMode, commandLine);
|
||||
}
|
||||
|
||||
public synchronized int copy(String sourcePath, LocalDestFile targetFile, ScpCommandLine.EscapeMode escapeMode, ScpCommandLine commandLine)
|
||||
throws IOException {
|
||||
engine.cleanSlate();
|
||||
try {
|
||||
startCopy(sourcePath, targetFile, escapeMode);
|
||||
commandLine.withPath(sourcePath, escapeMode);
|
||||
startCopy(targetFile, commandLine);
|
||||
} finally {
|
||||
engine.exit();
|
||||
}
|
||||
@@ -62,14 +73,7 @@ public class SCPDownloadClient extends AbstractSCPClient {
|
||||
this.recursiveMode = recursive;
|
||||
}
|
||||
|
||||
private void startCopy(String sourcePath, LocalDestFile targetFile, ScpCommandLine.EscapeMode escapeMode)
|
||||
throws IOException {
|
||||
ScpCommandLine commandLine = ScpCommandLine.with(ScpCommandLine.Arg.SOURCE)
|
||||
.and(ScpCommandLine.Arg.QUIET)
|
||||
.and(ScpCommandLine.Arg.PRESERVE_TIMES)
|
||||
.and(ScpCommandLine.Arg.RECURSIVE, recursiveMode)
|
||||
.and(ScpCommandLine.Arg.LIMIT, String.valueOf(bandwidthLimit), (bandwidthLimit > 0));
|
||||
commandLine.withPath(sourcePath, escapeMode);
|
||||
private void startCopy(LocalDestFile targetFile, ScpCommandLine commandLine) throws IOException {
|
||||
engine.execSCPWith(commandLine);
|
||||
|
||||
engine.signal("Start status OK");
|
||||
|
||||
@@ -19,6 +19,7 @@ import net.schmizz.sshj.common.IOUtils;
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
import net.schmizz.sshj.common.SSHException;
|
||||
import net.schmizz.sshj.common.StreamCopier;
|
||||
import net.schmizz.sshj.connection.channel.direct.Session;
|
||||
import net.schmizz.sshj.connection.channel.direct.Session.Command;
|
||||
import net.schmizz.sshj.connection.channel.direct.SessionFactory;
|
||||
import net.schmizz.sshj.xfer.TransferListener;
|
||||
@@ -41,6 +42,7 @@ class SCPEngine {
|
||||
private final SessionFactory host;
|
||||
private final TransferListener listener;
|
||||
|
||||
private Session session;
|
||||
private Command scp;
|
||||
private int exitStatus;
|
||||
|
||||
@@ -82,7 +84,8 @@ class SCPEngine {
|
||||
|
||||
void execSCPWith(ScpCommandLine commandLine)
|
||||
throws SSHException {
|
||||
scp = host.startSession().exec(commandLine.toCommandLine());
|
||||
session = host.startSession();
|
||||
scp = session.exec(commandLine.toCommandLine());
|
||||
}
|
||||
|
||||
void exit() {
|
||||
@@ -102,6 +105,10 @@ class SCPEngine {
|
||||
log.warn("SCP exit signal: {}", scp.getExitSignal());
|
||||
}
|
||||
}
|
||||
if(session != null) {
|
||||
IOUtils.closeQuietly(session);
|
||||
session = null;
|
||||
}
|
||||
|
||||
scp = null;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import net.schmizz.sshj.common.StreamCopier;
|
||||
import net.schmizz.sshj.xfer.LocalFileFilter;
|
||||
import net.schmizz.sshj.xfer.LocalSourceFile;
|
||||
import net.schmizz.sshj.xfer.TransferListener;
|
||||
import net.schmizz.sshj.xfer.scp.ScpCommandLine.Arg;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -43,26 +44,12 @@ public class SCPUploadClient extends AbstractSCPClient {
|
||||
return copy(sourceFile, remotePath, ScpCommandLine.EscapeMode.SingleQuote);
|
||||
}
|
||||
|
||||
public synchronized int copy (LocalSourceFile sourceFile, String remotePath, ScpCommandLine.EscapeMode escapeMode) throws IOException {
|
||||
public synchronized int copy(LocalSourceFile sourceFile, String remotePath, ScpCommandLine.EscapeMode escapeMode)
|
||||
throws IOException {
|
||||
return copy(sourceFile, remotePath, escapeMode, true);
|
||||
}
|
||||
|
||||
public synchronized int copy(LocalSourceFile sourceFile, String remotePath, ScpCommandLine.EscapeMode escapeMode, boolean preserveTimes)
|
||||
throws IOException {
|
||||
engine.cleanSlate();
|
||||
try {
|
||||
startCopy(sourceFile, remotePath, escapeMode, preserveTimes);
|
||||
} finally {
|
||||
engine.exit();
|
||||
}
|
||||
return engine.getExitStatus();
|
||||
}
|
||||
|
||||
public void setUploadFilter(LocalFileFilter uploadFilter) {
|
||||
this.uploadFilter = uploadFilter;
|
||||
}
|
||||
|
||||
private void startCopy(LocalSourceFile sourceFile, String targetPath, ScpCommandLine.EscapeMode escapeMode, boolean preserveTimes)
|
||||
throws IOException {
|
||||
ScpCommandLine commandLine = ScpCommandLine.with(ScpCommandLine.Arg.SINK)
|
||||
.and(ScpCommandLine.Arg.RECURSIVE)
|
||||
@@ -70,10 +57,31 @@ public class SCPUploadClient extends AbstractSCPClient {
|
||||
if (preserveTimes) {
|
||||
commandLine.and(ScpCommandLine.Arg.PRESERVE_TIMES, sourceFile.providesAtimeMtime());
|
||||
}
|
||||
commandLine.withPath(targetPath, escapeMode);
|
||||
return copy(sourceFile, remotePath, escapeMode, commandLine);
|
||||
}
|
||||
|
||||
public synchronized int copy(LocalSourceFile sourceFile, String remotePath, ScpCommandLine.EscapeMode escapeMode, ScpCommandLine commandLine)
|
||||
throws IOException {
|
||||
engine.cleanSlate();
|
||||
try {
|
||||
commandLine.withPath(remotePath, escapeMode);
|
||||
startCopy(sourceFile, commandLine);
|
||||
} finally {
|
||||
engine.exit();
|
||||
}
|
||||
return engine.getExitStatus();
|
||||
}
|
||||
|
||||
|
||||
public void setUploadFilter(LocalFileFilter uploadFilter) {
|
||||
this.uploadFilter = uploadFilter;
|
||||
}
|
||||
|
||||
private void startCopy(LocalSourceFile sourceFile, ScpCommandLine commandLine)
|
||||
throws IOException {
|
||||
engine.execSCPWith(commandLine);
|
||||
engine.check("Start status OK");
|
||||
process(engine.getTransferListener(), sourceFile, preserveTimes);
|
||||
process(engine.getTransferListener(), sourceFile, commandLine.has(Arg.PRESERVE_TIMES));
|
||||
}
|
||||
|
||||
private void process(TransferListener listener, LocalSourceFile f, boolean preserveTimes)
|
||||
|
||||
@@ -24,7 +24,7 @@ public class ScpCommandLine {
|
||||
private static final String SCP_COMMAND = "scp";
|
||||
private EscapeMode mode;
|
||||
|
||||
enum Arg {
|
||||
public enum Arg {
|
||||
SOURCE('f'),
|
||||
SINK('t'),
|
||||
RECURSIVE('r'),
|
||||
@@ -77,19 +77,19 @@ public class ScpCommandLine {
|
||||
ScpCommandLine() {
|
||||
}
|
||||
|
||||
static ScpCommandLine with(Arg name) {
|
||||
public static ScpCommandLine with(Arg name) {
|
||||
return with(name, null, true);
|
||||
}
|
||||
|
||||
static ScpCommandLine with(Arg name, String value) {
|
||||
public static ScpCommandLine with(Arg name, String value) {
|
||||
return with(name, value, true);
|
||||
}
|
||||
|
||||
static ScpCommandLine with(Arg name, boolean accept) {
|
||||
public static ScpCommandLine with(Arg name, boolean accept) {
|
||||
return with(name, null, accept);
|
||||
}
|
||||
|
||||
static ScpCommandLine with(Arg name, String value, boolean accept) {
|
||||
public static ScpCommandLine with(Arg name, String value, boolean accept) {
|
||||
ScpCommandLine commandLine = new ScpCommandLine();
|
||||
commandLine.addArgument(name, value, accept);
|
||||
return commandLine;
|
||||
@@ -101,22 +101,22 @@ public class ScpCommandLine {
|
||||
}
|
||||
}
|
||||
|
||||
ScpCommandLine and(Arg name) {
|
||||
public ScpCommandLine and(Arg name) {
|
||||
addArgument(name, null, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
ScpCommandLine and(Arg name, String value) {
|
||||
public ScpCommandLine and(Arg name, String value) {
|
||||
addArgument(name, value, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
ScpCommandLine and(Arg name, boolean accept) {
|
||||
public ScpCommandLine and(Arg name, boolean accept) {
|
||||
addArgument(name, null, accept);
|
||||
return this;
|
||||
}
|
||||
|
||||
ScpCommandLine and(Arg name, String value, boolean accept) {
|
||||
public ScpCommandLine and(Arg name, String value, boolean accept) {
|
||||
addArgument(name, value, accept);
|
||||
return this;
|
||||
}
|
||||
@@ -127,6 +127,10 @@ public class ScpCommandLine {
|
||||
return this;
|
||||
}
|
||||
|
||||
boolean has(Arg arg) {
|
||||
return arguments.containsKey(arg);
|
||||
}
|
||||
|
||||
String toCommandLine() {
|
||||
final StringBuilder cmd = new StringBuilder(SCP_COMMAND);
|
||||
for (Arg arg : arguments.keySet()) {
|
||||
|
||||
@@ -19,6 +19,7 @@ import com.hierynomus.sshj.test.SshServerExtension
|
||||
import com.hierynomus.sshj.test.util.FileUtil
|
||||
import net.schmizz.sshj.SSHClient
|
||||
import net.schmizz.sshj.sftp.FileMode
|
||||
import net.schmizz.sshj.sftp.RemoteResourceInfo
|
||||
import net.schmizz.sshj.sftp.SFTPClient
|
||||
import org.junit.jupiter.api.extension.RegisterExtension
|
||||
import spock.lang.Specification
|
||||
@@ -206,6 +207,60 @@ class SFTPClientSpec extends Specification {
|
||||
attrs.type == FileMode.Type.DIRECTORY
|
||||
}
|
||||
|
||||
def "should support premature termination of listing"() {
|
||||
given:
|
||||
SSHClient sshClient = fixture.setupConnectedDefaultClient()
|
||||
sshClient.authPassword("test", "test")
|
||||
SFTPClient sftpClient = sshClient.newSFTPClient()
|
||||
|
||||
final Path source = Files.createDirectory(temp.resolve("source")).toAbsolutePath()
|
||||
final Path destination = Files.createDirectory(temp.resolve("destination")).toAbsolutePath()
|
||||
final Path firstFile = Files.writeString(source.resolve("a_first.txt"), "first")
|
||||
final Path secondFile = Files.writeString(source.resolve("b_second.txt"), "second")
|
||||
final Path thirdFile = Files.writeString(source.resolve("c_third.txt"), "third")
|
||||
final Path fourthFile = Files.writeString(source.resolve("d_fourth.txt"), "fourth")
|
||||
sftpClient.put(firstFile.toString(), destination.resolve(firstFile.fileName).toString())
|
||||
sftpClient.put(secondFile.toString(), destination.resolve(secondFile.fileName).toString())
|
||||
sftpClient.put(thirdFile.toString(), destination.resolve(thirdFile.fileName).toString())
|
||||
sftpClient.put(fourthFile.toString(), destination.resolve(fourthFile.fileName).toString())
|
||||
|
||||
def filesListed = 0
|
||||
RemoteResourceInfo expectedFile = null
|
||||
RemoteResourceSelector limitingSelector = new RemoteResourceSelector() {
|
||||
@Override
|
||||
RemoteResourceSelector.Result select(RemoteResourceInfo resource) {
|
||||
filesListed += 1
|
||||
|
||||
switch(filesListed) {
|
||||
case 1:
|
||||
return RemoteResourceSelector.Result.CONTINUE
|
||||
case 2:
|
||||
expectedFile = resource
|
||||
return RemoteResourceSelector.Result.ACCEPT
|
||||
case 3:
|
||||
return RemoteResourceSelector.Result.BREAK
|
||||
default:
|
||||
throw new AssertionError((Object) "Should NOT select any more resources")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
when:
|
||||
def listingResult = sftpClient
|
||||
.ls(destination.toString(), limitingSelector);
|
||||
|
||||
then:
|
||||
// first should be skipped by CONTINUE
|
||||
listingResult.contains(expectedFile) // second should be included by ACCEPT
|
||||
// third should be skipped by BREAK
|
||||
// fourth should be skipped by preceding BREAK
|
||||
listingResult.size() == 1
|
||||
|
||||
cleanup:
|
||||
sftpClient.close()
|
||||
sshClient.disconnect()
|
||||
}
|
||||
|
||||
private void doUpload(File src, File dest) throws IOException {
|
||||
SSHClient sshClient = fixture.setupConnectedDefaultClient()
|
||||
sshClient.authPassword("test", "test")
|
||||
|
||||
@@ -15,22 +15,10 @@
|
||||
*/
|
||||
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 net.schmizz.sshj.common.Buffer;
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
import net.schmizz.sshj.transport.verification.OpenSSHKnownHosts;
|
||||
import net.schmizz.sshj.util.KeyUtil;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -38,10 +26,16 @@ 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;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Base64;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class OpenSSHKnownHostsTest {
|
||||
@TempDir
|
||||
@@ -110,6 +104,34 @@ public class OpenSSHKnownHostsTest {
|
||||
assertTrue(ohk.verify("host1", 22, k));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotFailOnMalformedBase64String() throws IOException {
|
||||
File knownHosts = knownHosts(
|
||||
"1.1.1.1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBA/CkqWXSlbdo7jPshvIWT/m3FAdpSIKUx/uTmz87ObpBxXsfF8aMSiwGMKHjqviTV4cG6F7vFf28ll+9CbGsbs=192\n"
|
||||
);
|
||||
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
|
||||
assertEquals(1, ohk.entries().size());
|
||||
assertThat(ohk.entries().get(0)).isInstanceOf(OpenSSHKnownHosts.BadHostEntry.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotFailOnMalformeSaltBase64String() throws IOException {
|
||||
// A record with broken base64 inside the salt part of the hash.
|
||||
// No matter how it could be generated, such broken strings must not cause unexpected errors.
|
||||
String hostName = "example.com";
|
||||
File knownHosts = knownHosts(
|
||||
"|1|2gujgGa6gJnK7wGPCX8zuGttvCMXX|Oqkbjtxd9RFxKQv6y3l3GIxLNiU= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBGVVnyoAD5/uWiiuTSM3RuW8dEWRrqOXYobAMKHhAA6kuOBoPK+LoAYyUcN26bdMiCxg+VOaLHxPNWv5SlhbMWw=\n"
|
||||
);
|
||||
OpenSSHKnownHosts ohk = new OpenSSHKnownHosts(knownHosts);
|
||||
assertEquals(1, ohk.entries().size());
|
||||
|
||||
// Some random valid public key. It doesn't matter for the test if it matches the broken host key record or not.
|
||||
PublicKey k = new Buffer.PlainBuffer(Base64.getDecoder().decode(
|
||||
"AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTjA7hduYGmvV9smEEsIdGLdghSPD7kL8QarIIOkeXmBh+LTtT/T1K+Ot/rmXCZsP8hoUXxbvN+Tks440Ci0ck="))
|
||||
.readPublicKey();
|
||||
assertFalse(ohk.verify(hostName, 22, k));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldMarkBadLineAndNotFail() throws Exception {
|
||||
File knownHosts = knownHosts(
|
||||
|
||||
105
src/test/java/net/schmizz/sshj/ConnectedSocketTest.java
Normal file
105
src/test/java/net/schmizz/sshj/ConnectedSocketTest.java
Normal file
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import com.hierynomus.sshj.test.SshServerExtension;
|
||||
import net.schmizz.sshj.SSHClient;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import org.apache.sshd.server.SshServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import javax.net.SocketFactory;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
|
||||
|
||||
public class ConnectedSocketTest {
|
||||
@RegisterExtension
|
||||
public SshServerExtension fixture = new SshServerExtension();
|
||||
|
||||
@BeforeEach
|
||||
public void setupClient() throws IOException {
|
||||
SSHClient defaultClient = fixture.setupDefaultClient();
|
||||
}
|
||||
|
||||
private static interface Connector {
|
||||
void connect(SshServerExtension fx) throws IOException;
|
||||
}
|
||||
|
||||
private static void connectViaHostname(SshServerExtension fx) throws IOException {
|
||||
SshServer server = fx.getServer();
|
||||
fx.getClient().connect("localhost", server.getPort());
|
||||
}
|
||||
|
||||
private static void connectViaAddr(SshServerExtension fx) throws IOException {
|
||||
SshServer server = fx.getServer();
|
||||
InetAddress addr = InetAddress.getByName(server.getHost());
|
||||
fx.getClient().connect(addr, server.getPort());
|
||||
}
|
||||
|
||||
private static Stream<Connector> connectMethods() {
|
||||
return Stream.of(fx -> connectViaHostname(fx), fx -> connectViaAddr(fx));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("connectMethods")
|
||||
public void connectsIfUnconnected(Connector connector) {
|
||||
assertDoesNotThrow(() -> connector.connect(fixture));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("connectMethods")
|
||||
public void handlesConnected(Connector connector) throws IOException {
|
||||
Socket socket = SocketFactory.getDefault().createSocket();
|
||||
SocketFactory factory = new SocketFactory() {
|
||||
@Override
|
||||
public Socket createSocket() {
|
||||
return socket;
|
||||
}
|
||||
@Override
|
||||
public Socket createSocket(InetAddress host, int port) {
|
||||
return socket;
|
||||
}
|
||||
@Override
|
||||
public Socket createSocket(InetAddress address, int port,
|
||||
InetAddress localAddress, int localPort) {
|
||||
return socket;
|
||||
}
|
||||
@Override
|
||||
public Socket createSocket(String host, int port) {
|
||||
return socket;
|
||||
}
|
||||
@Override
|
||||
public Socket createSocket(String host, int port,
|
||||
InetAddress localHost, int localPort) {
|
||||
return socket;
|
||||
}
|
||||
};
|
||||
socket.connect(new InetSocketAddress("localhost", fixture.getServer().getPort()));
|
||||
fixture.getClient().setSocketFactory(factory);
|
||||
assertDoesNotThrow(() -> connector.connect(fixture));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* 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.keyprovider;
|
||||
|
||||
import net.schmizz.sshj.SSHClient;
|
||||
import net.schmizz.sshj.util.CorruptBase64;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
public class CorruptedPublicKeyTest {
|
||||
private final Path keyRoot = Path.of("src/test/resources");
|
||||
|
||||
@TempDir
|
||||
public Path tempDir;
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"keyformats/ecdsa_opensshv1,",
|
||||
"keyformats/openssh,",
|
||||
"keytypes/test_ecdsa_nistp521_2,",
|
||||
"keytypes/ed25519_protected, sshjtest",
|
||||
})
|
||||
public void corruptedPublicKey(String privateKeyFileName, String passphrase) throws IOException {
|
||||
Files.createDirectories(tempDir.resolve(privateKeyFileName).getParent());
|
||||
Files.copy(keyRoot.resolve(privateKeyFileName), tempDir.resolve(privateKeyFileName));
|
||||
|
||||
{
|
||||
String publicKeyText;
|
||||
try (var reader = new BufferedReader(new FileReader(
|
||||
keyRoot.resolve(privateKeyFileName + ".pub").toFile()))) {
|
||||
publicKeyText = reader.readLine();
|
||||
}
|
||||
|
||||
String[] parts = publicKeyText.split("\\s+");
|
||||
parts[1] = CorruptBase64.corruptBase64(parts[1]);
|
||||
|
||||
try (var writer = new FileWriter(tempDir.resolve(privateKeyFileName + ".pub").toFile())) {
|
||||
writer.write(String.join(" ", parts));
|
||||
}
|
||||
}
|
||||
|
||||
// Must not throw an exception.
|
||||
try (var sshClient = new SSHClient()) {
|
||||
sshClient.loadKeys(
|
||||
tempDir.resolve(privateKeyFileName).toString(),
|
||||
Optional.ofNullable(passphrase).map(String::toCharArray).orElse(null)
|
||||
).getPublic();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -381,6 +381,18 @@ public class OpenSSHKeyFileTest {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSuccessfullyLoadSignedRSAPublicKeyFromStream() throws IOException {
|
||||
FileKeyProvider keyFile = new OpenSSHKeyFile();
|
||||
keyFile.init(new FileReader("src/test/resources/keytypes/certificate/test_rsa"),
|
||||
new FileReader("src/test/resources/keytypes/certificate/test_rsa.pub"),
|
||||
PasswordUtils.createOneOff(correctPassphrase));
|
||||
assertNotNull(keyFile.getPrivate());
|
||||
PublicKey pubKey = keyFile.getPublic();
|
||||
assertNotNull(pubKey);
|
||||
assertEquals("RSA", pubKey.getAlgorithm());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSuccessfullyLoadSignedRSAPublicKeyWithMaxDate() throws IOException {
|
||||
FileKeyProvider keyFile = new OpenSSHKeyFile();
|
||||
@@ -422,6 +434,17 @@ public class OpenSSHKeyFileTest {
|
||||
assertEquals("", certificate.getExtensions().get("permit-pty"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSuccessfullyLoadSignedDSAPublicKeyFromStream() throws IOException {
|
||||
FileKeyProvider keyFile = new OpenSSHKeyFile();
|
||||
keyFile.init(new FileReader("src/test/resources/keytypes/certificate/test_dsa"),
|
||||
new FileReader("src/test/resources/keytypes/certificate/test_dsa-cert.pub"),
|
||||
PasswordUtils.createOneOff(correctPassphrase));
|
||||
assertNotNull(keyFile.getPrivate());
|
||||
PublicKey pubKey = keyFile.getPublic();
|
||||
assertEquals("DSA", pubKey.getAlgorithm());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sometimes users copy-pastes private and public keys in text editors. It leads to redundant
|
||||
* spaces and newlines. OpenSSH can easily read such keys, so users expect from SSHJ the same.
|
||||
|
||||
@@ -18,15 +18,19 @@ package net.schmizz.sshj.keyprovider;
|
||||
import com.hierynomus.sshj.userauth.keyprovider.OpenSSHKeyV1KeyFile;
|
||||
import net.schmizz.sshj.userauth.keyprovider.PKCS8KeyFile;
|
||||
import net.schmizz.sshj.userauth.keyprovider.PuTTYKeyFile;
|
||||
import net.schmizz.sshj.util.CorruptBase64;
|
||||
import net.schmizz.sshj.util.UnitTestPasswordFinder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.Objects;
|
||||
|
||||
import static java.lang.Math.min;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class PuTTYKeyFileTest {
|
||||
@@ -421,7 +425,6 @@ public class PuTTYKeyFileTest {
|
||||
|
||||
PKCS8KeyFile referenceKey = new PKCS8KeyFile();
|
||||
referenceKey.init(new File("src/test/resources/keytypes/test_ecdsa_nistp256"));
|
||||
assertEquals(key.getPrivate(), referenceKey.getPrivate());
|
||||
assertEquals(key.getPublic(), referenceKey.getPublic());
|
||||
}
|
||||
|
||||
@@ -558,4 +561,61 @@ public class PuTTYKeyFileTest {
|
||||
assertNull(key.getPrivate());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void corruptedPublicLines() throws Exception {
|
||||
assertThrows(IOException.class, () -> {
|
||||
PuTTYKeyFile key = new PuTTYKeyFile();
|
||||
key.init(new StringReader(corruptBase64InPuttyKey(ppk2048, "Public-Lines: ")));
|
||||
key.getPublic();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void corruptedPrivateLines() throws Exception {
|
||||
assertThrows(IOException.class, () -> {
|
||||
PuTTYKeyFile key = new PuTTYKeyFile();
|
||||
key.init(new StringReader(corruptBase64InPuttyKey(ppk2048, "Private-Lines: ")));
|
||||
key.getPublic();
|
||||
});
|
||||
}
|
||||
|
||||
private String corruptBase64InPuttyKey(
|
||||
@SuppressWarnings("SameParameterValue") String source,
|
||||
String sectionPrefix
|
||||
) throws IOException {
|
||||
try (var reader = new BufferedReader(new StringReader(source))) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (true) {
|
||||
String line = reader.readLine();
|
||||
if (line == null) {
|
||||
break;
|
||||
} else if (line.startsWith(sectionPrefix)) {
|
||||
int base64LineCount = Integer.parseInt(line.substring(sectionPrefix.length()));
|
||||
StringBuilder base64 = new StringBuilder();
|
||||
for (int i = 0; i < base64LineCount; ++i) {
|
||||
base64.append(Objects.requireNonNull(reader.readLine()));
|
||||
}
|
||||
String corruptedBase64 = CorruptBase64.corruptBase64(base64.toString());
|
||||
|
||||
// 64 is the length of base64 lines in PuTTY keys generated by puttygen.
|
||||
// It's not clear if it's some standard or not.
|
||||
// It doesn't match the MIME Base64 standard.
|
||||
int chunkSize = 64;
|
||||
|
||||
result.append(sectionPrefix);
|
||||
result.append((corruptedBase64.length() + chunkSize - 1) / chunkSize);
|
||||
result.append('\n');
|
||||
for (int offset = 0; offset < corruptedBase64.length(); offset += chunkSize) {
|
||||
result.append(corruptedBase64, offset, min(corruptedBase64.length(), offset + chunkSize));
|
||||
result.append('\n');
|
||||
}
|
||||
} else {
|
||||
result.append(line);
|
||||
result.append('\n');
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,17 +15,24 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.kex;
|
||||
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
import net.schmizz.sshj.transport.random.JCERandom;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.Provider;
|
||||
import java.security.Security;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class Curve25519DHTest {
|
||||
|
||||
private static final String ALGORITHM_FILTER = "KeyPairGenerator.X25519";
|
||||
|
||||
private static final int KEY_LENGTH = 32;
|
||||
|
||||
private static final byte[] PEER_PUBLIC_KEY = {
|
||||
@@ -35,8 +42,16 @@ public class Curve25519DHTest {
|
||||
1, 2, 3, 4, 5, 6, 7, 8
|
||||
};
|
||||
|
||||
@BeforeEach
|
||||
public void clearSecurityProvider() {
|
||||
SecurityUtils.setSecurityProvider(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitPublicKeyLength() throws GeneralSecurityException {
|
||||
final boolean bouncyCastleRegistrationRequired = isAlgorithmUnsupported();
|
||||
SecurityUtils.setRegisterBouncyCastle(bouncyCastleRegistrationRequired);
|
||||
|
||||
final Curve25519DH dh = new Curve25519DH();
|
||||
dh.init(null, new JCERandom.Factory());
|
||||
|
||||
@@ -48,6 +63,8 @@ public class Curve25519DHTest {
|
||||
|
||||
@Test
|
||||
public void testInitComputeSharedSecretKey() throws GeneralSecurityException {
|
||||
SecurityUtils.setRegisterBouncyCastle(true);
|
||||
|
||||
final Curve25519DH dh = new Curve25519DH();
|
||||
dh.init(null, new JCERandom.Factory());
|
||||
|
||||
@@ -57,4 +74,9 @@ public class Curve25519DHTest {
|
||||
assertNotNull(sharedSecretKey);
|
||||
assertEquals(BigInteger.ONE.signum(), sharedSecretKey.signum());
|
||||
}
|
||||
|
||||
private boolean isAlgorithmUnsupported() {
|
||||
final Provider[] providers = Security.getProviders(ALGORITHM_FILTER);
|
||||
return providers == null || providers.length == 0;
|
||||
}
|
||||
}
|
||||
|
||||
42
src/test/java/net/schmizz/sshj/util/CorruptBase64.java
Normal file
42
src/test/java/net/schmizz/sshj/util/CorruptBase64.java
Normal file
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import net.schmizz.sshj.common.Base64DecodingException;
|
||||
import net.schmizz.sshj.common.Base64Decoder;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class CorruptBase64 {
|
||||
private CorruptBase64() {
|
||||
}
|
||||
|
||||
public static String corruptBase64(String source) throws IOException {
|
||||
while (true) {
|
||||
try {
|
||||
Base64Decoder.decode(source);
|
||||
} catch (Base64DecodingException e) {
|
||||
return source;
|
||||
}
|
||||
|
||||
if (source.endsWith("=")) {
|
||||
source = source.substring(0, source.length() - 1);
|
||||
}
|
||||
source += "X";
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user