Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement AES-GCM cipher support #630

Merged
merged 3 commits into from
Sep 9, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions src/main/java/com/hierynomus/sshj/transport/cipher/GcmCipher.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hierynomus.sshj.transport.cipher;

import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.SSHRuntimeException;
import net.schmizz.sshj.transport.cipher.BaseCipher;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;

public class GcmCipher extends BaseCipher {

protected Mode mode;
protected boolean initialized;
protected CounterGCMParameterSpec parameters;
protected SecretKey secretKey;

public GcmCipher(int ivsize, int authSize, int bsize, String algorithm, String transformation) {
super(ivsize, authSize, bsize, algorithm, transformation);
}

protected Cipher getInitializedCipherInstance() throws GeneralSecurityException {
hierynomus marked this conversation as resolved.
Show resolved Hide resolved
Cipher cipher = getCipherInstance();
if (!initialized) {
cipher.init(mode == Mode.Encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, secretKey, parameters);
initialized = true;
}
return cipher;
}

@Override
protected void initCipher(Cipher cipher, Mode mode, byte[] key, byte[] iv) throws InvalidKeyException, InvalidAlgorithmParameterException {
this.mode = mode;
this.secretKey = getKeySpec(key);
this.parameters = new CounterGCMParameterSpec(getAuthenticationTagSize() * Byte.SIZE, iv);
cipher.init(getMode(mode), secretKey, parameters);
initialized = true;
}

@Override
public void updateAAD(byte[] data, int offset, int length) {
try {
Cipher cipher = getInitializedCipherInstance();
cipher.updateAAD(data, offset, length);
} catch (GeneralSecurityException e) {
throw new SSHRuntimeException("Error updating data through cipher", e);
}
}

@Override
public void update(byte[] input, int inputOffset, int inputLen) {
if (mode == Mode.Decrypt) {
inputLen += getAuthenticationTagSize();
}
try {
Cipher cipher = getInitializedCipherInstance();
cipher.doFinal(input, inputOffset, inputLen, input, inputOffset);
} catch (GeneralSecurityException e) {
throw new SSHRuntimeException("Error updating data through cipher", e);
}
parameters.incrementCounter();
initialized = false;
}

/**
* Algorithm parameters for AES/GCM that assumes the IV uses an 8-byte counter field as its most significant bytes.
*/
protected static class CounterGCMParameterSpec extends GCMParameterSpec {
protected final byte[] iv;

protected CounterGCMParameterSpec(int tLen, byte[] src) {
super(tLen, src);
if (src.length != 12) {
throw new IllegalArgumentException("GCM nonce must be 12 bytes, but given len=" + src.length);
}
iv = src.clone();
}

protected void incrementCounter() {
int off = iv.length - 8;
long counter = Buffer.getLong(iv, off, 8);
Buffer.putLong(addExact(counter, 1L), iv, off, 8);
}

@Override
public byte[] getIV() {
// JCE implementation of GCM will complain if the reference doesn't change between inits
return iv.clone();
}

static long addExact(long var0, long var2) {
long var4 = var0 + var2;
if (((var0 ^ var4) & (var2 ^ var4)) < 0L) {
throw new ArithmeticException("long overflow");
} else {
return var4;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hierynomus.sshj.transport.cipher;

import net.schmizz.sshj.transport.cipher.Cipher;

public class GcmCiphers {

public static final String GALOIS_COUNTER_MODE = "GCM";

public static Factory AES128GCM() {
return new Factory(12, 16,128, "aes128-gcm@openssh.com", "AES", GALOIS_COUNTER_MODE);
hierynomus marked this conversation as resolved.
Show resolved Hide resolved
}

public static Factory AES256GCM() {
return new Factory(12, 16, 256, "aes256-gcm@openssh.com", "AES", GALOIS_COUNTER_MODE);
}

/** Named factory for BlockCipher */
public static class Factory
implements net.schmizz.sshj.common.Factory.Named<Cipher> {

private int keysize;
private int authSize;
private String cipher;
private String mode;
private String name;
private int ivsize;

/**
* @param ivsize
* @param keysize The keysize used in bits.
* @param name
* @param cipher
* @param mode
*/
public Factory(int ivsize, int authSize, int keysize, String name, String cipher, String mode) {
this.name = name;
this.keysize = keysize;
this.cipher = cipher;
this.mode = mode;
this.ivsize = ivsize;
this.authSize = authSize;
}

@Override
public Cipher create() {
return new GcmCipher(ivsize, authSize,keysize / 8, cipher, cipher + "/" + mode + "/NoPadding");
hierynomus marked this conversation as resolved.
Show resolved Hide resolved
}

@Override
public String getName() {
return name;
}

@Override
public String toString() {
return getName();
}
}
}
3 changes: 3 additions & 0 deletions src/main/java/net/schmizz/sshj/DefaultConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.hierynomus.sshj.key.KeyAlgorithm;
import com.hierynomus.sshj.key.KeyAlgorithms;
import com.hierynomus.sshj.transport.cipher.BlockCiphers;
import com.hierynomus.sshj.transport.cipher.GcmCiphers;
import com.hierynomus.sshj.transport.cipher.StreamCiphers;
import com.hierynomus.sshj.transport.kex.DHGroups;
import com.hierynomus.sshj.transport.kex.ExtInfoClientFactory;
Expand Down Expand Up @@ -171,6 +172,8 @@ protected void initCipherFactories() {
BlockCiphers.AES192CTR(),
BlockCiphers.AES256CBC(),
BlockCiphers.AES256CTR(),
GcmCiphers.AES128GCM(),
GcmCiphers.AES256GCM(),
BlockCiphers.BlowfishCBC(),
BlockCiphers.BlowfishCTR(),
BlockCiphers.Cast128CBC(),
Expand Down
34 changes: 34 additions & 0 deletions src/main/java/net/schmizz/sshj/common/Buffer.java
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,23 @@ public BigInteger readUInt64AsBigInteger()
return new BigInteger(1, magnitude);
}

public static long getLong(byte[] buf, int off, int len) {
hierynomus marked this conversation as resolved.
Show resolved Hide resolved
if (len < 8) {
throw new IllegalArgumentException("Not enough data for a long: required=8, available=" + len);
}

long l = (long) buf[off] << 56;
l |= ((long) buf[off + 1] & 0xff) << 48;
l |= ((long) buf[off + 2] & 0xff) << 40;
l |= ((long) buf[off + 3] & 0xff) << 32;
l |= ((long) buf[off + 4] & 0xff) << 24;
l |= ((long) buf[off + 5] & 0xff) << 16;
l |= ((long) buf[off + 6] & 0xff) << 8;
l |= (long) buf[off + 7] & 0xff;

return l;
}

public T putUInt64(long uint64) {
if (uint64 < 0) {
throw new IllegalArgumentException("Invalid value: " + uint64);
Expand Down Expand Up @@ -384,6 +401,23 @@ private T putUInt64Unchecked(long uint64) {
return (T) this;
}

public static int putLong(long value, byte[] buf, int off, int len) {
if (len < 8) {
throw new IllegalArgumentException("Not enough data for a long: required=8, available=" + len);
}

buf[off] = (byte) (value >> 56);
buf[off + 1] = (byte) (value >> 48);
buf[off + 2] = (byte) (value >> 40);
buf[off + 3] = (byte) (value >> 32);
buf[off + 4] = (byte) (value >> 24);
buf[off + 5] = (byte) (value >> 16);
buf[off + 6] = (byte) (value >> 8);
buf[off + 7] = (byte) value;

return 8;
}

/**
* Reads an SSH string
*
Expand Down
7 changes: 6 additions & 1 deletion src/main/java/net/schmizz/sshj/transport/Converter.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ abstract class Converter {
protected long seq = -1;
protected boolean authed;
protected boolean etm;
protected boolean authMode;

long getSequenceNumber() {
return seq;
Expand All @@ -57,7 +58,11 @@ void setAlgorithms(Cipher cipher, MAC mac, Compression compression) {
if (compression != null)
compression.init(getCompressionType());
this.cipherSize = cipher.getIVSize();
this.etm = mac.isEtm();
this.etm = this.mac != null && mac.isEtm();
if(cipher.getAuthenticationTagSize() > 0) {
this.cipherSize = cipher.getAuthenticationTagSize();
this.authMode = true;
}
}

void setAuthenticated() {
Expand Down
62 changes: 58 additions & 4 deletions src/main/java/net/schmizz/sshj/transport/Decoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,50 @@ final class Decoder
*/
private int decode()
throws SSHException {

if (etm) {
if (authMode) {
return decodeAuthMode();
} else if (etm) {
return decodeEtm();
} else {
return decodeMte();
}
}

private int decodeAuthMode() throws SSHException {
hierynomus marked this conversation as resolved.
Show resolved Hide resolved
int need;
for(;;) {
if (packetLength == -1) { // Waiting for beginning of packet
assert inputBuffer.rpos() == 0 : "buffer cleared";
need = cipherSize - inputBuffer.available();
if (need <= 0) {
packetLength = decryptLengthAAD();
} else {
// Need more data
break;
}
} else {
assert inputBuffer.rpos() == 4 : "packet length read";
need = packetLength + cipherSize - inputBuffer.available();
if (need <= 0) {
seq = seq + 1 & 0xffffffffL;
cipher.update(inputBuffer.array(), 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 need;
}

/**
* Decode an Encrypt-Then-Mac packet.
*/
Expand All @@ -99,7 +135,7 @@ private int decodeEtm() throws SSHException {
}
} else {
assert inputBuffer.rpos() == 4 : "packet length read";
bytesNeeded = packetLength + mac.getBlockSize() - inputBuffer.available();
bytesNeeded = packetLength + (mac != null ? mac.getBlockSize() : 0) - inputBuffer.available();
if (bytesNeeded <= 0) {
seq = seq + 1 & 0xffffffffL;
checkMAC(inputBuffer.array());
Expand Down Expand Up @@ -170,6 +206,9 @@ private int decodeMte() throws SSHException {

private void checkMAC(final byte[] data)
throws TransportException {
if(mac == null)
hierynomus marked this conversation as resolved.
Show resolved Hide resolved
return;

mac.update(seq); // seq num
mac.update(data, 0, packetLength + 4); // packetLength+4 = entire packet w/o mac
mac.doFinal(macResult, 0); // compute
Expand All @@ -186,6 +225,20 @@ private SSHPacket decompressed()
return uncompressBuffer;
}

private int decryptLengthAAD() throws TransportException {
cipher.updateAAD(inputBuffer.array(), 0, 4);

final int len;
try {
len = inputBuffer.readUInt32AsInt();
} catch (Buffer.BufferException be) {
throw new TransportException(be);
}
checkPacketLength(len);

return len;
}

private int decryptLength()
throws TransportException {
decryptBuffer(0, cipherSize);
Expand Down Expand Up @@ -237,7 +290,8 @@ int received(byte[] b, int len)
@Override
void setAlgorithms(Cipher cipher, MAC mac, Compression compression) {
super.setAlgorithms(cipher, mac, compression);
macResult = new byte[mac.getBlockSize()];
if(mac != null)
hierynomus marked this conversation as resolved.
Show resolved Hide resolved
macResult = new byte[mac.getBlockSize()];
}

@Override
Expand Down
Loading