mirror of
https://github.com/hierynomus/sshj.git
synced 2025-12-08 08:10:55 +03:00
Merge branch 'master' into jumping
This commit is contained in:
@@ -19,23 +19,23 @@ import java.util.Collection;
|
||||
|
||||
public class ErrorDeliveryUtil {
|
||||
|
||||
public static void alertPromises(Throwable x, Promise... promises) {
|
||||
for (Promise p : promises)
|
||||
public static void alertPromises(Throwable x, Promise<?, ?>... promises) {
|
||||
for (Promise<?, ?> p : promises)
|
||||
p.deliverError(x);
|
||||
}
|
||||
|
||||
public static void alertPromises(Throwable x, Collection<? extends Promise> promises) {
|
||||
for (Promise p : promises)
|
||||
public static void alertPromises(Throwable x, Collection<? extends Promise<?, ?>> promises) {
|
||||
for (Promise<?, ?> p : promises)
|
||||
p.deliverError(x);
|
||||
}
|
||||
|
||||
public static void alertEvents(Throwable x, Event... events) {
|
||||
for (Event e : events)
|
||||
public static void alertEvents(Throwable x, Event<?>... events) {
|
||||
for (Event<?> e : events)
|
||||
e.deliverError(x);
|
||||
}
|
||||
|
||||
public static void alertEvents(Throwable x, Collection<? extends Event> events) {
|
||||
for (Event e : events)
|
||||
public static void alertEvents(Throwable x, Collection<? extends Event<?>> events) {
|
||||
for (Event<?> e : events)
|
||||
e.deliverError(x);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
*/
|
||||
package net.schmizz.concurrent;
|
||||
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
|
||||
/**
|
||||
* An event can be set, cleared, or awaited, similar to Python's {@code threading.event}. The key difference is that a
|
||||
* waiter may be delivered an exception of parameterized type {@code T}.
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
package net.schmizz.concurrent;
|
||||
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -22,8 +23,6 @@ import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Represents promised data of the parameterized type {@code V} and allows waiting on it. An exception may also be
|
||||
* delivered to a waiter, and will be of the parameterized type {@code T}.
|
||||
|
||||
@@ -15,12 +15,17 @@
|
||||
*/
|
||||
package net.schmizz.sshj;
|
||||
|
||||
import com.hierynomus.sshj.signature.SignatureEdDSA;
|
||||
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
import net.schmizz.sshj.signature.SignatureDSA;
|
||||
import net.schmizz.sshj.signature.SignatureRSA;
|
||||
import net.schmizz.sshj.transport.random.JCERandom;
|
||||
import net.schmizz.sshj.transport.random.SingletonRandomFactory;
|
||||
|
||||
/**
|
||||
* Registers SpongyCastle as JCE provider.
|
||||
*/
|
||||
public class AndroidConfig
|
||||
extends DefaultConfig {
|
||||
|
||||
@@ -30,7 +35,9 @@ public class AndroidConfig
|
||||
|
||||
// don't add ECDSA
|
||||
protected void initSignatureFactories() {
|
||||
setSignatureFactories(new SignatureRSA.Factory(), new SignatureDSA.Factory());
|
||||
setSignatureFactories(new SignatureRSA.Factory(), new SignatureDSA.Factory(),
|
||||
// but add EdDSA
|
||||
new SignatureEdDSA.Factory());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
package net.schmizz.sshj;
|
||||
|
||||
import net.schmizz.keepalive.KeepAliveProvider;
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
import net.schmizz.sshj.common.Factory;
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
import net.schmizz.sshj.signature.Signature;
|
||||
import net.schmizz.sshj.transport.cipher.Cipher;
|
||||
import net.schmizz.sshj.transport.compression.Compression;
|
||||
|
||||
@@ -15,22 +15,13 @@
|
||||
*/
|
||||
package net.schmizz.sshj;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import com.hierynomus.sshj.signature.SignatureEdDSA;
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
import com.hierynomus.sshj.transport.cipher.StreamCiphers;
|
||||
import com.hierynomus.sshj.transport.kex.DHGroups;
|
||||
import com.hierynomus.sshj.transport.kex.ExtendedDHGroups;
|
||||
import com.hierynomus.sshj.transport.mac.Macs;
|
||||
import com.hierynomus.sshj.userauth.keyprovider.OpenSSHKeyV1KeyFile;
|
||||
|
||||
import net.schmizz.keepalive.KeepAliveProvider;
|
||||
import net.schmizz.sshj.common.Factory;
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
@@ -38,26 +29,12 @@ import net.schmizz.sshj.common.SecurityUtils;
|
||||
import net.schmizz.sshj.signature.SignatureDSA;
|
||||
import net.schmizz.sshj.signature.SignatureECDSA;
|
||||
import net.schmizz.sshj.signature.SignatureRSA;
|
||||
import net.schmizz.sshj.transport.cipher.AES128CBC;
|
||||
import net.schmizz.sshj.transport.cipher.AES128CTR;
|
||||
import net.schmizz.sshj.transport.cipher.AES192CBC;
|
||||
import net.schmizz.sshj.transport.cipher.AES192CTR;
|
||||
import net.schmizz.sshj.transport.cipher.AES256CBC;
|
||||
import net.schmizz.sshj.transport.cipher.AES256CTR;
|
||||
import net.schmizz.sshj.transport.cipher.BlowfishCBC;
|
||||
import net.schmizz.sshj.transport.cipher.Cipher;
|
||||
import net.schmizz.sshj.transport.cipher.TripleDESCBC;
|
||||
import net.schmizz.sshj.transport.cipher.*;
|
||||
import net.schmizz.sshj.transport.compression.NoneCompression;
|
||||
import net.schmizz.sshj.transport.kex.Curve25519SHA256;
|
||||
import net.schmizz.sshj.transport.kex.DHGexSHA1;
|
||||
import net.schmizz.sshj.transport.kex.DHGexSHA256;
|
||||
import net.schmizz.sshj.transport.kex.ECDHNistP;
|
||||
import net.schmizz.sshj.transport.mac.HMACMD5;
|
||||
import net.schmizz.sshj.transport.mac.HMACMD596;
|
||||
import net.schmizz.sshj.transport.mac.HMACSHA1;
|
||||
import net.schmizz.sshj.transport.mac.HMACSHA196;
|
||||
import net.schmizz.sshj.transport.mac.HMACSHA2256;
|
||||
import net.schmizz.sshj.transport.mac.HMACSHA2512;
|
||||
import net.schmizz.sshj.transport.random.BouncyCastleRandom;
|
||||
import net.schmizz.sshj.transport.random.JCERandom;
|
||||
import net.schmizz.sshj.transport.random.SingletonRandomFactory;
|
||||
@@ -65,6 +42,9 @@ import net.schmizz.sshj.userauth.keyprovider.OpenSSHKeyFile;
|
||||
import net.schmizz.sshj.userauth.keyprovider.PKCS5KeyFile;
|
||||
import net.schmizz.sshj.userauth.keyprovider.PKCS8KeyFile;
|
||||
import net.schmizz.sshj.userauth.keyprovider.PuTTYKeyFile;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* A {@link net.schmizz.sshj.Config} that is initialized as follows. Items marked with an asterisk are added to the config only if
|
||||
@@ -72,9 +52,7 @@ import net.schmizz.sshj.userauth.keyprovider.PuTTYKeyFile;
|
||||
* <p/>
|
||||
* <ul>
|
||||
* <li>{@link net.schmizz.sshj.ConfigImpl#setKeyExchangeFactories Key exchange}: {@link net.schmizz.sshj.transport.kex.DHG14}*, {@link net.schmizz.sshj.transport.kex.DHG1}</li>
|
||||
* <li>{@link net.schmizz.sshj.ConfigImpl#setCipherFactories Ciphers} [1]: {@link net.schmizz.sshj.transport.cipher.AES128CTR}, {@link net.schmizz.sshj.transport.cipher.AES192CTR}, {@link net.schmizz.sshj.transport.cipher.AES256CTR},
|
||||
* {@link
|
||||
* net.schmizz.sshj.transport.cipher.AES128CBC}, {@link net.schmizz.sshj.transport.cipher.AES192CBC}, {@link net.schmizz.sshj.transport.cipher.AES256CBC}, {@link net.schmizz.sshj.transport.cipher.AES192CBC}, {@link net.schmizz.sshj.transport.cipher.TripleDESCBC}, {@link net.schmizz.sshj.transport.cipher.BlowfishCBC}</li>
|
||||
* <li>{@link net.schmizz.sshj.ConfigImpl#setCipherFactories Ciphers}: {@link BlockCiphers}, {@link StreamCiphers} [1]</li>
|
||||
* <li>{@link net.schmizz.sshj.ConfigImpl#setMACFactories MAC}: {@link net.schmizz.sshj.transport.mac.HMACSHA1}, {@link net.schmizz.sshj.transport.mac.HMACSHA196}, {@link net.schmizz.sshj.transport.mac.HMACMD5}, {@link
|
||||
* net.schmizz.sshj.transport.mac.HMACMD596}</li>
|
||||
* <li>{@link net.schmizz.sshj.ConfigImpl#setCompressionFactories Compression}: {@link net.schmizz.sshj.transport.compression.NoneCompression}</li>
|
||||
@@ -113,7 +91,7 @@ public class DefaultConfig
|
||||
properties.load(DefaultConfig.class.getClassLoader().getResourceAsStream("sshj.properties"));
|
||||
String property = properties.getProperty("sshj.version");
|
||||
return "SSHJ_" + property.replace('-', '_'); // '-' is a disallowed character, see RFC-4253#section-4.2
|
||||
} catch (IOException e) {
|
||||
} catch (Exception e) {
|
||||
log.error("Could not read the sshj.properties file, returning an 'unknown' version as fallback.");
|
||||
return "SSHJ_VERSION_UNKNOWN";
|
||||
}
|
||||
@@ -127,7 +105,9 @@ public class DefaultConfig
|
||||
|
||||
protected void initKeyExchangeFactories(boolean bouncyCastleRegistered) {
|
||||
if (bouncyCastleRegistered) {
|
||||
setKeyExchangeFactories(new Curve25519SHA256.Factory(),
|
||||
setKeyExchangeFactories(
|
||||
new Curve25519SHA256.Factory(),
|
||||
new Curve25519SHA256.FactoryLibSsh(),
|
||||
new DHGexSHA256.Factory(),
|
||||
new ECDHNistP.Factory521(),
|
||||
new ECDHNistP.Factory384(),
|
||||
@@ -172,14 +152,13 @@ public class DefaultConfig
|
||||
|
||||
protected void initCipherFactories() {
|
||||
List<Factory.Named<Cipher>> avail = new LinkedList<Factory.Named<Cipher>>(Arrays.<Factory.Named<Cipher>>asList(
|
||||
new AES128CTR.Factory(),
|
||||
new AES192CTR.Factory(),
|
||||
new AES256CTR.Factory(),
|
||||
new AES128CBC.Factory(),
|
||||
new AES192CBC.Factory(),
|
||||
new AES256CBC.Factory(),
|
||||
new TripleDESCBC.Factory(),
|
||||
new BlowfishCBC.Factory(),
|
||||
BlockCiphers.AES128CBC(),
|
||||
BlockCiphers.AES128CTR(),
|
||||
BlockCiphers.AES192CBC(),
|
||||
BlockCiphers.AES192CTR(),
|
||||
BlockCiphers.AES256CBC(),
|
||||
BlockCiphers.AES256CTR(),
|
||||
BlockCiphers.BlowfishCBC(),
|
||||
BlockCiphers.BlowfishCTR(),
|
||||
BlockCiphers.Cast128CBC(),
|
||||
BlockCiphers.Cast128CTR(),
|
||||
@@ -191,6 +170,7 @@ public class DefaultConfig
|
||||
BlockCiphers.Serpent192CTR(),
|
||||
BlockCiphers.Serpent256CBC(),
|
||||
BlockCiphers.Serpent256CTR(),
|
||||
BlockCiphers.TripleDESCBC(),
|
||||
BlockCiphers.TripleDESCTR(),
|
||||
BlockCiphers.Twofish128CBC(),
|
||||
BlockCiphers.Twofish128CTR(),
|
||||
@@ -229,23 +209,33 @@ public class DefaultConfig
|
||||
|
||||
protected void initSignatureFactories() {
|
||||
setSignatureFactories(
|
||||
new SignatureEdDSA.Factory(),
|
||||
new SignatureECDSA.Factory256(),
|
||||
new SignatureECDSA.Factory384(),
|
||||
new SignatureECDSA.Factory521(),
|
||||
new SignatureRSA.Factory(),
|
||||
new SignatureDSA.Factory(),
|
||||
new SignatureEdDSA.Factory()
|
||||
new SignatureDSA.Factory()
|
||||
);
|
||||
}
|
||||
|
||||
protected void initMACFactories() {
|
||||
setMACFactories(
|
||||
new HMACSHA1.Factory(),
|
||||
new HMACSHA196.Factory(),
|
||||
new HMACMD5.Factory(),
|
||||
new HMACMD596.Factory(),
|
||||
new HMACSHA2256.Factory(),
|
||||
new HMACSHA2512.Factory()
|
||||
Macs.HMACSHA1(),
|
||||
Macs.HMACSHA1Etm(),
|
||||
Macs.HMACSHA196(),
|
||||
Macs.HMACSHA196Etm(),
|
||||
Macs.HMACMD5(),
|
||||
Macs.HMACMD5Etm(),
|
||||
Macs.HMACMD596(),
|
||||
Macs.HMACMD596Etm(),
|
||||
Macs.HMACSHA2256(),
|
||||
Macs.HMACSHA2256Etm(),
|
||||
Macs.HMACSHA2512(),
|
||||
Macs.HMACSHA2512Etm(),
|
||||
Macs.HMACRIPEMD160(),
|
||||
Macs.HMACRIPEMD160Etm(),
|
||||
Macs.HMACRIPEMD16096(),
|
||||
Macs.HMACRIPEMD160OpenSsh()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,11 +15,7 @@
|
||||
*/
|
||||
package net.schmizz.sshj;
|
||||
|
||||
import net.schmizz.sshj.common.Factory;
|
||||
import net.schmizz.sshj.common.IOUtils;
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
import net.schmizz.sshj.common.SSHException;
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
import net.schmizz.sshj.common.*;
|
||||
import net.schmizz.sshj.connection.Connection;
|
||||
import net.schmizz.sshj.connection.ConnectionException;
|
||||
import net.schmizz.sshj.connection.ConnectionImpl;
|
||||
@@ -43,6 +39,7 @@ import net.schmizz.sshj.transport.compression.DelayedZlibCompression;
|
||||
import net.schmizz.sshj.transport.compression.NoneCompression;
|
||||
import net.schmizz.sshj.transport.compression.ZlibCompression;
|
||||
import net.schmizz.sshj.transport.verification.AlgorithmsVerifier;
|
||||
import net.schmizz.sshj.transport.verification.FingerprintVerifier;
|
||||
import net.schmizz.sshj.transport.verification.HostKeyVerifier;
|
||||
import net.schmizz.sshj.transport.verification.OpenSSHKnownHosts;
|
||||
import net.schmizz.sshj.userauth.UserAuth;
|
||||
@@ -65,7 +62,6 @@ import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.nio.charset.Charset;
|
||||
import java.security.KeyPair;
|
||||
import java.security.PublicKey;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
@@ -174,19 +170,23 @@ public class SSHClient
|
||||
|
||||
/**
|
||||
* Add a {@link HostKeyVerifier} that will verify any host that's able to claim a host key with the given {@code
|
||||
* fingerprint}, e.g. {@code "4b:69:6c:72:6f:79:20:77:61:73:20:68:65:72:65:21"}
|
||||
* fingerprint}.
|
||||
*
|
||||
* The fingerprint can be specified in either an MD5 colon-delimited format (16 hexadecimal octets, delimited by a colon),
|
||||
* or in a Base64 encoded format for SHA-1 or SHA-256 fingerprints.
|
||||
* Valid examples are:
|
||||
*
|
||||
* <ul><li>"SHA1:2Fo8c/96zv32xc8GZWbOGYOlRak="</li>
|
||||
* <li>"SHA256:oQGbQTujGeNIgh0ONthcEpA/BHxtt3rcYY+NxXTxQjs="</li>
|
||||
* <li>"MD5:d3:5e:40:72:db:08:f1:6d:0c:d7:6d:35:0d:ba:7c:32"</li>
|
||||
* <li>"d3:5e:40:72:db:08:f1:6d:0c:d7:6d:35:0d:ba:7c:32"</li></ul>
|
||||
*
|
||||
* @param fingerprint expected fingerprint in colon-delimited format (16 octets in hex delimited by a colon)
|
||||
*
|
||||
* @see SecurityUtils#getFingerprint
|
||||
*/
|
||||
public void addHostKeyVerifier(final String fingerprint) {
|
||||
addHostKeyVerifier(new HostKeyVerifier() {
|
||||
@Override
|
||||
public boolean verify(String h, int p, PublicKey k) {
|
||||
return SecurityUtils.getFingerprint(k).equals(fingerprint);
|
||||
}
|
||||
});
|
||||
addHostKeyVerifier(FingerprintVerifier.getInstance(fingerprint));
|
||||
}
|
||||
|
||||
// FIXME: there are way too many auth... overrides. Better API needed.
|
||||
@@ -360,8 +360,7 @@ public class SSHClient
|
||||
* @throws TransportException if there was a transport-layer error
|
||||
*/
|
||||
public void authPublickey(String username, KeyProvider... keyProviders)
|
||||
throws UserAuthException,
|
||||
TransportException {
|
||||
throws UserAuthException, TransportException {
|
||||
authPublickey(username, Arrays.<KeyProvider>asList(keyProviders));
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -132,8 +132,9 @@ public class Buffer<T extends Buffer<T>> {
|
||||
|
||||
protected void ensureAvailable(int a)
|
||||
throws BufferException {
|
||||
if (available() < a)
|
||||
if (available() < a) {
|
||||
throw new BufferException("Underflow");
|
||||
}
|
||||
}
|
||||
|
||||
public void ensureCapacity(int capacity) {
|
||||
@@ -147,7 +148,6 @@ public class Buffer<T extends Buffer<T>> {
|
||||
|
||||
/** Compact this {@link SSHPacket} */
|
||||
public void compact() {
|
||||
System.err.println("COMPACTING");
|
||||
if (available() > 0)
|
||||
System.arraycopy(data, rpos, data, 0, wpos - rpos);
|
||||
wpos -= rpos;
|
||||
@@ -246,7 +246,7 @@ public class Buffer<T extends Buffer<T>> {
|
||||
* @return this
|
||||
*/
|
||||
public T putBytes(byte[] b, int off, int len) {
|
||||
return putUInt32(len - off).putRawBytes(b, off, len);
|
||||
return putUInt32(len).putRawBytes(b, off, len);
|
||||
}
|
||||
|
||||
public void readRawBytes(byte[] buf)
|
||||
@@ -356,8 +356,9 @@ public class Buffer<T extends Buffer<T>> {
|
||||
}
|
||||
|
||||
public T putUInt64(long uint64) {
|
||||
if (uint64 < 0)
|
||||
if (uint64 < 0) {
|
||||
throw new IllegalArgumentException("Invalid value: " + uint64);
|
||||
}
|
||||
return putUInt64Unchecked(uint64);
|
||||
}
|
||||
|
||||
@@ -371,6 +372,7 @@ public class Buffer<T extends Buffer<T>> {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private T putUInt64Unchecked(long uint64) {
|
||||
ensureCapacity(8);
|
||||
data[wpos++] = (byte) (uint64 >> 56);
|
||||
data[wpos++] = (byte) (uint64 >> 48);
|
||||
data[wpos++] = (byte) (uint64 >> 40);
|
||||
@@ -392,8 +394,9 @@ public class Buffer<T extends Buffer<T>> {
|
||||
public String readString(Charset cs)
|
||||
throws BufferException {
|
||||
int len = readUInt32AsInt();
|
||||
if (len < 0 || len > 32768)
|
||||
if (len < 0 || len > 32768) {
|
||||
throw new BufferException("Bad item length: " + len);
|
||||
}
|
||||
ensureAvailable(len);
|
||||
String s = new String(data, rpos, len, cs);
|
||||
rpos += len;
|
||||
@@ -460,10 +463,13 @@ public class Buffer<T extends Buffer<T>> {
|
||||
|
||||
public PublicKey readPublicKey()
|
||||
throws BufferException {
|
||||
KeyType keyType = KeyType.fromString(readString());
|
||||
try {
|
||||
return KeyType.fromString(readString()).readPubKeyFromBuffer(this);
|
||||
return keyType.readPubKeyFromBuffer(this);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
throw new BufferException("Could not decode keytype " + keyType);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,4 +94,34 @@ public class ByteArrayUtils {
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
public static byte[] parseHex(String hex) {
|
||||
if (hex == null) {
|
||||
throw new IllegalArgumentException("Hex string is null");
|
||||
}
|
||||
if (hex.length() % 2 != 0) {
|
||||
throw new IllegalArgumentException("Hex string '" + hex + "' should have even length.");
|
||||
}
|
||||
|
||||
byte[] result = new byte[hex.length() / 2];
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
int hi = parseHexDigit(hex.charAt(i * 2)) << 4;
|
||||
int lo = parseHexDigit(hex.charAt(i * 2 + 1));
|
||||
result[i] = (byte) (hi + lo);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int parseHexDigit(char c) {
|
||||
if (c >= '0' && c <= '9') {
|
||||
return c - '0';
|
||||
}
|
||||
if (c >= 'a' && c <= 'f') {
|
||||
return c - 'a' + 10;
|
||||
}
|
||||
if (c >= 'A' && c <= 'F') {
|
||||
return c - 'A' + 10;
|
||||
}
|
||||
throw new IllegalArgumentException("Digit '" + c + "' out of bounds [0-9a-fA-F]");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,26 +15,27 @@
|
||||
*/
|
||||
package net.schmizz.sshj.common;
|
||||
|
||||
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;
|
||||
|
||||
import org.bouncycastle.asn1.nist.NISTNamedCurves;
|
||||
import org.bouncycastle.asn1.x9.X9ECParameters;
|
||||
import org.bouncycastle.jce.spec.ECParameterSpec;
|
||||
import org.bouncycastle.jce.spec.ECPublicKeySpec;
|
||||
import org.bouncycastle.math.ec.ECPoint;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.hierynomus.sshj.secg.SecgUtils;
|
||||
|
||||
public class ECDSAVariationsAdapter {
|
||||
class ECDSAVariationsAdapter {
|
||||
|
||||
private final static String BASE_ALGORITHM_NAME = "ecdsa-sha2-nistp";
|
||||
|
||||
@@ -53,7 +54,7 @@ public class ECDSAVariationsAdapter {
|
||||
SUPPORTED_CURVES.put("521", "nistp521");
|
||||
}
|
||||
|
||||
public static PublicKey readPubKeyFromBuffer(Buffer<?> buf, String variation) throws GeneralSecurityException {
|
||||
static PublicKey readPubKeyFromBuffer(Buffer<?> buf, String variation) throws GeneralSecurityException {
|
||||
String algorithm = BASE_ALGORITHM_NAME + variation;
|
||||
if (!SecurityUtils.isBouncyCastleRegistered()) {
|
||||
throw new GeneralSecurityException("BouncyCastle is required to read a key of type " + algorithm);
|
||||
@@ -80,19 +81,20 @@ public class ECDSAVariationsAdapter {
|
||||
BigInteger bigX = new BigInteger(1, x);
|
||||
BigInteger bigY = new BigInteger(1, y);
|
||||
|
||||
X9ECParameters ecParams = NISTNamedCurves.getByName(NIST_CURVES_NAMES.get(variation));
|
||||
ECPoint pPublicPoint = ecParams.getCurve().createPoint(bigX, bigY);
|
||||
ECParameterSpec spec = new ECParameterSpec(ecParams.getCurve(), ecParams.getG(), ecParams.getN());
|
||||
ECPublicKeySpec publicSpec = new ECPublicKeySpec(pPublicPoint, spec);
|
||||
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("ECDSA");
|
||||
return keyFactory.generatePublic(publicSpec);
|
||||
return keyFactory.generatePublic(publicKeySpec);
|
||||
} catch (Exception ex) {
|
||||
throw new GeneralSecurityException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static void writePubKeyContentsIntoBuffer(PublicKey pk, Buffer<?> buf) {
|
||||
static void writePubKeyContentsIntoBuffer(PublicKey pk, Buffer<?> buf) {
|
||||
final ECPublicKey ecdsa = (ECPublicKey) pk;
|
||||
byte[] encoded = SecgUtils.getEncoded(ecdsa.getW(), ecdsa.getParams().getCurve());
|
||||
|
||||
@@ -100,8 +102,12 @@ public class ECDSAVariationsAdapter {
|
||||
.putBytes(encoded);
|
||||
}
|
||||
|
||||
public static int fieldSizeFromKey(ECPublicKey ecPublicKey) {
|
||||
return ecPublicKey.getParams().getCurve().getField().getFieldSize();
|
||||
static boolean isECKeyWithFieldSize(Key key, int fieldSize) {
|
||||
return "ECDSA".equals(key.getAlgorithm())
|
||||
&& fieldSizeFromKey((ECKey) key) == fieldSize;
|
||||
}
|
||||
|
||||
private static int fieldSizeFromKey(ECKey ecPublicKey) {
|
||||
return ecPublicKey.getParams().getCurve().getField().getFieldSize();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ public class IOUtils {
|
||||
if (c != null)
|
||||
c.close();
|
||||
} catch (IOException logged) {
|
||||
loggerFactory.getLogger(IOUtils.class).warn("Error closing {} - {}", c, logged);
|
||||
loggerFactory.getLogger(IOUtils.class).warn("Error closing {} - {}", c, logged);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,16 @@
|
||||
*/
|
||||
package net.schmizz.sshj.common;
|
||||
|
||||
import com.hierynomus.sshj.signature.Ed25519PublicKey;
|
||||
import com.hierynomus.sshj.userauth.certificate.Certificate;
|
||||
import net.i2p.crypto.eddsa.EdDSAPublicKey;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveSpec;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec;
|
||||
import net.schmizz.sshj.common.Buffer.BufferException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.Key;
|
||||
@@ -22,30 +32,11 @@ import java.security.KeyFactory;
|
||||
import java.security.PublicKey;
|
||||
import java.security.interfaces.DSAPrivateKey;
|
||||
import java.security.interfaces.DSAPublicKey;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.DSAPublicKeySpec;
|
||||
import java.security.spec.RSAPublicKeySpec;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.hierynomus.sshj.signature.Ed25519PublicKey;
|
||||
import com.hierynomus.sshj.userauth.certificate.Certificate;
|
||||
|
||||
import net.i2p.crypto.eddsa.EdDSAPublicKey;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveSpec;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
|
||||
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec;
|
||||
import net.schmizz.sshj.common.Buffer.BufferException;
|
||||
import java.util.*;
|
||||
|
||||
/** Type of key e.g. rsa, dsa */
|
||||
public enum KeyType {
|
||||
@@ -130,7 +121,7 @@ public enum KeyType {
|
||||
|
||||
@Override
|
||||
protected boolean isMyType(Key key) {
|
||||
return ("ECDSA".equals(key.getAlgorithm()) && ECDSAVariationsAdapter.fieldSizeFromKey((ECPublicKey) key) == 256);
|
||||
return ECDSAVariationsAdapter.isECKeyWithFieldSize(key, 256);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -151,7 +142,7 @@ public enum KeyType {
|
||||
|
||||
@Override
|
||||
protected boolean isMyType(Key key) {
|
||||
return ("ECDSA".equals(key.getAlgorithm()) && ECDSAVariationsAdapter.fieldSizeFromKey((ECPublicKey) key) == 384);
|
||||
return ECDSAVariationsAdapter.isECKeyWithFieldSize(key, 384);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -172,7 +163,7 @@ public enum KeyType {
|
||||
|
||||
@Override
|
||||
protected boolean isMyType(Key key) {
|
||||
return ("ECDSA".equals(key.getAlgorithm()) && ECDSAVariationsAdapter.fieldSizeFromKey((ECPublicKey) key) == 521);
|
||||
return ECDSAVariationsAdapter.isECKeyWithFieldSize(key, 521);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -192,7 +183,7 @@ public enum KeyType {
|
||||
);
|
||||
}
|
||||
|
||||
EdDSANamedCurveSpec ed25519 = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512);
|
||||
EdDSANamedCurveSpec ed25519 = EdDSANamedCurveTable.getByName("Ed25519");
|
||||
EdDSAPublicKeySpec publicSpec = new EdDSAPublicKeySpec(p, ed25519);
|
||||
return new Ed25519PublicKey(publicSpec);
|
||||
|
||||
|
||||
@@ -15,13 +15,24 @@
|
||||
*/
|
||||
package net.schmizz.sshj.common;
|
||||
|
||||
import java.security.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.security.Provider;
|
||||
import java.security.PublicKey;
|
||||
import java.security.Security;
|
||||
import java.security.Signature;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyAgreement;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
@@ -36,12 +47,17 @@ public class SecurityUtils {
|
||||
*/
|
||||
public static final String BOUNCY_CASTLE = "BC";
|
||||
|
||||
/**
|
||||
* Identifier for the BouncyCastle JCE provider
|
||||
*/
|
||||
public static final String SPONGY_CASTLE = "SC";
|
||||
|
||||
/*
|
||||
* Security provider identifier. null = default JCE
|
||||
*/
|
||||
private static String securityProvider = null;
|
||||
|
||||
// relate to BC registration
|
||||
// relate to BC registration (or SpongyCastle on Android)
|
||||
private static Boolean registerBouncyCastle;
|
||||
private static boolean registrationDone;
|
||||
|
||||
@@ -68,19 +84,21 @@ public class SecurityUtils {
|
||||
}
|
||||
|
||||
if (securityProvider == null) {
|
||||
MessageDigest.getInstance("MD5", provider.getName());
|
||||
KeyAgreement.getInstance("DH", provider.getName());
|
||||
MessageDigest.getInstance("MD5", provider);
|
||||
KeyAgreement.getInstance("DH", provider);
|
||||
setSecurityProvider(provider.getName());
|
||||
return true;
|
||||
}
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
LOG.info(format("Security Provider '%s' does not support necessary algorithm", providerClassName), e);
|
||||
} catch (NoSuchProviderException e) {
|
||||
LOG.info("Registration of Security Provider '{}' unexpectedly failed", providerClassName);
|
||||
} catch (Exception e) {
|
||||
LOG.info(format("Registration of Security Provider '%s' unexpectedly failed", providerClassName), e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static synchronized Cipher getCipher(String transformation)
|
||||
throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException {
|
||||
register();
|
||||
@@ -221,11 +239,11 @@ public class SecurityUtils {
|
||||
* Attempts registering BouncyCastle as security provider if it has not been previously attempted and returns
|
||||
* whether the registration succeeded.
|
||||
*
|
||||
* @return whether BC registered
|
||||
* @return whether BC (or SC on Android) registered
|
||||
*/
|
||||
public static synchronized boolean isBouncyCastleRegistered() {
|
||||
register();
|
||||
return BOUNCY_CASTLE.equals(securityProvider);
|
||||
return BOUNCY_CASTLE.equals(securityProvider) || SPONGY_CASTLE.equals(securityProvider);
|
||||
}
|
||||
|
||||
public static synchronized void setRegisterBouncyCastle(boolean registerBouncyCastle) {
|
||||
|
||||
@@ -130,6 +130,9 @@ public class ConnectionImpl
|
||||
getChannel(buf).handle(msg, buf);
|
||||
} else if (msg.in(80, 90)) {
|
||||
switch (msg) {
|
||||
case GLOBAL_REQUEST:
|
||||
gotGlobalRequest(buf);
|
||||
break;
|
||||
case REQUEST_SUCCESS:
|
||||
gotGlobalReqResponse(buf);
|
||||
break;
|
||||
@@ -259,6 +262,20 @@ public class ConnectionImpl
|
||||
channels.clear();
|
||||
}
|
||||
|
||||
private void gotGlobalRequest(SSHPacket buf)
|
||||
throws ConnectionException, TransportException {
|
||||
try {
|
||||
final String requestName = buf.readString();
|
||||
boolean wantReply = buf.readBoolean();
|
||||
log.debug("Received GLOBAL_REQUEST `{}`; want reply: {}", requestName, wantReply);
|
||||
if (wantReply) {
|
||||
trans.write(new SSHPacket(Message.REQUEST_FAILURE));
|
||||
}
|
||||
} catch (Buffer.BufferException be) {
|
||||
throw new ConnectionException(be);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTimeoutMs(int timeoutMs) {
|
||||
this.timeoutMs = timeoutMs;
|
||||
|
||||
@@ -102,7 +102,8 @@ public abstract class AbstractChannel
|
||||
|
||||
protected void init(int recipient, long remoteWinSize, long remoteMaxPacketSize) {
|
||||
this.recipient = recipient;
|
||||
rwin = new Window.Remote(remoteWinSize, (int) Math.min(remoteMaxPacketSize, REMOTE_MAX_PACKET_SIZE_CEILING), loggerFactory);
|
||||
rwin = new Window.Remote(remoteWinSize, (int) Math.min(remoteMaxPacketSize, REMOTE_MAX_PACKET_SIZE_CEILING),
|
||||
conn.getTimeoutMs(), loggerFactory);
|
||||
out = new ChannelOutputStream(this, trans, rwin);
|
||||
log.debug("Initialized - {}", this);
|
||||
}
|
||||
@@ -362,10 +363,12 @@ public abstract class AbstractChannel
|
||||
} catch (Buffer.BufferException be) {
|
||||
throw new ConnectionException(be);
|
||||
}
|
||||
if (len < 0 || len > getLocalMaxPacketSize() || len > buf.available())
|
||||
if (len < 0 || len > getLocalMaxPacketSize() || len > buf.available()) {
|
||||
throw new ConnectionException(DisconnectReason.PROTOCOL_ERROR, "Bad item length: " + len);
|
||||
if (log.isTraceEnabled())
|
||||
}
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("IN #{}: {}", id, ByteArrayUtils.printHex(buf.array(), buf.rpos(), len));
|
||||
}
|
||||
stream.receive(buf.array(), buf.rpos(), len);
|
||||
}
|
||||
|
||||
|
||||
@@ -92,36 +92,43 @@ public final class ChannelInputStream
|
||||
throws IOException {
|
||||
synchronized (buf) {
|
||||
for (; ; ) {
|
||||
if (buf.available() > 0)
|
||||
if (buf.available() > 0) {
|
||||
break;
|
||||
if (eof)
|
||||
if (error != null)
|
||||
}
|
||||
if (eof) {
|
||||
if (error != null) {
|
||||
throw error;
|
||||
else
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
try {
|
||||
buf.wait();
|
||||
} catch (InterruptedException e) {
|
||||
throw (IOException) new InterruptedIOException().initCause(e);
|
||||
}
|
||||
}
|
||||
if (len > buf.available())
|
||||
if (len > buf.available()) {
|
||||
len = buf.available();
|
||||
}
|
||||
buf.readRawBytes(b, off, len);
|
||||
if (buf.rpos() > win.getMaxPacketSize() && buf.available() == 0)
|
||||
if (buf.rpos() > win.getMaxPacketSize() && buf.available() == 0) {
|
||||
buf.clear();
|
||||
}
|
||||
}
|
||||
|
||||
if (!chan.getAutoExpand())
|
||||
if (!chan.getAutoExpand()) {
|
||||
checkWindow();
|
||||
}
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
public void receive(byte[] data, int offset, int len)
|
||||
throws ConnectionException, TransportException {
|
||||
if (eof)
|
||||
if (eof) {
|
||||
throw new ConnectionException("Getting data on EOF'ed stream");
|
||||
}
|
||||
synchronized (buf) {
|
||||
buf.putRawBytes(data, offset, len);
|
||||
buf.notifyAll();
|
||||
@@ -132,8 +139,9 @@ public final class ChannelInputStream
|
||||
synchronized (win) {
|
||||
win.consume(len);
|
||||
}
|
||||
if (chan.getAutoExpand())
|
||||
if (chan.getAutoExpand()) {
|
||||
checkWindow();
|
||||
}
|
||||
}
|
||||
|
||||
private void checkWindow()
|
||||
@@ -143,7 +151,7 @@ public final class ChannelInputStream
|
||||
if (adjustment > 0) {
|
||||
log.debug("Sending SSH_MSG_CHANNEL_WINDOW_ADJUST to #{} for {} bytes", chan.getRecipient(), adjustment);
|
||||
trans.write(new SSHPacket(Message.CHANNEL_WINDOW_ADJUST)
|
||||
.putUInt32(chan.getRecipient()).putUInt32(adjustment));
|
||||
.putUInt32(chan.getRecipient()).putUInt32(adjustment));
|
||||
win.expand(adjustment);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,15 +39,21 @@ public class SocketStreamCopyMonitor
|
||||
new SocketStreamCopyMonitor(new Runnable() {
|
||||
public void run() {
|
||||
try {
|
||||
for (Event<IOException> ev = x;
|
||||
!ev.tryAwait(frequency, unit);
|
||||
ev = (ev == x) ? y : x) {
|
||||
}
|
||||
await(x);
|
||||
await(y);
|
||||
} catch (IOException ignored) {
|
||||
} finally {
|
||||
IOUtils.closeQuietly(channel, asCloseable(socket));
|
||||
}
|
||||
}
|
||||
|
||||
private void await(final Event<IOException> event) throws IOException {
|
||||
while(true){
|
||||
if(event.tryAwait(frequency, unit)){
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ import net.schmizz.sshj.common.SSHRuntimeException;
|
||||
import net.schmizz.sshj.connection.ConnectionException;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public abstract class Window {
|
||||
|
||||
protected final Logger log;
|
||||
@@ -59,8 +61,9 @@ public abstract class Window {
|
||||
synchronized (lock) {
|
||||
size -= dec;
|
||||
log.debug("Consuming by {} down to {}", dec, size);
|
||||
if (size < 0)
|
||||
if (size < 0) {
|
||||
throw new ConnectionException("Window consumed to below 0");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,17 +75,23 @@ public abstract class Window {
|
||||
/** Controls how much data we can send before an adjustment notification from remote end is required. */
|
||||
public static final class Remote
|
||||
extends Window {
|
||||
private final long timeoutMs;
|
||||
|
||||
public Remote(long initialWinSize, int maxPacketSize, LoggerFactory loggerFactory) {
|
||||
public Remote(long initialWinSize, int maxPacketSize, long timeoutMs, LoggerFactory loggerFactory) {
|
||||
super(initialWinSize, maxPacketSize, loggerFactory);
|
||||
this.timeoutMs = timeoutMs;
|
||||
}
|
||||
|
||||
public long awaitExpansion(long was) throws ConnectionException {
|
||||
synchronized (lock) {
|
||||
long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs);
|
||||
while (size <= was) {
|
||||
log.debug("Waiting, need size to grow from {} bytes", was);
|
||||
try {
|
||||
lock.wait();
|
||||
lock.wait(timeoutMs);
|
||||
if ((size <= was) && ((System.nanoTime() - end) > 0)) {
|
||||
throw new ConnectionException("Timeout when trying to expand the window size");
|
||||
}
|
||||
} catch (InterruptedException ie) {
|
||||
throw new ConnectionException(ie);
|
||||
}
|
||||
|
||||
@@ -137,6 +137,15 @@ public class LocalPortForwarder {
|
||||
listen(Thread.currentThread());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether this listener is running (ie. whether a thread is attached to it).
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
return this.runningThread != null && !serverSocket.isClosed();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start listening for incoming connections and forward to remote host as a channel and ensure that the thread is registered.
|
||||
* This is useful if for instance {@link #close() is called from another thread}
|
||||
@@ -172,8 +181,8 @@ public class LocalPortForwarder {
|
||||
public void close() throws IOException {
|
||||
if (!serverSocket.isClosed()) {
|
||||
log.info("Closing listener on {}", serverSocket.getLocalSocketAddress());
|
||||
serverSocket.close();
|
||||
runningThread.interrupt();
|
||||
serverSocket.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,8 +18,14 @@ package net.schmizz.sshj.sftp;
|
||||
public class PathComponents {
|
||||
|
||||
static String adjustForParent(String parent, String path, String pathSep) {
|
||||
return (path.startsWith(pathSep)) ? path // Absolute path, nothing to adjust
|
||||
: (parent + (parent.endsWith(pathSep) ? "" : pathSep) + path); // Relative path
|
||||
if (path.startsWith(pathSep)) {
|
||||
return path; // Absolute path, nothing to adjust
|
||||
} else if (parent.endsWith(pathSep)) {
|
||||
return parent + path; // Relative path, parent endsWith '/'
|
||||
} else if (parent.isEmpty()) {
|
||||
return path;
|
||||
}
|
||||
return parent + pathSep + path; // Relative path
|
||||
}
|
||||
|
||||
static String trimTrailingSeparator(String somePath, String pathSep) {
|
||||
@@ -33,7 +39,8 @@ public class PathComponents {
|
||||
public PathComponents(String parent, String name, String pathSep) {
|
||||
this.parent = parent;
|
||||
this.name = name;
|
||||
this.path = trimTrailingSeparator(adjustForParent(parent, name, pathSep), pathSep);
|
||||
String adjusted = adjustForParent(parent, name, pathSep);
|
||||
this.path = !pathSep.equals(adjusted) ? trimTrailingSeparator(adjusted, pathSep) : adjusted;
|
||||
}
|
||||
|
||||
public String getParent() {
|
||||
|
||||
@@ -70,16 +70,25 @@ public class PathHelper {
|
||||
*/
|
||||
public PathComponents getComponents(final String path)
|
||||
throws IOException {
|
||||
if (path.equals(pathSep))
|
||||
return getComponents("", "");
|
||||
if (path.equals(pathSep)) {
|
||||
return getComponents("", "/");
|
||||
}
|
||||
|
||||
if (path.isEmpty() || ".".equals(path) || ("." + pathSep).equals(path))
|
||||
if (path.isEmpty() || ".".equals(path) || ("." + pathSep).equals(path)) {
|
||||
return getComponents(getDotDir());
|
||||
}
|
||||
|
||||
final String withoutTrailSep = trimTrailingSeparator(path);
|
||||
final int lastSep = withoutTrailSep.lastIndexOf(pathSep);
|
||||
final String parent = (lastSep == -1) ? "" : withoutTrailSep.substring(0, lastSep);
|
||||
final String name = (lastSep == -1) ? withoutTrailSep : withoutTrailSep.substring(lastSep + pathSep.length());
|
||||
String parent;
|
||||
String name;
|
||||
if (lastSep == -1) {
|
||||
parent = "";
|
||||
name = withoutTrailSep;
|
||||
} else {
|
||||
parent = lastSep == 0 ? "/" : withoutTrailSep.substring(0, lastSep);
|
||||
name = withoutTrailSep.substring(lastSep + pathSep.length());
|
||||
}
|
||||
|
||||
if (".".equals(name) || "..".equals(name)) {
|
||||
return getComponents(canonicalizer.canonicalize(path));
|
||||
@@ -87,5 +96,4 @@ public class PathHelper {
|
||||
return getComponents(parent, name);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -82,9 +82,7 @@ public class RemoteFile
|
||||
throws IOException {
|
||||
return requester.request(newRequest(PacketType.WRITE)
|
||||
.putUInt64(fileOffset)
|
||||
// TODO The SFTP spec claims this field is unneeded...? See #187
|
||||
.putUInt32(len)
|
||||
.putRawBytes(data, off, len)
|
||||
.putString(data, off, len)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,9 @@ public final class Response
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
private final int protocolVersion;
|
||||
|
||||
@@ -15,34 +15,48 @@
|
||||
*/
|
||||
package net.schmizz.sshj.signature;
|
||||
|
||||
import net.schmizz.sshj.common.Buffer;
|
||||
import net.schmizz.sshj.common.SSHRuntimeException;
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.SignatureException;
|
||||
import java.security.*;
|
||||
|
||||
/** An abstract class for {@link Signature} that implements common functionality. */
|
||||
/**
|
||||
* An abstract class for {@link Signature} that implements common functionality.
|
||||
*/
|
||||
public abstract class AbstractSignature
|
||||
implements Signature {
|
||||
|
||||
protected final String algorithm;
|
||||
protected java.security.Signature signature;
|
||||
@SuppressWarnings("PMD.UnnecessaryFullyQualifiedName")
|
||||
protected final java.security.Signature signature;
|
||||
|
||||
protected AbstractSignature(String algorithm) {
|
||||
this.algorithm = algorithm;
|
||||
try {
|
||||
this.signature = SecurityUtils.getSignature(algorithm);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
protected AbstractSignature(@SuppressWarnings("PMD.UnnecessaryFullyQualifiedName")
|
||||
java.security.Signature signatureEngine) {
|
||||
this.signature = signatureEngine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(PublicKey publicKey, PrivateKey privateKey) {
|
||||
public void initVerify(PublicKey publicKey) {
|
||||
try {
|
||||
signature = SecurityUtils.getSignature(algorithm);
|
||||
if (publicKey != null)
|
||||
signature.initVerify(publicKey);
|
||||
if (privateKey != null)
|
||||
signature.initSign(privateKey);
|
||||
} catch (GeneralSecurityException e) {
|
||||
signature.initVerify(publicKey);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initSign(PrivateKey privateKey) {
|
||||
try {
|
||||
signature.initSign(privateKey);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
}
|
||||
}
|
||||
@@ -70,23 +84,24 @@ public abstract class AbstractSignature
|
||||
}
|
||||
}
|
||||
|
||||
protected byte[] extractSig(byte[] sig) {
|
||||
if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0) {
|
||||
int i = 0;
|
||||
int j = sig[i++] << 24 & 0xff000000
|
||||
| sig[i++] << 16 & 0x00ff0000
|
||||
| sig[i++] << 8 & 0x0000ff00
|
||||
| sig[i++] & 0x000000ff;
|
||||
i += j;
|
||||
j = sig[i++] << 24 & 0xff000000
|
||||
| sig[i++] << 16 & 0x00ff0000
|
||||
| sig[i++] << 8 & 0x0000ff00
|
||||
| sig[i++] & 0x000000ff;
|
||||
byte[] newSig = new byte[j];
|
||||
System.arraycopy(sig, i, newSig, 0, j);
|
||||
return newSig;
|
||||
/**
|
||||
* Check whether the signature is generated using the expected algorithm, and if so, return the signature blob
|
||||
*
|
||||
* @param sig The full signature
|
||||
* @param expectedKeyAlgorithm The expected key algorithm
|
||||
* @return The blob part of the signature
|
||||
*/
|
||||
protected byte[] extractSig(byte[] sig, String expectedKeyAlgorithm) {
|
||||
Buffer.PlainBuffer buffer = new Buffer.PlainBuffer(sig);
|
||||
try {
|
||||
String algo = buffer.readString();
|
||||
if (!expectedKeyAlgorithm.equals(algo)) {
|
||||
throw new SSHRuntimeException("Expected '" + expectedKeyAlgorithm + "' key algorithm, but got: " + algo);
|
||||
}
|
||||
return buffer.readBytes();
|
||||
} catch (Buffer.BufferException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
}
|
||||
return sig;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,13 +22,24 @@ import java.security.PublicKey;
|
||||
public interface Signature {
|
||||
|
||||
/**
|
||||
* Initialize this signature with the given public key and private key. If the private key is null, only signature
|
||||
* verification can be performed.
|
||||
* Initialize this signature with the given public key for signature verification.
|
||||
*
|
||||
* @param pubkey (null-ok) specify in case verification is needed
|
||||
* @param prvkey (null-ok) specify in case signing is needed
|
||||
* Note that subsequent calls to either {@link #initVerify(PublicKey)} or {@link #initSign(PrivateKey)} will
|
||||
* overwrite prior initialization.
|
||||
*
|
||||
* @param pubkey the public key to use for signature verification
|
||||
*/
|
||||
void init(PublicKey pubkey, PrivateKey prvkey);
|
||||
void initVerify(PublicKey pubkey);
|
||||
|
||||
/**
|
||||
* Initialize this signature with the given private key for signing.
|
||||
*
|
||||
* Note that subsequent calls to either {@link #initVerify(PublicKey)} or {@link #initSign(PrivateKey)} will
|
||||
* overwrite prior initialization.
|
||||
*
|
||||
* @param prvkey the private key to use for signing
|
||||
*/
|
||||
void initSign(PrivateKey prvkey);
|
||||
|
||||
/**
|
||||
* Convenience method, same as calling {@link #update(byte[], int, int)} with offset as {@code 0} and {@code
|
||||
|
||||
@@ -17,14 +17,23 @@ package net.schmizz.sshj.signature;
|
||||
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.common.SSHRuntimeException;
|
||||
import org.bouncycastle.asn1.*;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.security.SignatureException;
|
||||
import java.util.Arrays;
|
||||
|
||||
/** DSA {@link Signature} */
|
||||
/**
|
||||
* DSA {@link Signature}
|
||||
*/
|
||||
public class SignatureDSA
|
||||
extends AbstractSignature {
|
||||
|
||||
/** A named factory for DSA signature */
|
||||
/**
|
||||
* A named factory for DSA signature
|
||||
*/
|
||||
public static class Factory
|
||||
implements net.schmizz.sshj.common.Factory.Named<Signature> {
|
||||
|
||||
@@ -74,33 +83,33 @@ public class SignatureDSA
|
||||
|
||||
@Override
|
||||
public boolean verify(byte[] sig) {
|
||||
sig = extractSig(sig);
|
||||
|
||||
// ASN.1
|
||||
int frst = (sig[0] & 0x80) != 0 ? 1 : 0;
|
||||
int scnd = (sig[20] & 0x80) != 0 ? 1 : 0;
|
||||
|
||||
int length = sig.length + 6 + frst + scnd;
|
||||
byte[] tmp = new byte[length];
|
||||
tmp[0] = (byte) 0x30;
|
||||
tmp[1] = (byte) 0x2c;
|
||||
tmp[1] += frst;
|
||||
tmp[1] += scnd;
|
||||
tmp[2] = (byte) 0x02;
|
||||
tmp[3] = (byte) 0x14;
|
||||
tmp[3] += frst;
|
||||
System.arraycopy(sig, 0, tmp, 4 + frst, 20);
|
||||
tmp[4 + tmp[3]] = (byte) 0x02;
|
||||
tmp[5 + tmp[3]] = (byte) 0x14;
|
||||
tmp[5 + tmp[3]] += scnd;
|
||||
System.arraycopy(sig, 20, tmp, 6 + tmp[3] + scnd, 20);
|
||||
sig = tmp;
|
||||
|
||||
try {
|
||||
return signature.verify(sig);
|
||||
byte[] sigBlob = extractSig(sig, "ssh-dss");
|
||||
return signature.verify(asnEncode(sigBlob));
|
||||
} catch (SignatureException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
} catch (IOException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the signature as a DER sequence (ASN.1 format).
|
||||
*/
|
||||
private byte[] asnEncode(byte[] sigBlob) throws IOException {
|
||||
byte[] r = new BigInteger(1, Arrays.copyOfRange(sigBlob, 0, 20)).toByteArray();
|
||||
byte[] s = new BigInteger(1, Arrays.copyOfRange(sigBlob, 20, 40)).toByteArray();
|
||||
|
||||
ASN1EncodableVector vector = new ASN1EncodableVector();
|
||||
vector.add(new ASN1Integer(r));
|
||||
vector.add(new ASN1Integer(s));
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ASN1OutputStream asnOS = new ASN1OutputStream(baos);
|
||||
|
||||
asnOS.writeObject(new DERSequence(vector));
|
||||
asnOS.flush();
|
||||
|
||||
return baos.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,19 +15,18 @@
|
||||
*/
|
||||
package net.schmizz.sshj.signature;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.security.SignatureException;
|
||||
|
||||
import net.schmizz.sshj.common.Buffer;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.common.SSHRuntimeException;
|
||||
import org.bouncycastle.asn1.ASN1EncodableVector;
|
||||
import org.bouncycastle.asn1.ASN1Integer;
|
||||
import org.bouncycastle.asn1.ASN1OutputStream;
|
||||
import org.bouncycastle.asn1.DERSequence;
|
||||
|
||||
import net.schmizz.sshj.common.Buffer;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.common.SSHRuntimeException;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.security.SignatureException;
|
||||
|
||||
/** ECDSA {@link Signature} */
|
||||
public class SignatureECDSA extends AbstractSignature {
|
||||
@@ -99,7 +98,7 @@ public class SignatureECDSA extends AbstractSignature {
|
||||
System.arraycopy(sig, 4, r, 0, rLen);
|
||||
System.arraycopy(sig, 6 + rLen, s, 0, sLen);
|
||||
|
||||
Buffer buf = new Buffer.PlainBuffer();
|
||||
Buffer.PlainBuffer buf = new Buffer.PlainBuffer();
|
||||
buf.putMPInt(new BigInteger(r));
|
||||
buf.putMPInt(new BigInteger(s));
|
||||
|
||||
@@ -108,26 +107,9 @@ public class SignatureECDSA extends AbstractSignature {
|
||||
|
||||
@Override
|
||||
public boolean verify(byte[] sig) {
|
||||
byte[] r;
|
||||
byte[] s;
|
||||
try {
|
||||
Buffer sigbuf = new Buffer.PlainBuffer(sig);
|
||||
final String algo = new String(sigbuf.readBytes());
|
||||
if (!keyTypeName.equals(algo)) {
|
||||
throw new SSHRuntimeException(String.format("Signature :: " + keyTypeName + " expected, got %s", algo));
|
||||
}
|
||||
final int rsLen = sigbuf.readUInt32AsInt();
|
||||
if (sigbuf.available() != rsLen) {
|
||||
throw new SSHRuntimeException("Invalid key length");
|
||||
}
|
||||
r = sigbuf.readBytes();
|
||||
s = sigbuf.readBytes();
|
||||
} catch (Exception e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
return signature.verify(asnEncode(r, s));
|
||||
byte[] sigBlob = extractSig(sig, keyTypeName);
|
||||
return signature.verify(asnEncode(sigBlob));
|
||||
} catch (SignatureException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
} catch (IOException e) {
|
||||
@@ -135,29 +117,19 @@ public class SignatureECDSA extends AbstractSignature {
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] asnEncode(byte[] r, byte[] s) throws IOException {
|
||||
int rLen = r.length;
|
||||
int sLen = s.length;
|
||||
|
||||
/*
|
||||
* We can't have the high bit set, so add an extra zero at the beginning
|
||||
* if so.
|
||||
*/
|
||||
if ((r[0] & 0x80) != 0) {
|
||||
rLen++;
|
||||
}
|
||||
if ((s[0] & 0x80) != 0) {
|
||||
sLen++;
|
||||
}
|
||||
|
||||
/* Calculate total output length */
|
||||
int length = 6 + rLen + sLen;
|
||||
/**
|
||||
* Encodes the signature as a DER sequence (ASN.1 format).
|
||||
*/
|
||||
private byte[] asnEncode(byte[] sigBlob) throws IOException {
|
||||
Buffer.PlainBuffer sigbuf = new Buffer.PlainBuffer(sigBlob);
|
||||
byte[] r = sigbuf.readBytes();
|
||||
byte[] s = sigbuf.readBytes();
|
||||
|
||||
ASN1EncodableVector vector = new ASN1EncodableVector();
|
||||
vector.add(new ASN1Integer(r));
|
||||
vector.add(new ASN1Integer(s));
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ASN1OutputStream asnOS = new ASN1OutputStream(baos);
|
||||
|
||||
asnOS.writeObject(new DERSequence(vector));
|
||||
|
||||
@@ -51,7 +51,7 @@ public class SignatureRSA
|
||||
|
||||
@Override
|
||||
public boolean verify(byte[] sig) {
|
||||
sig = extractSig(sig);
|
||||
sig = extractSig(sig, "ssh-rsa");
|
||||
try {
|
||||
return signature.verify(sig);
|
||||
} catch (SignatureException e) {
|
||||
|
||||
@@ -44,6 +44,7 @@ abstract class Converter {
|
||||
protected int cipherSize = 8;
|
||||
protected long seq = -1;
|
||||
protected boolean authed;
|
||||
protected boolean etm;
|
||||
|
||||
long getSequenceNumber() {
|
||||
return seq;
|
||||
@@ -56,6 +57,7 @@ abstract class Converter {
|
||||
if (compression != null)
|
||||
compression.init(getCompressionType());
|
||||
this.cipherSize = cipher.getIVSize();
|
||||
this.etm = mac.isEtm();
|
||||
}
|
||||
|
||||
void setAuthenticated() {
|
||||
|
||||
@@ -21,7 +21,9 @@ import net.schmizz.sshj.transport.compression.Compression;
|
||||
import net.schmizz.sshj.transport.mac.MAC;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/** Decodes packets from the SSH binary protocol per the current algorithms. */
|
||||
/**
|
||||
* Decodes packets from the SSH binary protocol per the current algorithms.
|
||||
*/
|
||||
final class Decoder
|
||||
extends Converter {
|
||||
|
||||
@@ -29,16 +31,26 @@ final class Decoder
|
||||
|
||||
private final Logger log;
|
||||
|
||||
/** What we pass decoded packets to */
|
||||
/**
|
||||
* What we pass decoded packets to
|
||||
*/
|
||||
private final SSHPacketHandler packetHandler;
|
||||
/** Buffer where as-yet undecoded data lives */
|
||||
/**
|
||||
* Buffer where as-yet undecoded data lives
|
||||
*/
|
||||
private final SSHPacket inputBuffer = new SSHPacket();
|
||||
/** Used in case compression is active to store the uncompressed data */
|
||||
/**
|
||||
* Used in case compression is active to store the uncompressed data
|
||||
*/
|
||||
private final SSHPacket uncompressBuffer = new SSHPacket();
|
||||
/** MAC result is stored here */
|
||||
/**
|
||||
* MAC result is stored here
|
||||
*/
|
||||
private byte[] macResult;
|
||||
|
||||
/** -1 if packet length not yet been decoded, else the packet length */
|
||||
/**
|
||||
* -1 if packet length not yet been decoded, else the packet length
|
||||
*/
|
||||
private int packetLength = -1;
|
||||
|
||||
/**
|
||||
@@ -60,53 +72,97 @@ final class Decoder
|
||||
*/
|
||||
private int decode()
|
||||
throws SSHException {
|
||||
|
||||
if (etm) {
|
||||
return decodeEtm();
|
||||
} else {
|
||||
return decodeMte();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode an Encrypt-Then-Mac packet.
|
||||
*/
|
||||
private int decodeEtm() throws SSHException {
|
||||
int bytesNeeded;
|
||||
while (true) {
|
||||
if (packetLength == -1) {
|
||||
assert inputBuffer.rpos() == 0 : "buffer cleared";
|
||||
bytesNeeded = 4 - inputBuffer.available();
|
||||
if (bytesNeeded <= 0) {
|
||||
// In Encrypt-Then-Mac, the packetlength is sent unencrypted.
|
||||
packetLength = inputBuffer.readUInt32AsInt();
|
||||
checkPacketLength(packetLength);
|
||||
} else {
|
||||
// Needs more data
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
assert inputBuffer.rpos() == 4 : "packet length read";
|
||||
bytesNeeded = packetLength + mac.getBlockSize() - inputBuffer.available();
|
||||
if (bytesNeeded <= 0) {
|
||||
seq = seq + 1 & 0xffffffffL;
|
||||
checkMAC(inputBuffer.array());
|
||||
decryptBuffer(4, packetLength);
|
||||
inputBuffer.wpos(packetLength + 4 - inputBuffer.readByte());
|
||||
final SSHPacket plain = usingCompression() ? decompressed() : inputBuffer;
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Received packet #{}: {}", seq, plain.printHex());
|
||||
}
|
||||
packetHandler.handle(plain.readMessageID(), plain); // Process the decoded packet
|
||||
inputBuffer.clear();
|
||||
packetLength = -1;
|
||||
} else {
|
||||
// Needs more data
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return bytesNeeded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a Mac-Then-Encrypt packet
|
||||
* @return
|
||||
* @throws SSHException
|
||||
*/
|
||||
private int decodeMte() throws SSHException {
|
||||
int need;
|
||||
|
||||
/* Decoding loop */
|
||||
for (; ; )
|
||||
|
||||
if (packetLength == -1) // Waiting for beginning of packet
|
||||
{
|
||||
|
||||
if (packetLength == -1) { // Waiting for beginning of packet
|
||||
assert inputBuffer.rpos() == 0 : "buffer cleared";
|
||||
|
||||
need = cipherSize - inputBuffer.available();
|
||||
if (need <= 0)
|
||||
if (need <= 0) {
|
||||
packetLength = decryptLength();
|
||||
else
|
||||
} else {
|
||||
// Need more data
|
||||
break;
|
||||
|
||||
}
|
||||
} else {
|
||||
|
||||
assert inputBuffer.rpos() == 4 : "packet length read";
|
||||
|
||||
need = packetLength + (mac != null ? mac.getBlockSize() : 0) - inputBuffer.available();
|
||||
if (need <= 0) {
|
||||
|
||||
decryptPayload(inputBuffer.array());
|
||||
|
||||
decryptBuffer(cipherSize, packetLength + 4 - cipherSize); // Decrypt the rest of the payload
|
||||
seq = seq + 1 & 0xffffffffL;
|
||||
|
||||
if (mac != null)
|
||||
if (mac != null) {
|
||||
checkMAC(inputBuffer.array());
|
||||
|
||||
}
|
||||
// Exclude the padding & MAC
|
||||
inputBuffer.wpos(packetLength + 4 - inputBuffer.readByte());
|
||||
|
||||
final SSHPacket plain = usingCompression() ? decompressed() : inputBuffer;
|
||||
|
||||
if (log.isTraceEnabled())
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("Received packet #{}: {}", seq, plain.printHex());
|
||||
|
||||
}
|
||||
packetHandler.handle(plain.readMessageID(), plain); // Process the decoded packet
|
||||
|
||||
inputBuffer.clear();
|
||||
packetLength = -1;
|
||||
|
||||
} else
|
||||
} else {
|
||||
// Need more data
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return need;
|
||||
@@ -118,8 +174,9 @@ final class Decoder
|
||||
mac.update(data, 0, packetLength + 4); // packetLength+4 = entire packet w/o mac
|
||||
mac.doFinal(macResult, 0); // compute
|
||||
// Check against the received MAC
|
||||
if (!ByteArrayUtils.equals(macResult, 0, data, packetLength + 4, mac.getBlockSize()))
|
||||
if (!ByteArrayUtils.equals(macResult, 0, data, packetLength + 4, mac.getBlockSize())) {
|
||||
throw new TransportException(DisconnectReason.MAC_ERROR, "MAC Error");
|
||||
}
|
||||
}
|
||||
|
||||
private SSHPacket decompressed()
|
||||
@@ -131,7 +188,7 @@ final class Decoder
|
||||
|
||||
private int decryptLength()
|
||||
throws TransportException {
|
||||
cipher.update(inputBuffer.array(), 0, cipherSize);
|
||||
decryptBuffer(0, cipherSize);
|
||||
|
||||
final int len; // Read packet length
|
||||
try {
|
||||
@@ -140,22 +197,26 @@ final class Decoder
|
||||
throw new TransportException(be);
|
||||
}
|
||||
|
||||
if (isInvalidPacketLength(len)) { // Check packet length validity
|
||||
log.error("Error decoding packet (invalid length) {}", inputBuffer.printHex());
|
||||
throw new TransportException(DisconnectReason.PROTOCOL_ERROR, "invalid packet length: " + len);
|
||||
}
|
||||
checkPacketLength(len);
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
private static boolean isInvalidPacketLength(int len) {
|
||||
return len < 5 || len > MAX_PACKET_LEN;
|
||||
private void decryptBuffer(int offset, int length) {
|
||||
cipher.update(inputBuffer.array(), offset, length);
|
||||
}
|
||||
|
||||
private void decryptPayload(final byte[] data) {
|
||||
cipher.update(data, cipherSize, packetLength + 4 - cipherSize);
|
||||
private void checkPacketLength(int len) throws TransportException {
|
||||
if (len < 5 || len > MAX_PACKET_LEN) { // Check packet length validity
|
||||
log.error("Error decoding packet (invalid length) {}", inputBuffer.printHex());
|
||||
throw new TransportException(DisconnectReason.PROTOCOL_ERROR, "invalid packet length: " + len);
|
||||
}
|
||||
}
|
||||
|
||||
// private void decryptPayload(final byte[] data, int offset, int length) {
|
||||
// cipher.update(data, cipherSize, packetLength + 4 - cipherSize);
|
||||
// }
|
||||
|
||||
/**
|
||||
* Adds {@code len} bytes from {@code b} to the decoder buffer. When a packet has been successfully decoded, hooks
|
||||
* in to {@link SSHPacketHandler#handle} of the {@link SSHPacketHandler} this decoder was initialized with.
|
||||
|
||||
@@ -62,39 +62,63 @@ final class Encoder
|
||||
long encode(SSHPacket buffer) {
|
||||
encodeLock.lock();
|
||||
try {
|
||||
if (log.isTraceEnabled())
|
||||
log.trace("Encoding packet #{}: {}", seq, buffer.printHex());
|
||||
if (log.isTraceEnabled()) {
|
||||
// Add +1 to seq as we log before actually incrementing the sequence.
|
||||
log.trace("Encoding packet #{}: {}", seq + 1, buffer.printHex());
|
||||
}
|
||||
|
||||
if (usingCompression())
|
||||
if (usingCompression()) {
|
||||
compress(buffer);
|
||||
}
|
||||
|
||||
final int payloadSize = buffer.available();
|
||||
int lengthWithoutPadding;
|
||||
if (etm) {
|
||||
// in Encrypt-Then-Mac mode, the length field is not encrypted, so we should keep it out of the
|
||||
// padding length calculation
|
||||
lengthWithoutPadding = 1 + payloadSize; // padLength (1 byte) + payload
|
||||
} else {
|
||||
lengthWithoutPadding = 4 + 1 + payloadSize; // packetLength (4 bytes) + padLength (1 byte) + payload
|
||||
}
|
||||
|
||||
// Compute padding length
|
||||
int padLen = -(payloadSize + 5) & cipherSize - 1;
|
||||
if (padLen < cipherSize)
|
||||
int padLen = cipherSize - (lengthWithoutPadding % cipherSize);
|
||||
if (padLen < 4) {
|
||||
padLen += cipherSize;
|
||||
}
|
||||
|
||||
final int startOfPacket = buffer.rpos() - 5;
|
||||
final int packetLen = payloadSize + 1 + padLen;
|
||||
int packetLen = 1 + payloadSize + padLen; // packetLength = padLen (1 byte) + payload + padding
|
||||
|
||||
if (packetLen < 16) {
|
||||
padLen += cipherSize;
|
||||
packetLen = 1 + payloadSize + padLen;
|
||||
}
|
||||
|
||||
final int endOfPadding = startOfPacket + 4 + packetLen;
|
||||
|
||||
// Put packet header
|
||||
buffer.wpos(startOfPacket);
|
||||
buffer.putUInt32(packetLen);
|
||||
buffer.putByte((byte) padLen);
|
||||
|
||||
// Now wpos will mark end of padding
|
||||
buffer.wpos(startOfPacket + 5 + payloadSize + padLen);
|
||||
buffer.wpos(endOfPadding);
|
||||
|
||||
// Fill padding
|
||||
prng.fill(buffer.array(), buffer.wpos() - padLen, padLen);
|
||||
prng.fill(buffer.array(), endOfPadding - padLen, padLen);
|
||||
|
||||
seq = seq + 1 & 0xffffffffL;
|
||||
|
||||
if (mac != null)
|
||||
putMAC(buffer, startOfPacket, buffer.wpos());
|
||||
|
||||
cipher.update(buffer.array(), startOfPacket, 4 + packetLen);
|
||||
if (etm) {
|
||||
cipher.update(buffer.array(), startOfPacket + 4, packetLen);
|
||||
putMAC(buffer, startOfPacket, endOfPadding);
|
||||
} else {
|
||||
if (mac != null) {
|
||||
putMAC(buffer, startOfPacket, endOfPadding);
|
||||
}
|
||||
|
||||
cipher.update(buffer.array(), startOfPacket, 4 + packetLen);
|
||||
}
|
||||
buffer.rpos(startOfPacket); // Make ready-to-read
|
||||
|
||||
return seq;
|
||||
|
||||
@@ -197,6 +197,12 @@ final class KeyExchanger
|
||||
if (hkv.verify(transport.getRemoteHost(), transport.getRemotePort(), key))
|
||||
return;
|
||||
}
|
||||
log.error("Disconnecting because none of the configured Host key verifiers ({}) could verify '{}' host key with fingerprint {} for {}:{}",
|
||||
hostVerifiers,
|
||||
KeyType.fromKey(key),
|
||||
SecurityUtils.getFingerprint(key),
|
||||
transport.getRemoteHost(),
|
||||
transport.getRemotePort());
|
||||
|
||||
throw new TransportException(DisconnectReason.HOST_KEY_NOT_VERIFIABLE,
|
||||
"Could not verify `" + KeyType.fromKey(key)
|
||||
|
||||
@@ -60,10 +60,8 @@ public final class Reader
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
//noinspection StatementWithEmptyBody
|
||||
if (isInterrupted()) {
|
||||
// We are meant to shut up and draw to a close if interrupted
|
||||
} else {
|
||||
// We are meant to shut up and draw to a close if interrupted
|
||||
if (!isInterrupted()) {
|
||||
trans.die(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,14 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.cipher;
|
||||
|
||||
/** {@code aes128-cbc} cipher */
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
|
||||
/**
|
||||
* {@code aes128-cbc} cipher
|
||||
*
|
||||
* @deprecated Use {@link BlockCiphers#AES128CBC()}
|
||||
*/
|
||||
@Deprecated
|
||||
public class AES128CBC
|
||||
extends BlockCipher {
|
||||
|
||||
@@ -32,6 +39,11 @@ public class AES128CBC
|
||||
public String getName() {
|
||||
return "aes128-cbc";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName();
|
||||
}
|
||||
}
|
||||
|
||||
public AES128CBC() {
|
||||
|
||||
@@ -15,11 +15,18 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.cipher;
|
||||
|
||||
/** {@code aes128-ctr} cipher */
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
|
||||
/**
|
||||
* {@code aes128-ctr} cipher
|
||||
*
|
||||
* @deprecated Use {@link BlockCiphers#AES128CTR()}
|
||||
*/
|
||||
@Deprecated
|
||||
public class AES128CTR
|
||||
extends BlockCipher {
|
||||
|
||||
/** Named factory for AES128CBC Cipher */
|
||||
/** Named factory for AES128CTR Cipher */
|
||||
public static class Factory
|
||||
implements net.schmizz.sshj.common.Factory.Named<Cipher> {
|
||||
|
||||
@@ -32,6 +39,11 @@ public class AES128CTR
|
||||
public String getName() {
|
||||
return "aes128-ctr";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName();
|
||||
}
|
||||
}
|
||||
|
||||
public AES128CTR() {
|
||||
|
||||
@@ -15,7 +15,14 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.cipher;
|
||||
|
||||
/** {@code aes192-cbc} cipher */
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
|
||||
/**
|
||||
* {@code aes192-cbc} cipher
|
||||
*
|
||||
* @deprecated Use {@link BlockCiphers#AES192CBC()}
|
||||
*/
|
||||
@Deprecated
|
||||
public class AES192CBC
|
||||
extends BlockCipher {
|
||||
|
||||
@@ -32,6 +39,11 @@ public class AES192CBC
|
||||
public String getName() {
|
||||
return "aes192-cbc";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName();
|
||||
}
|
||||
}
|
||||
|
||||
public AES192CBC() {
|
||||
|
||||
@@ -15,7 +15,14 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.cipher;
|
||||
|
||||
/** {@code aes192-ctr} cipher */
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
|
||||
/**
|
||||
* {@code aes192-ctr} cipher
|
||||
*
|
||||
* @deprecated Use {@link BlockCiphers#AES192CTR()}
|
||||
*/
|
||||
@Deprecated
|
||||
public class AES192CTR
|
||||
extends BlockCipher {
|
||||
|
||||
@@ -32,6 +39,11 @@ public class AES192CTR
|
||||
public String getName() {
|
||||
return "aes192-ctr";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName();
|
||||
}
|
||||
}
|
||||
|
||||
public AES192CTR() {
|
||||
|
||||
@@ -15,7 +15,14 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.cipher;
|
||||
|
||||
/** {@code aes256-ctr} cipher */
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
|
||||
/**
|
||||
* {@code aes256-cbc} cipher
|
||||
*
|
||||
* @deprecated Use {@link BlockCiphers#AES256CBC()}
|
||||
*/
|
||||
@Deprecated
|
||||
public class AES256CBC
|
||||
extends BlockCipher {
|
||||
|
||||
@@ -32,6 +39,11 @@ public class AES256CBC
|
||||
public String getName() {
|
||||
return "aes256-cbc";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName();
|
||||
}
|
||||
}
|
||||
|
||||
public AES256CBC() {
|
||||
|
||||
@@ -15,11 +15,18 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.cipher;
|
||||
|
||||
/** {@code aes256-ctr} cipher */
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
|
||||
/**
|
||||
* {@code aes256-ctr} cipher
|
||||
*
|
||||
* @deprecated Use {@link BlockCiphers#AES256CTR()}
|
||||
*/
|
||||
@Deprecated
|
||||
public class AES256CTR
|
||||
extends BlockCipher {
|
||||
|
||||
/** Named factory for AES256CBC Cipher */
|
||||
/** Named factory for AES256CTR Cipher */
|
||||
public static class Factory
|
||||
implements net.schmizz.sshj.common.Factory.Named<Cipher> {
|
||||
|
||||
@@ -32,6 +39,11 @@ public class AES256CTR
|
||||
public String getName() {
|
||||
return "aes256-ctr";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName();
|
||||
}
|
||||
}
|
||||
|
||||
public AES256CTR() {
|
||||
|
||||
@@ -15,7 +15,14 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.cipher;
|
||||
|
||||
/** {@code blowfish-ctr} cipher */
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
|
||||
/**
|
||||
* {@code blowfish-bcb} cipher
|
||||
*
|
||||
* @deprecated Use {@link BlockCiphers#BlowfishCBC()}
|
||||
*/
|
||||
@Deprecated
|
||||
public class BlowfishCBC
|
||||
extends BlockCipher {
|
||||
|
||||
@@ -32,6 +39,11 @@ public class BlowfishCBC
|
||||
public String getName() {
|
||||
return "blowfish-cbc";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName();
|
||||
}
|
||||
}
|
||||
|
||||
public BlowfishCBC() {
|
||||
|
||||
@@ -15,7 +15,14 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.cipher;
|
||||
|
||||
/** {@code 3des-cbc} cipher */
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
|
||||
/**
|
||||
* {@code 3des-cbc} cipher
|
||||
*
|
||||
* @deprecated Use {@link BlockCiphers#TripleDESCBC()}
|
||||
*/
|
||||
@Deprecated
|
||||
public class TripleDESCBC
|
||||
extends BlockCipher {
|
||||
|
||||
@@ -32,6 +39,11 @@ public class TripleDESCBC
|
||||
public String getName() {
|
||||
return "3des-cbc";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName();
|
||||
}
|
||||
}
|
||||
|
||||
public TripleDESCBC() {
|
||||
|
||||
@@ -80,7 +80,7 @@ public abstract class AbstractDHG extends AbstractDH
|
||||
|
||||
Signature signature = Factory.Named.Util.create(trans.getConfig().getSignatureFactories(),
|
||||
KeyType.fromKey(hostKey).toString());
|
||||
signature.init(hostKey, null);
|
||||
signature.initVerify(hostKey);
|
||||
signature.update(H, 0, H.length);
|
||||
if (!signature.verify(sig))
|
||||
throw new TransportException(DisconnectReason.KEY_EXCHANGE_FAILED,
|
||||
|
||||
@@ -86,7 +86,7 @@ public abstract class AbstractDHGex extends AbstractDH {
|
||||
H = digest.digest();
|
||||
Signature signature = Factory.Named.Util.create(trans.getConfig().getSignatureFactories(),
|
||||
KeyType.fromKey(hostKey).toString());
|
||||
signature.init(hostKey, null);
|
||||
signature.initVerify(hostKey);
|
||||
signature.update(H, 0, H.length);
|
||||
if (!signature.verify(sig))
|
||||
throw new TransportException(DisconnectReason.KEY_EXCHANGE_FAILED,
|
||||
|
||||
@@ -15,16 +15,16 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.kex;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.spec.AlgorithmParameterSpec;
|
||||
import java.util.Arrays;
|
||||
import net.schmizz.sshj.common.Factory;
|
||||
import net.schmizz.sshj.transport.random.Random;
|
||||
import org.bouncycastle.asn1.x9.X9ECParameters;
|
||||
import org.bouncycastle.crypto.ec.CustomNamedCurves;
|
||||
import org.bouncycastle.jce.spec.ECParameterSpec;
|
||||
|
||||
import net.schmizz.sshj.common.Factory;
|
||||
import net.schmizz.sshj.transport.random.Random;
|
||||
import java.math.BigInteger;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.spec.AlgorithmParameterSpec;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class Curve25519DH extends DHBase {
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ import java.security.GeneralSecurityException;
|
||||
|
||||
public class Curve25519SHA256 extends AbstractDHG {
|
||||
/** Named factory for Curve25519SHA256 key exchange */
|
||||
public static class Factory
|
||||
public static class FactoryLibSsh
|
||||
implements net.schmizz.sshj.common.Factory.Named<KeyExchange> {
|
||||
|
||||
@Override
|
||||
@@ -35,6 +35,21 @@ public class Curve25519SHA256 extends AbstractDHG {
|
||||
}
|
||||
}
|
||||
|
||||
/** Named factory for Curve25519SHA256 key exchange */
|
||||
public static class Factory
|
||||
implements net.schmizz.sshj.common.Factory.Named<KeyExchange> {
|
||||
|
||||
@Override
|
||||
public KeyExchange create() {
|
||||
return new Curve25519SHA256();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "curve25519-sha256";
|
||||
}
|
||||
}
|
||||
|
||||
public Curve25519SHA256() {
|
||||
super(new Curve25519DH(), new SHA256());
|
||||
}
|
||||
|
||||
@@ -30,12 +30,18 @@ public class BaseMAC
|
||||
private final int defbsize;
|
||||
private final int bsize;
|
||||
private final byte[] tmp;
|
||||
private final boolean etm;
|
||||
private javax.crypto.Mac mac;
|
||||
|
||||
public BaseMAC(String algorithm, int bsize, int defbsize) {
|
||||
this(algorithm, bsize, defbsize, false);
|
||||
}
|
||||
|
||||
public BaseMAC(String algorithm, int bsize, int defbsize, boolean isEtm) {
|
||||
this.algorithm = algorithm;
|
||||
this.bsize = bsize;
|
||||
this.defbsize = defbsize;
|
||||
this.etm = isEtm;
|
||||
tmp = new byte[defbsize];
|
||||
}
|
||||
|
||||
@@ -112,4 +118,8 @@ public class BaseMAC
|
||||
update(tmp, 0, 4);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEtm() {
|
||||
return etm;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,12 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.mac;
|
||||
|
||||
/** HMAC-MD5 <code>MAC</code>. */
|
||||
import com.hierynomus.sshj.transport.mac.Macs;
|
||||
|
||||
/** HMAC-MD5 <code>MAC</code>.
|
||||
*
|
||||
* @deprecated Use {@link Macs#HMACMD5()}
|
||||
*/
|
||||
public class HMACMD5
|
||||
extends BaseMAC {
|
||||
|
||||
|
||||
@@ -15,7 +15,12 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.mac;
|
||||
|
||||
/** HMAC-MD5-96 <code>MAC</code> */
|
||||
import com.hierynomus.sshj.transport.mac.Macs;
|
||||
|
||||
/** HMAC-MD5-96 <code>MAC</code>
|
||||
*
|
||||
* @deprecated Use {@link Macs#HMACMD596()}
|
||||
*/
|
||||
public class HMACMD596
|
||||
extends BaseMAC {
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright (C)2009 - SSHJ Contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package net.schmizz.sshj.transport.mac;
|
||||
|
||||
import com.hierynomus.sshj.transport.mac.Macs;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link Macs#HMACRIPEMD160()}
|
||||
*/
|
||||
public class HMACRIPEMD160 extends BaseMAC {
|
||||
/** Named factory for the HMAC-RIPEMD160 <code>MAC</code> */
|
||||
public static class Factory
|
||||
implements net.schmizz.sshj.common.Factory.Named<MAC> {
|
||||
|
||||
@Override
|
||||
public MAC create() {
|
||||
return new HMACRIPEMD160();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "hmac-ripemd160";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public HMACRIPEMD160() {
|
||||
super("HMACRIPEMD160", 20, 20);
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,12 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.mac;
|
||||
|
||||
/** HMAC-SHA1 <code>MAC</code> */
|
||||
import com.hierynomus.sshj.transport.mac.Macs;
|
||||
|
||||
/** HMAC-SHA1 <code>MAC</code>
|
||||
*
|
||||
* @deprecated Use {@link Macs#HMACSHA1()}
|
||||
*/
|
||||
public class HMACSHA1
|
||||
extends BaseMAC {
|
||||
|
||||
|
||||
@@ -15,7 +15,12 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.mac;
|
||||
|
||||
/** HMAC-SHA1-96 <code>MAC</code> */
|
||||
import com.hierynomus.sshj.transport.mac.Macs;
|
||||
|
||||
/** HMAC-SHA1-96 <code>MAC</code>
|
||||
*
|
||||
* @deprecated Use {@link Macs#HMACSHA196()}
|
||||
*/
|
||||
public class HMACSHA196
|
||||
extends BaseMAC {
|
||||
|
||||
|
||||
@@ -15,7 +15,12 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.mac;
|
||||
|
||||
/** HMAC-SHA1 <code>MAC</code> */
|
||||
import com.hierynomus.sshj.transport.mac.Macs;
|
||||
|
||||
/** HMAC-SHA1 <code>MAC</code>
|
||||
*
|
||||
* @deprecated Use {@link Macs#HMACSHA2256()}
|
||||
*/
|
||||
public class HMACSHA2256
|
||||
extends BaseMAC {
|
||||
|
||||
|
||||
@@ -15,7 +15,12 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.mac;
|
||||
|
||||
/** HMAC-SHA1 <code>MAC</code> */
|
||||
import com.hierynomus.sshj.transport.mac.Macs;
|
||||
|
||||
/** HMAC-SHA1 <code>MAC</code>
|
||||
*
|
||||
* @deprecated Use {@link Macs#HMACSHA2512()}
|
||||
*/
|
||||
public class HMACSHA2512
|
||||
extends BaseMAC {
|
||||
|
||||
|
||||
@@ -15,7 +15,9 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.mac;
|
||||
|
||||
/** Message Authentication Code for use in SSH. It usually wraps a javax.crypto.Mac class. */
|
||||
/**
|
||||
* Message Authentication Code for use in SSH. It usually wraps a javax.crypto.Mac class.
|
||||
*/
|
||||
public interface MAC {
|
||||
|
||||
byte[] doFinal();
|
||||
@@ -33,4 +35,40 @@ public interface MAC {
|
||||
void update(byte[] foo, int start, int len);
|
||||
|
||||
void update(long foo);
|
||||
|
||||
/**
|
||||
* Indicates that an Encrypt-Then-Mac algorithm was selected.
|
||||
* <p>
|
||||
* This has the following implementation details.
|
||||
* 1.5 transport: Protocol 2 Encrypt-then-MAC MAC algorithms
|
||||
* <p>
|
||||
* OpenSSH supports MAC algorithms, whose names contain "-etm", that
|
||||
* perform the calculations in a different order to that defined in RFC
|
||||
* 4253. These variants use the so-called "encrypt then MAC" ordering,
|
||||
* calculating the MAC over the packet ciphertext rather than the
|
||||
* plaintext. This ordering closes a security flaw in the SSH transport
|
||||
* protocol, where decryption of unauthenticated ciphertext provided a
|
||||
* "decryption oracle" that could, in conjunction with cipher flaws, reveal
|
||||
* session plaintext.
|
||||
* <p>
|
||||
* Specifically, the "-etm" MAC algorithms modify the transport protocol
|
||||
* to calculate the MAC over the packet ciphertext and to send the packet
|
||||
* length unencrypted. This is necessary for the transport to obtain the
|
||||
* length of the packet and location of the MAC tag so that it may be
|
||||
* verified without decrypting unauthenticated data.
|
||||
* <p>
|
||||
* As such, the MAC covers:
|
||||
* <p>
|
||||
* mac = MAC(key, sequence_number || packet_length || encrypted_packet)
|
||||
* <p>
|
||||
* where "packet_length" is encoded as a uint32 and "encrypted_packet"
|
||||
* contains:
|
||||
* <p>
|
||||
* byte padding_length
|
||||
* byte[n1] payload; n1 = packet_length - padding_length - 1
|
||||
* byte[n2] random padding; n2 = padding_length
|
||||
*
|
||||
* @return Whether the MAC algorithm is an Encrypt-Then-Mac algorithm
|
||||
*/
|
||||
boolean isEtm();
|
||||
}
|
||||
|
||||
@@ -15,10 +15,11 @@
|
||||
*/
|
||||
package net.schmizz.sshj.transport.random;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
|
||||
/** A {@link Random} implementation using the built-in {@link SecureRandom} PRNG. */
|
||||
public class JCERandom
|
||||
implements Random {
|
||||
|
||||
@@ -41,7 +41,7 @@ public class ConsoleKnownHostsVerifier
|
||||
protected boolean hostKeyUnverifiableAction(String hostname, PublicKey key) {
|
||||
final KeyType type = KeyType.fromKey(key);
|
||||
console.printf("The authenticity of host '%s' can't be established.\n" +
|
||||
"%s key fingerprint is %s.\n", hostname, type, SecurityUtils.getFingerprint(key));
|
||||
"%s key fingerprint is %s.\n", hostname, type, SecurityUtils.getFingerprint(key));
|
||||
String response = console.readLine("Are you sure you want to continue connecting (yes/no)? ");
|
||||
while (!(response.equalsIgnoreCase(YES) || response.equalsIgnoreCase(NO))) {
|
||||
response = console.readLine("Please explicitly enter yes/no: ");
|
||||
@@ -60,7 +60,7 @@ public class ConsoleKnownHostsVerifier
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean hostKeyChangedAction(KnownHostEntry entry, String hostname, PublicKey key) {
|
||||
protected boolean hostKeyChangedAction(String hostname, PublicKey key) {
|
||||
final KeyType type = KeyType.fromKey(key);
|
||||
final String fp = SecurityUtils.getFingerprint(key);
|
||||
final String path = getFile().getAbsolutePath();
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Copyright (C)2009 - SSHJ Contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package net.schmizz.sshj.transport.verification;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Arrays;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import net.schmizz.sshj.common.Base64;
|
||||
import net.schmizz.sshj.common.Buffer;
|
||||
import net.schmizz.sshj.common.SSHRuntimeException;
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
|
||||
public class FingerprintVerifier implements HostKeyVerifier {
|
||||
private static final Pattern MD5_FINGERPRINT_PATTERN = Pattern.compile("[0-9a-f]{2}+(:[0-9a-f]{2}+){15}+");
|
||||
/**
|
||||
* Valid examples:
|
||||
*
|
||||
* <ul>
|
||||
* <li><code>4b:69:6c:72:6f:79:20:77:61:73:20:68:65:72:65:21</code></li>
|
||||
* <li><code>MD5:4b:69:6c:72:6f:79:20:77:61:73:20:68:65:72:65:21</code></li>
|
||||
* <li><code>SHA1:FghNYu1l/HyE/qWbdQ2mkxrd0rU</code></li>
|
||||
* <li><code>SHA1:FghNYu1l/HyE/qWbdQ2mkxrd0rU=</code></li>
|
||||
* <li><code>SHA256:l/SjyCoKP8jAx3d8k8MWH+UZG0gcuIR7TQRE/A3faQo</code></li>
|
||||
* <li><code>SHA256:l/SjyCoKP8jAx3d8k8MWH+UZG0gcuIR7TQRE/A3faQo=</code></li>
|
||||
* </ul>
|
||||
*
|
||||
*
|
||||
* @param fingerprint of an SSH fingerprint in MD5 (hex), SHA-1 (base64) or SHA-256(base64) format
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static HostKeyVerifier getInstance(String fingerprint) {
|
||||
|
||||
try {
|
||||
if (fingerprint.startsWith("SHA1:")) {
|
||||
return new FingerprintVerifier("SHA-1", fingerprint.substring(5));
|
||||
}
|
||||
|
||||
if (fingerprint.startsWith("SHA256:")) {
|
||||
return new FingerprintVerifier("SHA-256", fingerprint.substring(7));
|
||||
}
|
||||
|
||||
final String md5;
|
||||
if (fingerprint.startsWith("MD5:")) {
|
||||
md5 = fingerprint.substring(4); // remove the MD5: prefix
|
||||
} else {
|
||||
md5 = fingerprint;
|
||||
}
|
||||
|
||||
if (!MD5_FINGERPRINT_PATTERN.matcher(md5).matches()) {
|
||||
throw new SSHRuntimeException("Invalid MD5 fingerprint: " + fingerprint);
|
||||
}
|
||||
|
||||
// Use the old default fingerprint verifier for md5 fingerprints
|
||||
return (new HostKeyVerifier() {
|
||||
@Override
|
||||
public boolean verify(String h, int p, PublicKey k) {
|
||||
return SecurityUtils.getFingerprint(k).equals(md5);
|
||||
}
|
||||
});
|
||||
} catch (SSHRuntimeException e) {
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private final String digestAlgorithm;
|
||||
private final byte[] fingerprintData;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param digestAlgorithm
|
||||
* the used digest algorithm
|
||||
* @param base64Fingerprint
|
||||
* base64 encoded fingerprint data
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
private FingerprintVerifier(String digestAlgorithm, String base64Fingerprint) throws IOException {
|
||||
this.digestAlgorithm = digestAlgorithm;
|
||||
|
||||
// if the length is not padded with "=" chars at the end so that it is divisible by 4 the SSHJ Base64 implementation does not work correctly
|
||||
StringBuilder base64FingerprintBuilder = new StringBuilder(base64Fingerprint);
|
||||
while (base64FingerprintBuilder.length() % 4 != 0) {
|
||||
base64FingerprintBuilder.append("=");
|
||||
}
|
||||
fingerprintData = Base64.decode(base64FingerprintBuilder.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(String hostname, int port, PublicKey key) {
|
||||
MessageDigest digest;
|
||||
try {
|
||||
digest = SecurityUtils.getMessageDigest(digestAlgorithm);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new SSHRuntimeException(e);
|
||||
}
|
||||
digest.update(new Buffer.PlainBuffer().putPublicKey(key).getCompactData());
|
||||
|
||||
byte[] digestData = digest.digest();
|
||||
return Arrays.equals(fingerprintData, digestData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "FingerprintVerifier{digestAlgorithm='" + digestAlgorithm + "'}";
|
||||
}
|
||||
}
|
||||
@@ -87,14 +87,23 @@ public class OpenSSHKnownHosts
|
||||
|
||||
final String adjustedHostname = (port != 22) ? "[" + hostname + "]:" + port : hostname;
|
||||
|
||||
boolean foundApplicableHostEntry = false;
|
||||
for (KnownHostEntry e : entries) {
|
||||
try {
|
||||
if (e.appliesTo(type, adjustedHostname))
|
||||
return e.verify(key) || hostKeyChangedAction(e, adjustedHostname, key);
|
||||
if (e.appliesTo(type, adjustedHostname)) {
|
||||
foundApplicableHostEntry = true;
|
||||
if (e.verify(key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
log.error("Error with {}: {}", e, ioe);
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
if (foundApplicableHostEntry) {
|
||||
return hostKeyChangedAction(adjustedHostname, key);
|
||||
}
|
||||
|
||||
return hostKeyUnverifiableAction(adjustedHostname, key);
|
||||
@@ -104,7 +113,7 @@ public class OpenSSHKnownHosts
|
||||
return false;
|
||||
}
|
||||
|
||||
protected boolean hostKeyChangedAction(KnownHostEntry entry, String hostname, PublicKey key) {
|
||||
protected boolean hostKeyChangedAction(String hostname, PublicKey key) {
|
||||
log.warn("Host key for `{}` has changed!", hostname);
|
||||
return false;
|
||||
}
|
||||
@@ -199,7 +208,7 @@ public class OpenSSHKnownHosts
|
||||
}
|
||||
if(split.length < 3) {
|
||||
log.error("Error reading entry `{}`", line);
|
||||
return null;
|
||||
return new BadHostEntry(line);
|
||||
}
|
||||
final String hostnames = split[i++];
|
||||
final String sType = split[i++];
|
||||
@@ -209,7 +218,13 @@ public class OpenSSHKnownHosts
|
||||
|
||||
if (type != KeyType.UNKNOWN) {
|
||||
final String sKey = split[i++];
|
||||
key = new Buffer.PlainBuffer(Base64.decode(sKey)).readPublicKey();
|
||||
try {
|
||||
byte[] keyBytes = Base64.decode(sKey);
|
||||
key = new Buffer.PlainBuffer(keyBytes).readPublicKey();
|
||||
} catch (IOException ioe) {
|
||||
log.warn("Error decoding Base64 key bytes", ioe);
|
||||
return new BadHostEntry(line);
|
||||
}
|
||||
} else if (isBits(sType)) {
|
||||
type = KeyType.RSA;
|
||||
// int bits = Integer.valueOf(sType);
|
||||
@@ -220,11 +235,11 @@ public class OpenSSHKnownHosts
|
||||
key = keyFactory.generatePublic(new RSAPublicKeySpec(n, e));
|
||||
} catch (Exception ex) {
|
||||
log.error("Error reading entry `{}`, could not create key", line, ex);
|
||||
return null;
|
||||
return new BadHostEntry(line);
|
||||
}
|
||||
} else {
|
||||
log.error("Error reading entry `{}`, could not determine type", line);
|
||||
return null;
|
||||
return new BadHostEntry(line);
|
||||
}
|
||||
|
||||
return new HostEntry(marker, hostnames, type, key);
|
||||
@@ -310,7 +325,7 @@ public class OpenSSHKnownHosts
|
||||
protected final PublicKey key;
|
||||
private final KnownHostMatchers.HostMatcher matcher;
|
||||
|
||||
HostEntry(Marker marker, String hostPart, KeyType type, PublicKey key) throws SSHException {
|
||||
public HostEntry(Marker marker, String hostPart, KeyType type, PublicKey key) throws SSHException {
|
||||
this.marker = marker;
|
||||
this.hostPart = hostPart;
|
||||
this.type = type;
|
||||
@@ -340,7 +355,7 @@ public class OpenSSHKnownHosts
|
||||
|
||||
@Override
|
||||
public boolean verify(PublicKey key) throws IOException {
|
||||
return key.equals(this.key) && marker != Marker.REVOKED;
|
||||
return getKeyString(key).equals(getKeyString(this.key)) && marker != Marker.REVOKED;
|
||||
}
|
||||
|
||||
public String getLine() {
|
||||
@@ -350,17 +365,55 @@ public class OpenSSHKnownHosts
|
||||
|
||||
line.append(getHostPart());
|
||||
line.append(" ").append(type.toString());
|
||||
line.append(" ").append(getKeyString());
|
||||
line.append(" ").append(getKeyString(key));
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
private String getKeyString() {
|
||||
final Buffer.PlainBuffer buf = new Buffer.PlainBuffer().putPublicKey(key);
|
||||
private String getKeyString(PublicKey pk) {
|
||||
final Buffer.PlainBuffer buf = new Buffer.PlainBuffer().putPublicKey(pk);
|
||||
return Base64.encodeBytes(buf.array(), buf.rpos(), buf.available());
|
||||
}
|
||||
|
||||
protected String getHostPart() {
|
||||
return hostPart;
|
||||
return hostPart;
|
||||
}
|
||||
}
|
||||
|
||||
public static class BadHostEntry implements KnownHostEntry {
|
||||
private String line;
|
||||
|
||||
public BadHostEntry(String line) {
|
||||
this.line = line;
|
||||
}
|
||||
|
||||
@Override
|
||||
public KeyType getType() {
|
||||
return KeyType.UNKNOWN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFingerprint() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(String host) throws IOException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(KeyType type, String host) throws IOException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(PublicKey key) throws IOException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLine() {
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,4 +440,10 @@ public class OpenSSHKnownHosts
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OpenSSHKnownHosts{khFile='" + khFile + "'}";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
*/
|
||||
package net.schmizz.sshj.userauth.keyprovider;
|
||||
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.userauth.password.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
@@ -22,9 +25,6 @@ import java.security.KeyPair;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.userauth.password.*;
|
||||
|
||||
public abstract class BaseFileKeyProvider implements FileKeyProvider {
|
||||
protected Resource<?> resource;
|
||||
protected PasswordFinder pwdf;
|
||||
|
||||
@@ -15,10 +15,10 @@
|
||||
*/
|
||||
package net.schmizz.sshj.userauth.keyprovider;
|
||||
|
||||
import com.hierynomus.sshj.userauth.keyprovider.OpenSSHKeyV1KeyFile;
|
||||
import net.schmizz.sshj.common.IOUtils;
|
||||
|
||||
import java.io.*;
|
||||
import com.hierynomus.sshj.userauth.keyprovider.OpenSSHKeyV1KeyFile;
|
||||
|
||||
public class KeyProviderUtil {
|
||||
|
||||
@@ -89,7 +89,7 @@ public class KeyProviderUtil {
|
||||
|
||||
private static KeyFormat keyFormatFromHeader(String header, boolean separatePubKey) {
|
||||
if (header.startsWith("-----BEGIN") && header.endsWith("PRIVATE KEY-----")) {
|
||||
if (separatePubKey && header.contains(OpenSSHKeyV1KeyFile.OPENSSH_PRIVATE_KEY)) {
|
||||
if (header.contains(OpenSSHKeyV1KeyFile.OPENSSH_PRIVATE_KEY)) {
|
||||
return KeyFormat.OpenSSHv1;
|
||||
} else if (separatePubKey) {
|
||||
// Can delay asking for password since have unencrypted pubkey
|
||||
|
||||
@@ -75,7 +75,12 @@ public class OpenSSHKeyFile
|
||||
@Override
|
||||
public void init(String privateKey, String publicKey) {
|
||||
if (publicKey != null) {
|
||||
initPubKey(new StringReader(publicKey));
|
||||
try {
|
||||
initPubKey(new StringReader(publicKey));
|
||||
} catch (IOException e) {
|
||||
// let super provide both public & private key
|
||||
log.warn("Error reading public key: {}", e.toString());
|
||||
}
|
||||
}
|
||||
super.init(privateKey, null);
|
||||
}
|
||||
@@ -85,23 +90,18 @@ public class OpenSSHKeyFile
|
||||
*
|
||||
* @param publicKey Public key accessible through a {@code Reader}
|
||||
*/
|
||||
private void initPubKey(Reader publicKey) {
|
||||
private void initPubKey(Reader publicKey) throws IOException {
|
||||
final BufferedReader br = new BufferedReader(publicKey);
|
||||
try {
|
||||
final BufferedReader br = new BufferedReader(publicKey);
|
||||
try {
|
||||
final String keydata = br.readLine();
|
||||
if (keydata != null) {
|
||||
String[] parts = keydata.trim().split(" ");
|
||||
assert parts.length >= 2;
|
||||
type = KeyType.fromString(parts[0]);
|
||||
pubKey = new Buffer.PlainBuffer(Base64.decode(parts[1])).readPublicKey();
|
||||
}
|
||||
} finally {
|
||||
br.close();
|
||||
final String keydata = br.readLine();
|
||||
if (keydata != null) {
|
||||
String[] parts = keydata.trim().split(" ");
|
||||
assert parts.length >= 2;
|
||||
type = KeyType.fromString(parts[0]);
|
||||
pubKey = new Buffer.PlainBuffer(Base64.decode(parts[1])).readPublicKey();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// let super provide both public & private key
|
||||
log.warn("Error reading public key: {}", e.toString());
|
||||
} finally {
|
||||
br.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,15 @@
|
||||
*/
|
||||
package net.schmizz.sshj.userauth.keyprovider;
|
||||
|
||||
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
|
||||
import net.schmizz.sshj.common.Base64;
|
||||
import net.schmizz.sshj.common.ByteArrayUtils;
|
||||
import net.schmizz.sshj.common.IOUtils;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.transport.cipher.*;
|
||||
import net.schmizz.sshj.transport.digest.Digest;
|
||||
import net.schmizz.sshj.transport.digest.MD5;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
@@ -24,14 +33,6 @@ import java.nio.CharBuffer;
|
||||
import java.security.*;
|
||||
import java.security.spec.*;
|
||||
import java.util.Arrays;
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
import net.schmizz.sshj.common.Base64;
|
||||
import net.schmizz.sshj.common.IOUtils;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.transport.cipher.*;
|
||||
import net.schmizz.sshj.transport.digest.Digest;
|
||||
import net.schmizz.sshj.transport.digest.MD5;
|
||||
|
||||
/**
|
||||
* Represents a PKCS5-encoded key file. This is the format typically used by OpenSSH, OpenSSL, Amazon, etc.
|
||||
@@ -116,17 +117,17 @@ public class PKCS5KeyFile extends BaseFileKeyProvider {
|
||||
} else {
|
||||
String algorithm = line.substring(10, ptr);
|
||||
if ("DES-EDE3-CBC".equals(algorithm)) {
|
||||
cipher = new TripleDESCBC();
|
||||
cipher = BlockCiphers.TripleDESCBC().create();
|
||||
} else if ("AES-128-CBC".equals(algorithm)) {
|
||||
cipher = new AES128CBC();
|
||||
cipher = BlockCiphers.AES128CBC().create();
|
||||
} else if ("AES-192-CBC".equals(algorithm)) {
|
||||
cipher = new AES192CBC();
|
||||
cipher = BlockCiphers.AES192CBC().create();
|
||||
} else if ("AES-256-CBC".equals(algorithm)) {
|
||||
cipher = new AES256CBC();
|
||||
cipher = BlockCiphers.AES256CBC().create();
|
||||
} else {
|
||||
throw new FormatException("Not a supported algorithm: " + algorithm);
|
||||
}
|
||||
iv = Arrays.copyOfRange(DatatypeConverter.parseHexBinary(line.substring(ptr + 1)), 0, cipher.getIVSize());
|
||||
iv = Arrays.copyOfRange(ByteArrayUtils.parseHex(line.substring(ptr + 1)), 0, cipher.getIVSize());
|
||||
}
|
||||
} else if (line.length() > 0) {
|
||||
sb.append(line);
|
||||
|
||||
@@ -15,8 +15,9 @@
|
||||
*/
|
||||
package net.schmizz.sshj.userauth.keyprovider;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.KeyPair;
|
||||
import net.schmizz.sshj.common.IOUtils;
|
||||
import net.schmizz.sshj.common.SecurityUtils;
|
||||
import net.schmizz.sshj.userauth.password.PasswordUtils;
|
||||
import org.bouncycastle.openssl.EncryptionException;
|
||||
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
|
||||
import org.bouncycastle.openssl.PEMKeyPair;
|
||||
@@ -26,8 +27,8 @@ import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import net.schmizz.sshj.common.IOUtils;
|
||||
import net.schmizz.sshj.userauth.password.PasswordUtils;
|
||||
import java.io.IOException;
|
||||
import java.security.KeyPair;
|
||||
|
||||
/** Represents a PKCS8-encoded key file. This is the format used by (old-style) OpenSSH and OpenSSL. */
|
||||
public class PKCS8KeyFile extends BaseFileKeyProvider {
|
||||
@@ -62,12 +63,12 @@ public class PKCS8KeyFile extends BaseFileKeyProvider {
|
||||
final Object o = r.readObject();
|
||||
|
||||
final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
|
||||
pemConverter.setProvider("BC");
|
||||
pemConverter.setProvider(SecurityUtils.getSecurityProvider());
|
||||
|
||||
if (o instanceof PEMEncryptedKeyPair) {
|
||||
final PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) o;
|
||||
JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder();
|
||||
decryptorBuilder.setProvider("BC");
|
||||
decryptorBuilder.setProvider(SecurityUtils.getSecurityProvider());
|
||||
try {
|
||||
passphrase = pwdf == null ? null : pwdf.reqPassword(resource);
|
||||
kp = pemConverter.getKeyPair(encryptedKeyPair.decryptKeyPair(decryptorBuilder.build(passphrase)));
|
||||
|
||||
@@ -15,21 +15,21 @@
|
||||
*/
|
||||
package net.schmizz.sshj.userauth.keyprovider;
|
||||
|
||||
import net.schmizz.sshj.common.Base64;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.userauth.password.PasswordUtils;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.*;
|
||||
import java.math.BigInteger;
|
||||
import java.security.*;
|
||||
import java.security.spec.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
||||
import net.schmizz.sshj.common.Base64;
|
||||
import net.schmizz.sshj.common.KeyType;
|
||||
import net.schmizz.sshj.userauth.password.PasswordUtils;
|
||||
|
||||
/**
|
||||
* <h2>Sample PuTTY file format</h2>
|
||||
|
||||
@@ -66,7 +66,7 @@ public abstract class KeyedAuthMethod
|
||||
if (signature == null)
|
||||
throw new UserAuthException("Could not create signature instance for " + kt + " key");
|
||||
|
||||
signature.init(null, key);
|
||||
signature.initSign(key);
|
||||
signature.update(new Buffer.PlainBuffer()
|
||||
.putString(params.getTransport().getSessionID())
|
||||
.putBuffer(reqBuf) // & rest of the data for sig
|
||||
|
||||
@@ -27,6 +27,6 @@ public class PrivateKeyFileResource
|
||||
@Override
|
||||
public Reader getReader()
|
||||
throws IOException {
|
||||
return new InputStreamReader(new FileInputStream(getDetail()));
|
||||
return new InputStreamReader(new FileInputStream(getDetail()), "UTF-8");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
package net.schmizz.sshj.xfer;
|
||||
|
||||
import net.schmizz.sshj.common.LoggerFactory;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public abstract class AbstractFileTransfer {
|
||||
|
||||
@@ -21,6 +21,7 @@ import org.slf4j.LoggerFactory;
|
||||
import java.io.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
|
||||
public class FileSystemFile
|
||||
implements LocalSourceFile, LocalDestFile {
|
||||
@@ -83,8 +84,9 @@ public class FileSystemFile
|
||||
}
|
||||
});
|
||||
|
||||
if (childFiles == null)
|
||||
if (childFiles == null) {
|
||||
throw new IOException("Error listing files in directory: " + this);
|
||||
}
|
||||
|
||||
final List<FileSystemFile> children = new ArrayList<FileSystemFile>();
|
||||
for (File f : childFiles) {
|
||||
@@ -113,12 +115,13 @@ public class FileSystemFile
|
||||
@Override
|
||||
public int getPermissions()
|
||||
throws IOException {
|
||||
if (isDirectory())
|
||||
if (isDirectory()) {
|
||||
return 0755;
|
||||
else if (isFile())
|
||||
} else if (isFile()) {
|
||||
return 0644;
|
||||
else
|
||||
} else {
|
||||
throw new IOException("Unsupported file type");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -130,8 +133,9 @@ public class FileSystemFile
|
||||
@Override
|
||||
public void setLastModifiedTime(long t)
|
||||
throws IOException {
|
||||
if (!file.setLastModified(t * 1000))
|
||||
if (!file.setLastModified(t * 1000)) {
|
||||
log.warn("Could not set last modified time for {} to {}", file, t);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -143,22 +147,41 @@ public class FileSystemFile
|
||||
!(FilePermission.OTH_W.isIn(perms) || FilePermission.GRP_W.isIn(perms)));
|
||||
final boolean x = file.setExecutable(FilePermission.USR_X.isIn(perms),
|
||||
!(FilePermission.OTH_X.isIn(perms) || FilePermission.GRP_X.isIn(perms)));
|
||||
if (!(r && w && x))
|
||||
if (!(r && w && x)) {
|
||||
log.warn("Could not set permissions for {} to {}", file, Integer.toString(perms, 16));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileSystemFile getChild(String name) {
|
||||
validateIsChildPath(name);
|
||||
return new FileSystemFile(new File(file, name));
|
||||
}
|
||||
|
||||
private void validateIsChildPath(String name) {
|
||||
String[] split = name.split("/");
|
||||
Stack<String> s = new Stack<String>();
|
||||
for (String component : split) {
|
||||
if (component == null || component.isEmpty() || ".".equals(component)) {
|
||||
continue;
|
||||
} else if ("..".equals(component) && !s.isEmpty()) {
|
||||
s.pop();
|
||||
continue;
|
||||
} else if ("..".equals(component)) {
|
||||
throw new IllegalArgumentException("Cannot traverse higher than " + file + " to get child " + name);
|
||||
}
|
||||
s.push(component);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileSystemFile getTargetFile(String filename)
|
||||
throws IOException {
|
||||
FileSystemFile f = this;
|
||||
|
||||
if (f.isDirectory())
|
||||
if (f.isDirectory()) {
|
||||
f = f.getChild(filename);
|
||||
}
|
||||
|
||||
if (!f.getFile().exists()) {
|
||||
if (!f.getFile().createNewFile())
|
||||
@@ -174,12 +197,15 @@ public class FileSystemFile
|
||||
throws IOException {
|
||||
FileSystemFile f = this;
|
||||
|
||||
if (f.getFile().exists())
|
||||
if (f.getFile().exists()) {
|
||||
if (f.isDirectory()) {
|
||||
if (!f.getName().equals(dirname))
|
||||
if (!f.getName().equals(dirname)) {
|
||||
f = f.getChild(dirname);
|
||||
} else
|
||||
}
|
||||
} else {
|
||||
throw new IOException(f + " - already exists as a file; directory required");
|
||||
}
|
||||
}
|
||||
|
||||
if (!f.getFile().exists() && !f.getFile().mkdir())
|
||||
throw new IOException("Failed to create directory: " + f);
|
||||
|
||||
@@ -75,9 +75,9 @@ public class SCPDownloadClient extends AbstractSCPClient {
|
||||
engine.signal("Start status OK");
|
||||
|
||||
String msg = engine.readMessage();
|
||||
do
|
||||
do {
|
||||
process(engine.getTransferListener(), null, msg, targetFile);
|
||||
while (!(msg = engine.readMessage()).isEmpty());
|
||||
} while (!(msg = engine.readMessage()).isEmpty());
|
||||
}
|
||||
|
||||
private long parseLong(String longString, String valType)
|
||||
@@ -93,15 +93,17 @@ public class SCPDownloadClient extends AbstractSCPClient {
|
||||
|
||||
private int parsePermissions(String cmd)
|
||||
throws SCPException {
|
||||
if (cmd.length() != 5)
|
||||
if (cmd.length() != 5) {
|
||||
throw new SCPException("Could not parse permissions from `" + cmd + "`");
|
||||
}
|
||||
return Integer.parseInt(cmd.substring(1), 8);
|
||||
}
|
||||
|
||||
private boolean process(TransferListener listener, String bufferedTMsg, String msg, LocalDestFile f)
|
||||
throws IOException {
|
||||
if (msg.length() < 1)
|
||||
if (msg.length() < 1) {
|
||||
throw new SCPException("Could not parse message `" + msg + "`");
|
||||
}
|
||||
|
||||
switch (msg.charAt(0)) {
|
||||
|
||||
@@ -139,8 +141,9 @@ public class SCPDownloadClient extends AbstractSCPClient {
|
||||
final List<String> dMsgParts = tokenize(dMsg, 3, true); // D<perms> 0 <dirname>
|
||||
final long length = parseLong(dMsgParts.get(1), "dir length");
|
||||
final String dirname = dMsgParts.get(2);
|
||||
if (length != 0)
|
||||
if (length != 0) {
|
||||
throw new IOException("Remote SCP command sent strange directory length: " + length);
|
||||
}
|
||||
|
||||
final TransferListener dirListener = listener.directory(dirname);
|
||||
{
|
||||
@@ -186,9 +189,9 @@ public class SCPDownloadClient extends AbstractSCPClient {
|
||||
private static List<String> tokenize(String msg, int totalParts, boolean consolidateTail)
|
||||
throws IOException {
|
||||
List<String> parts = Arrays.asList(msg.split(" "));
|
||||
if (parts.size() < totalParts ||
|
||||
(!consolidateTail && parts.size() != totalParts))
|
||||
if (parts.size() < totalParts || (!consolidateTail && parts.size() != totalParts)) {
|
||||
throw new IOException("Could not parse message received from remote SCP: " + msg);
|
||||
}
|
||||
|
||||
if (consolidateTail && totalParts < parts.size()) {
|
||||
final StringBuilder sb = new StringBuilder(parts.get(totalParts - 1));
|
||||
|
||||
Reference in New Issue
Block a user