diff --git a/Cargo.lock b/Cargo.lock index 1e9a28abc079b299f31dac66dfd6aacb781dbbee..d5dec6fbd9354fbcfacae73d1dacc744d40658b6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3030,9 +3030,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "300.1.6+3.1.4" +version = "300.5.3+3.5.4" +checksum = "dc6bad8cd0233b63971e232cc9c5e83039375b8586d2312f31fda85db8f888c2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439fac53e092cd7442a3660c85dde4643ab3b5bd39040912388dcdabf6b88085" dependencies = [ "cc", ] diff --git a/app/src/pages/listShow/ChangeCheck.vue b/app/src/pages/listShow/ChangeCheck.vue index d403a64a354e534fbdb16fb6ec571da21e32317d..a4d6eabd85d5c08ebe9962b86aff03ee563f2095 100644 --- a/app/src/pages/listShow/ChangeCheck.vue +++ b/app/src/pages/listShow/ChangeCheck.vue @@ -28,7 +28,7 @@ import { useBaseStore } from "@/store/base"; const useBase = useBaseStore(); const title = ref(); const check = [ - // "Import X509 Keys", + "Import X509 Keys", // "Import PGP Keys", "Create X509 Keys", "Create PGP Keys", diff --git a/app/src/pages/listShow/CreateX509.vue b/app/src/pages/listShow/CreateX509.vue index 14359521fccdd4a736863d4186722562f9c128fb..7469729f7195ad2f075e7a4a02e653d1bb1260a0 100644 --- a/app/src/pages/listShow/CreateX509.vue +++ b/app/src/pages/listShow/CreateX509.vue @@ -114,6 +114,10 @@ :key="item.value" :label="item.label" :value="item.value" + :disabled=" + (formLabelAlign.key_type === 'sm2' && ['2048', '3072', '4096'].includes(item.value)) || + (['rsa', 'dsa'].includes(formLabelAlign.key_type) && ['256'].includes(item.value)) + " /> @@ -128,6 +132,10 @@ :key="item.value" :label="item.label" :value="item.value" + :disabled=" + (formLabelAlign.key_type === 'sm2' && ['md5', 'sha1', 'sha2_256', 'sha2_224', 'sha2_384', 'sha2_512'].includes(item.value)) || + (['rsa', 'dsa'].includes(formLabelAlign.key_type) && ['sm3'].includes(item.value)) + " /> @@ -262,6 +270,10 @@ const optionsType = [ value: 'dsa', label: 'DSA', }, + { + value: 'sm2', + label: 'SM2', + }, ]; const typeKey = [ { @@ -283,6 +295,10 @@ const usageKey = [ }, ]; const optionsSize = [ + { + value: '256', + label: '256', + }, { value: '2048', label: '2048', @@ -321,6 +337,10 @@ const optionsDigest = [ value: 'sha2_512', label: 'sha2_512', }, + { + value: 'sm3', + label: 'sm3', + }, ]; //删除掉 diff --git a/app/src/pages/listShow/ImportX509.vue b/app/src/pages/listShow/ImportX509.vue index 550449048486ee0a57f28fd976bb6012af256407..0bfbc7f96a8ee2d31d7b4ab498157ac1f32b7716 100644 --- a/app/src/pages/listShow/ImportX509.vue +++ b/app/src/pages/listShow/ImportX509.vue @@ -122,7 +122,7 @@ const formLabelAlign = reactive({ private_key: "", public_key: "", certificate: "", - key_type: "x509", + key_type: "x509ee", keytype: "rsa", key_length: "2048", digest_algorithm: "md5", @@ -152,8 +152,16 @@ const optionsType = [ value: "dsa", label: "DSA", }, + { + value: "sm2", + label: "SM2", + } ]; const optionsSize = [ + { + value: '256', + label: '256', + }, { value: "2048", label: "2048", @@ -192,6 +200,10 @@ const optionsDigest = [ value: "sha2_512", label: "sha2_512", }, + { + value: "sm3", + label: "sm3", + }, ]; // 表单校验规则 /* 姓名 */ diff --git a/scripts/initialize-user-and-keys.sh b/scripts/initialize-user-and-keys.sh index 9b030f893e26dd85a29f92ac52dd7e3343bb77fe..5aa974f495d54454b27e0e32b39338201594cf15 100755 --- a/scripts/initialize-user-and-keys.sh +++ b/scripts/initialize-user-and-keys.sh @@ -38,6 +38,24 @@ function create_default_x509_ee { --param-x509-common-name Infra --param-x509-organization Huawei --param-x509-locality ShenZhen --param-x509-province-name GuangDong --param-x509-country-name CN --param-x509-organizational-unit "Infra EE" --digest-algorithm sha2_256 --param-x509-parent-name default-x509ica --visibility public } +function create_default_x509_ca_sm2 { + echo "start to create default x509_sm2 CA identified with default-x509ca-sm2" + RUST_LOG=info ./target/debug/control-admin --config ./config/server.toml generate-keys --name default-x509ca-sm2 --description "used for test purpose only" --key-type x509ca --email tommylikehu@gmail.com --param-key-type sm2 --param-key-size 2048 \ + --param-x509-common-name Infra --param-x509-organization Huawei --param-x509-locality ShenZhen --param-x509-province-name GuangDong --param-x509-country-name CN --param-x509-organizational-unit "Infra CA" --digest-algorithm sm3 --visibility public +} + +function create_default_x509_ia_sm2 { + echo "start to create default x509 sm2 ICA identified with default-x509" + RUST_LOG=info ./target/debug/control-admin --config ./config/server.toml generate-keys --name default-x509ica-sm2 --description "used for test purpose only" --key-type x509ica --email tommylikehu@gmail.com --param-key-type sm2 --param-key-size 2048 \ + --param-x509-common-name Infra --param-x509-organization Huawei --param-x509-locality ShenZhen --param-x509-province-name GuangDong --param-x509-country-name CN --param-x509-organizational-unit "Infra ICA" --digest-algorithm sm3 --param-x509-parent-name default-x509ca-sm2 --visibility public +} + +function create_default_x509_ee_sm2 { + echo "start to create default x509 sm2 EE certificate identified with default-x509" + RUST_LOG=info ./target/debug/control-admin --config ./config/server.toml generate-keys --name default-x509ee-sm2 --description "used for test purpose only" --key-type x509ee --email tommylikehu@gmail.com --param-key-type sm2 --param-key-size 2048 \ + --param-x509-common-name Infra --param-x509-organization Huawei --param-x509-locality ShenZhen --param-x509-province-name GuangDong --param-x509-country-name CN --param-x509-organizational-unit "Infra EE" --digest-algorithm sm3 --param-x509-parent-name default-x509ica-sm2 --visibility public +} + function create_default_openpgp_rsa { echo "start to create default openpgp keys identified with default-pgp" RUST_LOG=info ./target/debug/control-admin --config ./config/server.toml generate-keys --name default-pgp-rsa --description "used for test purpose only" --key-type pgp --email tommylikehu@gmail.com --param-key-type rsa --param-key-size 2048 --param-pgp-email infra@openeuler.org --param-pgp-passphrase husheng1234 --digest-algorithm sha2_256 --visibility public @@ -54,6 +72,8 @@ function create_default_private_openpgp_rsa { } + + echo "Preparing basic keys for signatrust......" check-binary @@ -68,6 +88,12 @@ create_default_x509_ica create_default_x509_ee +create_default_x509_ca_sm2 + +create_default_x509_ia_sm2 + +create_default_x509_ee_sm2 + create_default_openpgp_rsa create_default_openpgp_eddsa diff --git a/src/client/cmd/add.rs b/src/client/cmd/add.rs index 9a8a5f8cbbe8e363bcb65cd9abdb90f1c6a0139b..90e2301cba7583a367b7c692bde9ecef80c95ff1 100644 --- a/src/client/cmd/add.rs +++ b/src/client/cmd/add.rs @@ -51,6 +51,7 @@ lazy_static! { (FileType::EfiImage, vec![".*"]), // ima can be used for any file (FileType::ImaEvm, vec![".*"]), + (FileType::P7s, vec![".*"]), ]); } diff --git a/src/client/file_handler/factory.rs b/src/client/file_handler/factory.rs index 537fa9b29649f603e08173e024696e6115f6a6f2..5f78d4b2cbda4e388b962a5f37d3427c512469de 100644 --- a/src/client/file_handler/factory.rs +++ b/src/client/file_handler/factory.rs @@ -18,6 +18,7 @@ use super::efi::EfiFileHandler; use super::generic::GenericFileHandler; use super::ima::ImaFileHandler; use super::kernel_module::KernelModuleFileHandler; +use super::p7s::CmsFileHandler; use super::rpm::RpmFileHandler; use super::traits::FileHandler; use crate::util::sign::FileType; @@ -32,6 +33,7 @@ impl FileHandlerFactory { FileType::KernelModule => Box::new(KernelModuleFileHandler::new()), FileType::EfiImage => Box::new(EfiFileHandler::new()), FileType::ImaEvm => Box::new(ImaFileHandler::new()), + FileType::P7s => Box::new(CmsFileHandler::new()), } } } diff --git a/src/client/file_handler/ima.rs b/src/client/file_handler/ima.rs index 1ccdd4408ff493c4e6fcbad681ff017ebaa26ff3..74b670858f5f4c6e0df1fdefdda7eb74ebe798ba 100644 --- a/src/client/file_handler/ima.rs +++ b/src/client/file_handler/ima.rs @@ -82,7 +82,7 @@ impl FileHandler for ImaFileHandler { if let Some(detached) = sign_options.get(options::DETACHED) { if detached == "false" { return Err(Error::InvalidArgumentError( - "ima signer only support detached signature, you may need remove the --detach argument".to_string(), + "ima signer only support detached signature, you may need add the --detach argument".to_string(), )); } } diff --git a/src/client/file_handler/mod.rs b/src/client/file_handler/mod.rs index 21ccba363b3e82c36bd9fcc717106bd7ddb26aeb..79c1f77ed0523b712ac9f43f083ba960a76d4956 100644 --- a/src/client/file_handler/mod.rs +++ b/src/client/file_handler/mod.rs @@ -3,5 +3,6 @@ pub mod factory; pub mod generic; pub mod ima; pub mod kernel_module; +pub mod p7s; pub mod rpm; pub mod traits; diff --git a/src/client/file_handler/p7s.rs b/src/client/file_handler/p7s.rs new file mode 100644 index 0000000000000000000000000000000000000000..3391bb9992f813d85d9dfcd60fc42c3ed5ae9df5 --- /dev/null +++ b/src/client/file_handler/p7s.rs @@ -0,0 +1,141 @@ +/* + * + * * // Copyright (c) 2025 Huawei Technologies Co.,Ltd. All rights reserved. + * * // + * * // signatrust is licensed under Mulan PSL v2. + * * // You can use this software according to the terms and conditions of the Mulan + * * // PSL v2. + * * // You may obtain a copy of Mulan PSL v2 at: + * * // http://license.coscl.org.cn/MulanPSL2 + * * // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY + * * // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO + * * // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + * * // See the Mulan PSL v2 for more details. + * + */ + +use super::traits::FileHandler; +use crate::util::error::{Error, Result}; +use crate::util::options; +use crate::util::sign::{KeyType, SignType}; +use async_trait::async_trait; +use std::collections::HashMap; +use std::path::PathBuf; +use tokio::fs; +use uuid::Uuid; + +const CMS_EXTENSION: &str = "p7s"; + +#[derive(Clone)] +pub struct CmsFileHandler {} + +impl CmsFileHandler { + pub fn new() -> Self { + Self {} + } +} + +#[async_trait] +impl FileHandler for CmsFileHandler { + fn validate_options(&self, sign_options: &mut HashMap) -> Result<()> { + if let Some(detached) = sign_options.get(options::DETACHED) { + if detached == "false" { + return Err(Error::InvalidArgumentError( + "p7s only support detached signature".to_string(), + )); + } + } + + if let Some(key_type) = sign_options.get(options::KEY_TYPE) { + if key_type != KeyType::X509EE.to_string().as_str() { + return Err(Error::InvalidArgumentError( + "p7s only support x509 key".to_string(), + )); + } + } + + if let Some(sign_type) = sign_options.get(options::SIGN_TYPE) { + if sign_type != SignType::Cms.to_string().as_str() { + return Err(Error::InvalidArgumentError( + "p7s file only support cms".to_string(), + )); + } + } + Ok(()) + } + + async fn assemble_data( + &self, + path: &PathBuf, + data: Vec>, + temp_dir: &PathBuf, + _sign_options: &HashMap, + _key_attributes: &HashMap, + ) -> Result<(String, String)> { + let temp_file = temp_dir.join(Uuid::new_v4().to_string()); + fs::write(temp_file.clone(), &data[0]).await?; + Ok(( + temp_file.as_path().display().to_string(), + format!("{}.{}", path.as_path().display(), CMS_EXTENSION), + )) + } +} + +#[cfg(test)] +mod test { + use super::*; + use std::env; + + #[test] + fn test_validate_options() { + let mut options = HashMap::new(); + options.insert(options::DETACHED.to_string(), "false".to_string()); + let handler = CmsFileHandler::new(); + let result = handler.validate_options(&mut options); + assert!(result.is_err()); + assert_eq!( + result.unwrap_err().to_string(), + "invalid argument: p7s only support detached signature" + ); + + options.insert(options::DETACHED.to_string(), "true".to_string()); + options.insert(options::KEY_TYPE.to_string(), KeyType::Pgp.to_string()); + let result = handler.validate_options(&mut options); + assert!(result.is_err()); + assert_eq!( + result.unwrap_err().to_string(), + "invalid argument: p7s only support x509 key" + ); + + options.insert(options::KEY_TYPE.to_string(), KeyType::X509EE.to_string()); + options.insert( + options::SIGN_TYPE.to_string(), + SignType::RsaHash.to_string(), + ); + let result = handler.validate_options(&mut options); + assert!(result.is_err()); + assert_eq!( + result.unwrap_err().to_string(), + "invalid argument: p7s file only support cms" + ); + options.insert(options::SIGN_TYPE.to_string(), SignType::Cms.to_string()); + let result = handler.validate_options(&mut options); + assert!(result.is_ok()); + } + + #[tokio::test] + async fn test_assemble_data() { + let handler = CmsFileHandler::new(); + let options = HashMap::new(); + let path = PathBuf::from("./test_data/test.txt"); + let data = vec![vec![1, 2, 3]]; + let temp_dir = env::temp_dir(); + let result = handler + .assemble_data(&path, data, &temp_dir, &options, &HashMap::new()) + .await; + assert!(result.is_ok()); + let (temp_file, file_name) = result.expect("invoke assemble data should work"); + assert_eq!(temp_file.starts_with(temp_dir.to_str().unwrap()), true); + assert_eq!(file_name, "./test_data/test.txt.p7s"); + } +} diff --git a/src/domain/datakey/plugins/x509.rs b/src/domain/datakey/plugins/x509.rs index 63dcfbf36819c2b72d561ddec3f94d944f94bdd5..cece7126ce1f1d49780f9f307a0eb0941284dd62 100644 --- a/src/domain/datakey/plugins/x509.rs +++ b/src/domain/datakey/plugins/x509.rs @@ -14,7 +14,9 @@ use crate::util::error::{Error, Result}; use enum_iterator::Sequence; use openssl::dsa::Dsa; +use openssl::ec::{EcGroup, EcKey}; use openssl::hash::MessageDigest; +use openssl::nid::Nid; use openssl::pkey::{PKey, Private}; use openssl::rsa::Rsa; use serde::Deserialize; @@ -23,6 +25,7 @@ use std::fmt::{Display, Formatter}; use std::str::FromStr; pub const X509_VALID_KEY_SIZE: [&str; 3] = ["2048", "3072", "4096"]; +pub const X509_SM2_VALID_KEY_SIZE: [&str; 1] = ["256"]; #[derive(Debug, Clone, PartialEq, Sequence, Deserialize, Default)] pub enum X509EEUsage { @@ -58,6 +61,8 @@ pub enum X509KeyType { Rsa, #[serde(rename = "dsa")] Dsa, + #[serde(rename = "sm2")] + Sm2, } impl FromStr for X509KeyType { @@ -67,6 +72,7 @@ impl FromStr for X509KeyType { match s { "rsa" => Ok(X509KeyType::Rsa), "dsa" => Ok(X509KeyType::Dsa), + "sm2" => Ok(X509KeyType::Sm2), _ => Err(Error::UnsupportedTypeError(format!( "unsupported x509 key type {}", s @@ -80,15 +86,32 @@ impl Display for X509KeyType { match self { X509KeyType::Rsa => write!(f, "rsa"), X509KeyType::Dsa => write!(f, "dsa"), + X509KeyType::Sm2 => write!(f, "sm2"), } } } +pub fn generate_sm2() -> Result> { + let group = EcGroup::from_curve_name(Nid::SM2)?; + let ec_key = EcKey::generate(&group)?; + let key = PKey::from_ec_key(ec_key)?; + Ok(key) +} + impl X509KeyType { pub fn get_real_key_type(&self, key_length: u32) -> Result> { match self { X509KeyType::Rsa => Ok(PKey::from_rsa(Rsa::generate(key_length)?)?), X509KeyType::Dsa => Ok(PKey::from_dsa(Dsa::generate(key_length)?)?), + X509KeyType::Sm2 => Ok(generate_sm2()?), // sm2 key length is fixed at 256 + } + } + + pub fn as_str(&self) -> &'static str { + match self { + X509KeyType::Rsa => "rsa", + X509KeyType::Dsa => "dsa", + X509KeyType::Sm2 => "sm2", } } } @@ -107,6 +130,8 @@ pub enum X509DigestAlgorithm { SHA2_384, #[serde(rename = "sha2_512")] SHA2_512, + #[serde(rename = "sm3")] + SM3, } impl Display for X509DigestAlgorithm { @@ -118,6 +143,7 @@ impl Display for X509DigestAlgorithm { X509DigestAlgorithm::SHA2_256 => write!(f, "sha2_256"), X509DigestAlgorithm::SHA2_384 => write!(f, "sha2_384"), X509DigestAlgorithm::SHA2_512 => write!(f, "sha2_512"), + X509DigestAlgorithm::SM3 => write!(f, "sm3"), } } } @@ -133,6 +159,7 @@ impl FromStr for X509DigestAlgorithm { "sha2_256" => Ok(X509DigestAlgorithm::SHA2_256), "sha2_384" => Ok(X509DigestAlgorithm::SHA2_384), "sha2_512" => Ok(X509DigestAlgorithm::SHA2_512), + "sm3" => Ok(X509DigestAlgorithm::SM3), _ => Err(Error::UnsupportedTypeError(format!( "unsupported x509 digest algorithm {}", s @@ -150,6 +177,19 @@ impl X509DigestAlgorithm { X509DigestAlgorithm::SHA2_256 => MessageDigest::sha256(), X509DigestAlgorithm::SHA2_384 => MessageDigest::sha384(), X509DigestAlgorithm::SHA2_512 => MessageDigest::sha512(), + X509DigestAlgorithm::SM3 => MessageDigest::sm3(), + } + } + + pub fn as_str(&self) -> &'static str { + match self { + X509DigestAlgorithm::MD5 => "md5", + X509DigestAlgorithm::SHA1 => "sha1", + X509DigestAlgorithm::SHA2_224 => "sha2_224", + X509DigestAlgorithm::SHA2_256 => "sha2_256", + X509DigestAlgorithm::SHA2_384 => "sha2_384", + X509DigestAlgorithm::SHA2_512 => "sha2_512", + X509DigestAlgorithm::SM3 => "sm3", } } } diff --git a/src/infra/sign_plugin/x509.rs b/src/infra/sign_plugin/x509.rs index a497e6ed6ffb00dcff6130c450d2ff6b722db4a1..4aef0258b1db9baa8718692d8ca59c8f20cbc8fb 100644 --- a/src/infra/sign_plugin/x509.rs +++ b/src/infra/sign_plugin/x509.rs @@ -14,10 +14,6 @@ * */ -use std::collections::HashMap; -use std::str::FromStr; -use std::time::{Duration, SystemTime}; - use chrono::{DateTime, Utc}; use foreign_types_shared::{ForeignType, ForeignTypeRef}; use openssl::asn1::{Asn1Integer, Asn1Time}; @@ -40,6 +36,9 @@ use openssl_sys::{ }; use secstr::SecVec; use serde::Deserialize; +use std::collections::HashMap; +use std::str::FromStr; +use std::time::{Duration, SystemTime}; use super::util::{attributes_validate, validate_utc_time, validate_utc_time_not_expire}; use crate::domain::datakey::entity::{ @@ -47,7 +46,7 @@ use crate::domain::datakey::entity::{ INFRA_CONFIG_DOMAIN_NAME, }; use crate::domain::datakey::plugins::x509::{ - X509DigestAlgorithm, X509EEUsage, X509KeyType, X509_VALID_KEY_SIZE, + X509DigestAlgorithm, X509EEUsage, X509KeyType, X509_SM2_VALID_KEY_SIZE, X509_VALID_KEY_SIZE, }; use crate::domain::sign_plugin::SignPlugins; use crate::util::attributes; @@ -60,6 +59,7 @@ use enum_iterator::all; use validator::{Validate, ValidationError}; #[derive(Debug, Validate, Deserialize)] +#[validate(schema(function = "validate_x509_key_size_for_generation"))] pub struct X509KeyGenerationParameter { #[validate(length(min = 1, max = 30, message = "invalid x509 subject 'CommonName'"))] common_name: String, @@ -82,10 +82,6 @@ pub struct X509KeyGenerationParameter { #[validate(length(min = 2, max = 2, message = "invalid x509 subject 'CountryName'"))] country_name: String, key_type: X509KeyType, - #[validate(custom( - function = "validate_x509_key_size", - message = "invalid x509 attribute 'key_length'" - ))] key_length: String, digest_algorithm: X509DigestAlgorithm, #[validate(custom( @@ -103,12 +99,9 @@ pub struct X509KeyGenerationParameter { } #[derive(Debug, Validate, Deserialize)] +#[validate(schema(function = "validate_x509_key_size_for_import"))] pub struct X509KeyImportParameter { key_type: X509KeyType, - #[validate(custom( - function = "validate_x509_key_size", - message = "invalid x509 attribute 'key_length'" - ))] key_length: String, digest_algorithm: X509DigestAlgorithm, #[validate(custom( @@ -136,13 +129,42 @@ impl X509KeyGenerationParameter { } } -fn validate_x509_key_size(key_size: &str) -> std::result::Result<(), ValidationError> { - if !X509_VALID_KEY_SIZE.contains(&key_size) { - return Err(ValidationError::new( - "invalid key size, possible values are 2048/3072/4096", - )); +fn validate_key_size_core( + key_type: &X509KeyType, + key_length: &String, +) -> std::result::Result<(), ValidationError> { + match key_type { + X509KeyType::Rsa | X509KeyType::Dsa => { + if X509_VALID_KEY_SIZE.contains(&key_length.as_str()) { + Ok(()) + } else { + return Err(ValidationError::new( + "invaild key size, RSA/DSA possible values are 2048/3072/4049", + )); + } + } + X509KeyType::Sm2 => { + if X509_SM2_VALID_KEY_SIZE.contains(&key_length.as_str()) { + Ok(()) + } else { + return Err(ValidationError::new( + "invaild key size, SM2 possible values are 256", + )); + } + } } - Ok(()) +} + +fn validate_x509_key_size_for_import( + p: &X509KeyImportParameter, +) -> std::result::Result<(), ValidationError> { + validate_key_size_core(&p.key_type, &p.key_length) +} + +fn validate_x509_key_size_for_generation( + p: &X509KeyGenerationParameter, +) -> std::result::Result<(), ValidationError> { + validate_key_size_core(&p.key_type, &p.key_length) } fn days_in_duration(time: &str) -> Result { @@ -871,7 +893,9 @@ mod test { parameter.insert("key_type".to_string(), "".to_string()); attributes_validate::(¶meter) .expect_err("invalid empty key type"); - for key_type in all::().collect::>() { + + let key_types = vec![X509KeyType::Rsa, X509KeyType::Dsa]; + for key_type in key_types { parameter.insert("key_type".to_string(), key_type.to_string()); attributes_validate::(¶meter).expect("valid key type"); } @@ -945,12 +969,21 @@ mod test { } #[tokio::test] - async fn test_generate_ca_with_possible_digest_hash() { + async fn test_generate_ca_with_international_algo() { let mut parameter = get_default_parameter(); //choose 4 random digest algorithm let dummy_engine = get_encryption_engine(); let infra_config = get_infra_config(); - for hash in all::().collect::>() { + let algos = vec![ + X509DigestAlgorithm::MD5, + X509DigestAlgorithm::SHA1, + X509DigestAlgorithm::SHA2_224, + X509DigestAlgorithm::SHA2_256, + X509DigestAlgorithm::SHA2_384, + X509DigestAlgorithm::SHA2_512, + ]; + + for hash in algos { parameter.insert("digest_algorithm".to_string(), hash.to_string()); let sec_datakey = SecDataKey::load( &get_default_datakey(None, Some(parameter.clone()), Some(KeyType::X509CA)), @@ -965,6 +998,44 @@ mod test { } } + #[tokio::test] + async fn test_generate_ca_with_sm_algo() { + let mut parameter = get_default_parameter(); + let dummy_engine = get_encryption_engine(); + let infra_config = get_infra_config(); + parameter.insert("key_type".to_string(), "sm2".to_string()); + parameter.insert("digest_algorithm".to_string(), "sm3".to_string()); + parameter.insert("key_length".to_string(), "256".to_string()); + let sec_datakey = SecDataKey::load( + &get_default_datakey(None, Some(parameter.clone()), Some(KeyType::X509CA)), + &dummy_engine, + ) + .await + .expect("load sec datakey successfully"); + let plugin = X509Plugin::new(sec_datakey).expect("create plugin successfully"); + plugin + .generate_keys(&KeyType::X509CA, &infra_config) + .expect(format!("generate ca key with digest sm3 successfully").as_str()); + } + + #[tokio::test] + async fn test_generate_sm_ca_with_incorrect_length() { + let mut parameter = get_default_parameter(); + let dummy_engine = get_encryption_engine(); + let infra_config = get_infra_config(); + parameter.insert("key_type".to_string(), "sm2".to_string()); + parameter.insert("digest_algorithm".to_string(), "sm3".to_string()); + let sec_datakey = SecDataKey::load( + &get_default_datakey(None, Some(parameter.clone()), Some(KeyType::X509CA)), + &dummy_engine, + ) + .await + .expect("load sec datakey successfully"); + let plugin = X509Plugin::new(sec_datakey).expect("create plugin successfully"); + let result = plugin.generate_keys(&KeyType::X509CA, &infra_config); + assert!(result.is_err()); + } + #[tokio::test] async fn test_generate_key_with_possible_length() { let mut parameter = get_default_parameter(); @@ -988,11 +1059,13 @@ mod test { } #[tokio::test] - async fn test_generate_key_with_possible_key_type() { + async fn test_generate_key_with_international_type() { let mut parameter = get_default_parameter(); let dummy_engine = get_encryption_engine(); let infra_config = get_infra_config(); - for key_type in all::().collect::>() { + + let types = vec![X509KeyType::Rsa, X509KeyType::Dsa]; + for key_type in types { parameter.insert("key_type".to_string(), key_type.to_string()); let sec_datakey = SecDataKey::load( &get_default_datakey(None, Some(parameter.clone()), Some(KeyType::X509CA)), diff --git a/src/util/sign.rs b/src/util/sign.rs index 70767362a34a6a66aff49490f785aba64a3baf5d..2ba901fcf3b1db54749e8e99fbb97ecbcf7f16ed 100644 --- a/src/util/sign.rs +++ b/src/util/sign.rs @@ -42,6 +42,7 @@ pub enum FileType { KernelModule, EfiImage, ImaEvm, + P7s, } impl Display for FileType { @@ -52,6 +53,7 @@ impl Display for FileType { FileType::KernelModule => write!(f, "ko"), FileType::EfiImage => write!(f, "efi"), FileType::ImaEvm => write!(f, "ima"), + FileType::P7s => write!(f, "p7s"), } } }