This commit is contained in:
Mateusz Gruszczyński
2026-08-23 22:19:53 +02:00
parent 9c9b7b272b
commit d834284695
9 changed files with 199 additions and 64 deletions
+46 -8
View File
@@ -1,7 +1,14 @@
use aes::{Aes128, cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray}};
use aes_gcm::{Aes128Gcm, Nonce, aead::{AeadInPlace, KeyInit as AeadKeyInit}};
use anyhow::{anyhow, bail, Context, Result};
use base64::{engine::general_purpose::STANDARD, Engine};
use base64::{
alphabet,
engine::{
general_purpose::{GeneralPurpose, GeneralPurposeConfig, STANDARD},
DecodePaddingMode,
},
Engine,
};
/// Shared discovery/bind key used by the original AES-128-ECB protocol.
pub const GENERIC_GREE_V1_KEY: &str = "a3K8Bx%2r8Y7#xDh";
@@ -11,6 +18,17 @@ pub const GENERIC_GREE_V2_KEY: &str = "{yxAHAY_Lm6pbC/<";
const GCM_NONCE: [u8; 12] = [0x54, 0x40, 0x78, 0x44, 0x49, 0x67, 0x5a, 0x51, 0x6c, 0x5e, 0x63, 0x13];
const GCM_AAD: &[u8] = b"qualcomm-test";
// Some GREE Wi-Fi modules emit technically non-canonical Base64: padding may
// be omitted and unused trailing bits can be set. Python's base64 decoder,
// used by the established GREE implementations, accepts those packets. Keep
// encoding canonical but use a forgiving decoder for device-originated data.
const GREE_BASE64_DECODE: GeneralPurpose = GeneralPurpose::new(
&alphabet::STANDARD,
GeneralPurposeConfig::new()
.with_decode_padding_mode(DecodePaddingMode::Indifferent)
.with_decode_allow_trailing_bits(true),
);
pub fn normalize_key(key: &str) -> Result<[u8; 16]> {
let bytes = key.as_bytes();
if bytes.len() == 16 {
@@ -44,7 +62,7 @@ pub fn encrypt_v1(key: &str, plaintext: &[u8]) -> Result<String> {
pub fn decrypt_v1(key: &str, ciphertext_b64: &str) -> Result<Vec<u8>> {
let key = normalize_key(key)?;
let cipher = Aes128::new_from_slice(&key).map_err(|_| anyhow!("invalid AES key"))?;
let mut data = STANDARD.decode(ciphertext_b64).context("invalid base64 packet")?;
let mut data = GREE_BASE64_DECODE.decode(ciphertext_b64).context("invalid base64 packet")?;
if data.is_empty() || data.len() % 16 != 0 {
bail!("invalid AES-ECB ciphertext length")
}
@@ -52,10 +70,19 @@ pub fn decrypt_v1(key: &str, ciphertext_b64: &str) -> Result<Vec<u8>> {
cipher.decrypt_block(GenericArray::from_mut_slice(block));
}
let pad = *data.last().ok_or_else(|| anyhow!("empty plaintext"))? as usize;
if pad == 0 || pad > 16 || data.len() < pad || data[data.len() - pad..].iter().any(|v| *v as usize != pad) {
bail!("invalid PKCS#7 padding")
let valid_padding = pad > 0
&& pad <= 16
&& data.len() >= pad
&& data[data.len() - pad..].iter().all(|v| *v as usize == pad);
if valid_padding {
data.truncate(data.len() - pad);
} else if let Some(last_json_byte) = data.iter().rposition(|byte| *byte == b'}') {
// Legacy GREE implementations are deliberately tolerant here: some
// modules return non-standard padding but the JSON itself is valid.
data.truncate(last_json_byte + 1);
} else {
bail!("invalid AES-ECB padding and no JSON terminator")
}
data.truncate(data.len() - pad);
Ok(data)
}
@@ -81,13 +108,15 @@ pub fn encrypt_v2(key: &str, plaintext: &[u8]) -> Result<V2Encrypted> {
pub fn decrypt_v2(key: &str, ciphertext_b64: &str, tag_b64: &str) -> Result<Vec<u8>> {
let key = normalize_key(key)?;
let cipher = <Aes128Gcm as AeadKeyInit>::new_from_slice(&key).map_err(|_| anyhow!("invalid AES-GCM key"))?;
let tag_bytes = STANDARD.decode(tag_b64).context("invalid GCM tag")?;
if tag_bytes.len() != 16 { bail!("invalid GCM tag length") }
let mut data = STANDARD.decode(ciphertext_b64).context("invalid GCM ciphertext")?;
let tag_bytes = GREE_BASE64_DECODE.decode(tag_b64).context("invalid GCM tag")?;
if tag_bytes.len() != 16 { bail!("invalid GCM tag length: {} bytes", tag_bytes.len()) }
let mut data = GREE_BASE64_DECODE.decode(ciphertext_b64).context("invalid GCM ciphertext")?;
let nonce = Nonce::from_slice(&GCM_NONCE);
let tag = GenericArray::from_slice(&tag_bytes);
cipher.decrypt_in_place_detached(nonce, GCM_AAD, &mut data, tag)
.map_err(|_| anyhow!("AES-GCM authentication failed"))?;
// A few modules append 0xff filler bytes to decrypted JSON.
data.retain(|byte| *byte != 0xff);
Ok(data)
}
@@ -108,4 +137,13 @@ mod tests {
let encrypted = encrypt_v2(GENERIC_GREE_V2_KEY, value).unwrap();
assert_eq!(decrypt_v2(GENERIC_GREE_V2_KEY, &encrypted.ciphertext, &encrypted.tag).unwrap(), value);
}
#[test]
fn gree_base64_accepts_noncanonical_trailing_bits() {
// 16 zero bytes canonically end with `A==`. `B==` carries the same
// useful two bits but has non-zero unused trailing bits. Python's
// base64.b64decode accepts it and real GREE modules emit this form.
let decoded = GREE_BASE64_DECODE.decode("AAAAAAAAAAAAAAAAAAAAAB==").unwrap();
assert_eq!(decoded, vec![0_u8; 16]);
}
}