dm_crypt: Extend unit tests to cover both ciphers
The current tests (that maps crypt device & checks if data is accessible
or not) only covered for the default cipher. Extend the tests for both
the ciphers (and correct key size).
This patch also add logic to validate_key_size depending on chosen
cipher in dm_rust lib.
Test: atest libdm_rust.test
Bug: 259253336
Change-Id: Ie32c0882db364ac296f0ed55991ce079bee0fbb8
diff --git a/libs/devicemapper/src/crypt.rs b/libs/devicemapper/src/crypt.rs
index 75105ce..b2e677a 100644
--- a/libs/devicemapper/src/crypt.rs
+++ b/libs/devicemapper/src/crypt.rs
@@ -17,10 +17,9 @@
/// `crypt` module implements the "crypt" target in the device mapper framework. Specifically,
/// it provides `DmCryptTargetBuilder` struct which is used to construct a `DmCryptTarget` struct
/// which is then given to `DeviceMapper` to create a mapper device.
-use crate::util::*;
use crate::DmTargetSpec;
-use anyhow::{bail, Context, Result};
+use anyhow::{ensure, Context, Result};
use data_model::DataInit;
use std::io::Write;
use std::mem::size_of;
@@ -32,6 +31,7 @@
// Documentation/admin-guide/device-mapper/dm-crypt.rst
/// Supported ciphers
+#[derive(Clone, Copy, Debug)]
pub enum CipherType {
// AES-256-HCTR2 takes a 32-byte key
AES256HCTR2,
@@ -47,6 +47,17 @@
CipherType::AES256XTS => "aes-xts-plain64",
}
}
+
+ fn get_required_key_size(&self) -> usize {
+ match *self {
+ CipherType::AES256HCTR2 => 32,
+ CipherType::AES256XTS => 64,
+ }
+ }
+
+ fn validata_key_size(&self, key_size: usize) -> bool {
+ key_size == self.get_required_key_size()
+ }
}
pub struct DmCryptTarget(Box<[u8]>);
@@ -124,8 +135,13 @@
.to_str()
.context("data device path is not encoded in utf8")?;
- let key =
- if let Some(key) = self.key { hexstring_from(key) } else { bail!("key is not set") };
+ ensure!(self.key.is_some(), "key is not set");
+ // Unwrap is safe because we already made sure key.is_some()
+ ensure!(
+ self.cipher.validata_key_size(self.key.unwrap().len()),
+ format!("Invalid key size for cipher:{}", self.cipher.get_kernel_crypto_name())
+ );
+ let key = hex::encode(self.key.unwrap());
// Step2: serialize the information according to the spec, which is ...
// DmTargetSpec{...}