Merge "Temporary ignore check_tee_service_permission tests" into main
diff --git a/guest/forwarder_guest_launcher/src/main.rs b/guest/forwarder_guest_launcher/src/main.rs
index 0e06c66..bba9691 100644
--- a/guest/forwarder_guest_launcher/src/main.rs
+++ b/guest/forwarder_guest_launcher/src/main.rs
@@ -110,8 +110,11 @@
 async fn report_active_ports(
     mut client: DebianServiceClient<Channel>,
 ) -> Result<(), Box<dyn std::error::Error>> {
-    let mut cmd =
-        Command::new("/usr/sbin/tcpstates-bpfcc").arg("-s").stdout(Stdio::piped()).spawn()?;
+    let mut cmd = Command::new("python3")
+        .arg("-u")
+        .arg("/usr/sbin/tcpstates-bpfcc -s")
+        .stdout(Stdio::piped())
+        .spawn()?;
     let stdout = cmd.stdout.take().context("Failed to get stdout of tcpstates")?;
     let mut csv_reader = AsyncReader::from_reader(BufReader::new(stdout));
     let header = csv_reader.headers().await?.clone();
diff --git a/guest/trusty/security_vm/launcher/Android.bp b/guest/trusty/security_vm/launcher/Android.bp
index e482e02..ef32740 100644
--- a/guest/trusty/security_vm/launcher/Android.bp
+++ b/guest/trusty/security_vm/launcher/Android.bp
@@ -40,12 +40,15 @@
 // python -c "import hashlib; print(hashlib.sha256(b'trusty_security_vm_salt').hexdigest())"
 trusty_security_vm_salt = "75a71e967c1a1e0f805cca20465e7acf83e6a04e567a67c426d8b5a94f8d61c5"
 
+TRUSTY_SECURITY_VM_VERSION = 1
+
 avb_add_hash_footer {
     name: "trusty_security_vm_signed",
     filename: "trusty_security_vm_signed",
     partition_name: "boot",
     private_key: ":trusty_vm_sign_key",
     salt: trusty_security_vm_salt,
+    rollback_index: TRUSTY_SECURITY_VM_VERSION,
     src: ":empty_file",
     enabled: false,
     arch: {
diff --git a/libs/cborutil/src/lib.rs b/libs/cborutil/src/lib.rs
index b218c82..4d308c1 100644
--- a/libs/cborutil/src/lib.rs
+++ b/libs/cborutil/src/lib.rs
@@ -21,10 +21,7 @@
 use alloc::string::String;
 use alloc::vec::Vec;
 use ciborium::value::{Integer, Value};
-use coset::{
-    iana::{self, EnumI64},
-    CborSerializable, CoseError, CoseKey, Label, Result,
-};
+use coset::{CborSerializable, CoseError, CoseKey, Label, Result};
 use log::error;
 use serde::{de::DeserializeOwned, Serialize};
 
@@ -135,19 +132,3 @@
         .ok_or(CoseError::UnexpectedItem("", "Label not found in CoseKey"))?
         .1)
 }
-
-/// Converts the provided COSE key algorithm integer to an `iana::Algorithm` used
-/// by DICE chains.
-pub fn dice_cose_key_alg(cose_key_alg: i32) -> Result<iana::Algorithm> {
-    let key_alg = iana::Algorithm::from_i64(cose_key_alg as i64).ok_or_else(|| {
-        error!("Unsupported COSE key algorithm for DICE: {cose_key_alg}");
-        CoseError::UnexpectedItem("COSE key algorithm", "")
-    })?;
-    match key_alg {
-        iana::Algorithm::EdDSA | iana::Algorithm::ES256 | iana::Algorithm::ES384 => Ok(key_alg),
-        _ => {
-            error!("Unsupported COSE key algorithm for DICE: {key_alg:?}");
-            Err(CoseError::UnexpectedItem("-8, -7 or -35", ""))
-        }
-    }
-}
diff --git a/libs/dice/open_dice/Android.bp b/libs/dice/open_dice/Android.bp
index d1129fb..c60260e 100644
--- a/libs/dice/open_dice/Android.bp
+++ b/libs/dice/open_dice/Android.bp
@@ -14,13 +14,11 @@
     name: "libdiced_open_dice_nostd",
     defaults: ["libdiced_open_dice_defaults"],
     rustlibs: [
+        "libcoset_nostd",
         "libopen_dice_android_bindgen_nostd",
         "libopen_dice_cbor_bindgen_nostd",
         "libzeroize_nostd",
     ],
-    features: [
-        "alloc",
-    ],
     whole_static_libs: [
         "libcrypto_baremetal",
     ],
@@ -35,13 +33,13 @@
     host_supported: true,
     vendor_available: true,
     rustlibs: [
+        "libcoset",
         "libopen_dice_android_bindgen",
         "libopen_dice_cbor_bindgen",
         "libserde",
         "libzeroize",
     ],
     features: [
-        "alloc",
         "serde_derive",
         "std",
     ],
@@ -154,10 +152,7 @@
         "--allowlist-var=DICE_INLINE_CONFIG_SIZE",
         "--allowlist-var=DICE_PRIVATE_KEY_SEED_SIZE",
         "--allowlist-var=DICE_ID_SIZE",
-        "--allowlist-var=DICE_PUBLIC_KEY_SIZE",
         "--allowlist-var=DICE_PRIVATE_KEY_SIZE",
-        "--allowlist-var=DICE_SIGNATURE_SIZE",
-        "--allowlist-var=DICE_COSE_KEY_ALG_VALUE",
     ],
 }
 
diff --git a/libs/dice/open_dice/src/dice.rs b/libs/dice/open_dice/src/dice.rs
index e330e00..6404508 100644
--- a/libs/dice/open_dice/src/dice.rs
+++ b/libs/dice/open_dice/src/dice.rs
@@ -16,12 +16,12 @@
 //! This module mirrors the content in open-dice/include/dice/dice.h
 
 use crate::error::{check_result, Result};
+use coset::iana;
 pub use open_dice_cbor_bindgen::DiceMode;
 use open_dice_cbor_bindgen::{
     DiceConfigType, DiceDeriveCdiCertificateId, DiceDeriveCdiPrivateKeySeed, DiceInputValues,
     DiceMainFlow, DICE_CDI_SIZE, DICE_HASH_SIZE, DICE_HIDDEN_SIZE, DICE_ID_SIZE,
     DICE_INLINE_CONFIG_SIZE, DICE_PRIVATE_KEY_SEED_SIZE, DICE_PRIVATE_KEY_SIZE,
-    DICE_PUBLIC_KEY_SIZE, DICE_SIGNATURE_SIZE,
 };
 #[cfg(feature = "serde_derive")]
 use serde_derive::{Deserialize, Serialize};
@@ -40,10 +40,6 @@
 pub const PRIVATE_KEY_SEED_SIZE: usize = DICE_PRIVATE_KEY_SEED_SIZE as usize;
 /// The size of a private key.
 pub const PRIVATE_KEY_SIZE: usize = DICE_PRIVATE_KEY_SIZE as usize;
-/// The size of a public key.
-pub const PUBLIC_KEY_SIZE: usize = DICE_PUBLIC_KEY_SIZE as usize;
-/// The size of a signature.
-pub const SIGNATURE_SIZE: usize = DICE_SIGNATURE_SIZE as usize;
 /// The size of an ID.
 pub const ID_SIZE: usize = DICE_ID_SIZE as usize;
 
@@ -55,13 +51,69 @@
 pub type InlineConfig = [u8; INLINE_CONFIG_SIZE];
 /// Array type of CDIs.
 pub type Cdi = [u8; CDI_SIZE];
-/// Array type of the public key.
-pub type PublicKey = [u8; PUBLIC_KEY_SIZE];
-/// Array type of the signature.
-pub type Signature = [u8; SIGNATURE_SIZE];
 /// Array type of DICE ID.
 pub type DiceId = [u8; ID_SIZE];
 
+/// Key algorithm used for DICE.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum KeyAlgorithm {
+    /// Ed25519.
+    Ed25519,
+    /// ECDSA using P-256 curve.
+    EcdsaP256,
+    /// ECDSA using P-384 curve.
+    EcdsaP384,
+}
+
+impl From<KeyAlgorithm> for iana::Algorithm {
+    fn from(alg: KeyAlgorithm) -> Self {
+        match alg {
+            KeyAlgorithm::Ed25519 => iana::Algorithm::EdDSA,
+            KeyAlgorithm::EcdsaP256 => iana::Algorithm::ES256,
+            KeyAlgorithm::EcdsaP384 => iana::Algorithm::ES384,
+        }
+    }
+}
+
+/// Key algorithm used within different components in VMs.
+///
+/// This algorithm serves two primary purposes:
+///
+/// * **pvmfw Handover:** In pvmfw, a vendor DICE chain, potentially using various algorithms, is
+///   transitioned to this specific algorithm.
+/// * **Post-Handover Consistency:** In components following pvmfw (e.g., the Microdroid OS), this
+///   algorithm is used consistently for both the authority and subject keys in DICE derivation.
+pub const VM_KEY_ALGORITHM: KeyAlgorithm = KeyAlgorithm::Ed25519;
+
+impl KeyAlgorithm {
+    /// Returns the size of the public key.
+    pub fn public_key_size(&self) -> usize {
+        match self {
+            KeyAlgorithm::Ed25519 => 32,
+            KeyAlgorithm::EcdsaP256 => 64,
+            KeyAlgorithm::EcdsaP384 => 96,
+        }
+    }
+
+    /// Returns the size of the signature.
+    pub fn signature_size(&self) -> usize {
+        match self {
+            KeyAlgorithm::Ed25519 => 64,
+            KeyAlgorithm::EcdsaP256 => 64,
+            KeyAlgorithm::EcdsaP384 => 96,
+        }
+    }
+
+    /// Returns the size of the private key.
+    pub fn private_key_size(&self) -> usize {
+        match self {
+            KeyAlgorithm::Ed25519 => 64,
+            KeyAlgorithm::EcdsaP256 => 32,
+            KeyAlgorithm::EcdsaP384 => 48,
+        }
+    }
+}
+
 /// A trait for types that represent Dice artifacts, which include:
 ///
 /// - Attestation CDI
diff --git a/libs/dice/open_dice/src/lib.rs b/libs/dice/open_dice/src/lib.rs
index 085a2cd..a347d46 100644
--- a/libs/dice/open_dice/src/lib.rs
+++ b/libs/dice/open_dice/src/lib.rs
@@ -17,7 +17,6 @@
 
 #![cfg_attr(not(feature = "std"), no_std)]
 
-#[cfg(feature = "alloc")]
 extern crate alloc;
 
 #[cfg(not(feature = "std"))]
@@ -27,7 +26,6 @@
 mod dice;
 mod error;
 mod ops;
-#[cfg(feature = "alloc")]
 mod retry;
 
 pub use bcc::{
@@ -36,18 +34,14 @@
 };
 pub use dice::{
     derive_cdi_certificate_id, derive_cdi_private_key_seed, dice_main_flow, Cdi, CdiValues, Config,
-    DiceArtifacts, DiceMode, Hash, Hidden, InlineConfig, InputValues, PrivateKey, PrivateKeySeed,
-    PublicKey, Signature, CDI_SIZE, HASH_SIZE, HIDDEN_SIZE, ID_SIZE, PRIVATE_KEY_SEED_SIZE,
+    DiceArtifacts, DiceMode, Hash, Hidden, InlineConfig, InputValues, KeyAlgorithm, PrivateKey,
+    PrivateKeySeed, CDI_SIZE, HASH_SIZE, HIDDEN_SIZE, ID_SIZE, PRIVATE_KEY_SEED_SIZE,
+    VM_KEY_ALGORITHM,
 };
 pub use error::{DiceError, Result};
-// Currently, open-dice library only supports a single signing and verification algorithm.
-// The value of DICE_COSE_KEY_ALG_VALUE depends on the algorithm chosen by the underlying C
-// library at build time. Refer to b/342333212 for more information.
-pub use open_dice_cbor_bindgen::DICE_COSE_KEY_ALG_VALUE;
 pub use ops::{
     derive_cdi_leaf_priv, generate_certificate, hash, kdf, keypair_from_seed, sign, verify,
 };
-#[cfg(feature = "alloc")]
 pub use retry::{
     retry_bcc_format_config_descriptor, retry_bcc_main_flow, retry_dice_main_flow,
     retry_generate_certificate, OwnedDiceArtifacts,
diff --git a/libs/dice/open_dice/src/ops.rs b/libs/dice/open_dice/src/ops.rs
index 47b5244..137736f 100644
--- a/libs/dice/open_dice/src/ops.rs
+++ b/libs/dice/open_dice/src/ops.rs
@@ -17,10 +17,11 @@
 //! main DICE functions depend on.
 
 use crate::dice::{
-    derive_cdi_private_key_seed, DiceArtifacts, Hash, InputValues, PrivateKey, PublicKey,
-    Signature, HASH_SIZE, PRIVATE_KEY_SEED_SIZE, PRIVATE_KEY_SIZE, PUBLIC_KEY_SIZE, SIGNATURE_SIZE,
+    derive_cdi_private_key_seed, DiceArtifacts, Hash, InputValues, PrivateKey, HASH_SIZE,
+    PRIVATE_KEY_SEED_SIZE, PRIVATE_KEY_SIZE, VM_KEY_ALGORITHM,
 };
-use crate::error::{check_result, Result};
+use crate::error::{check_result, DiceError, Result};
+use alloc::{vec, vec::Vec};
 use open_dice_cbor_bindgen::{
     DiceGenerateCertificate, DiceHash, DiceKdf, DiceKeypairFromSeed, DiceSign, DiceVerify,
 };
@@ -71,8 +72,8 @@
 /// Deterministically generates a public and private key pair from `seed`.
 /// Since this is deterministic, `seed` is as sensitive as a private key and can
 /// be used directly as the private key.
-pub fn keypair_from_seed(seed: &[u8; PRIVATE_KEY_SEED_SIZE]) -> Result<(PublicKey, PrivateKey)> {
-    let mut public_key = [0u8; PUBLIC_KEY_SIZE];
+pub fn keypair_from_seed(seed: &[u8; PRIVATE_KEY_SEED_SIZE]) -> Result<(Vec<u8>, PrivateKey)> {
+    let mut public_key = vec![0u8; VM_KEY_ALGORITHM.public_key_size()];
     let mut private_key = PrivateKey::default();
     check_result(
         // SAFETY: The function writes to the `public_key` and `private_key` within the given
@@ -106,8 +107,8 @@
 }
 
 /// Signs the `message` with the give `private_key` using `DiceSign`.
-pub fn sign(message: &[u8], private_key: &[u8; PRIVATE_KEY_SIZE]) -> Result<Signature> {
-    let mut signature = [0u8; SIGNATURE_SIZE];
+pub fn sign(message: &[u8], private_key: &[u8; PRIVATE_KEY_SIZE]) -> Result<Vec<u8>> {
+    let mut signature = vec![0u8; VM_KEY_ALGORITHM.signature_size()];
     check_result(
         // SAFETY: The function writes to the `signature` within the given bounds, and only reads
         // the message and the private key. The first argument context is not used in this
@@ -127,7 +128,12 @@
 }
 
 /// Verifies the `signature` of the `message` with the given `public_key` using `DiceVerify`.
-pub fn verify(message: &[u8], signature: &Signature, public_key: &PublicKey) -> Result<()> {
+pub fn verify(message: &[u8], signature: &[u8], public_key: &[u8]) -> Result<()> {
+    if signature.len() != VM_KEY_ALGORITHM.signature_size()
+        || public_key.len() != VM_KEY_ALGORITHM.public_key_size()
+    {
+        return Err(DiceError::InvalidInput);
+    }
     check_result(
         // SAFETY: only reads the messages, signature and public key as constant values.
         // The first argument context is not used in this function.
diff --git a/libs/dice/open_dice/src/retry.rs b/libs/dice/open_dice/src/retry.rs
index d9551f3..6e75e91 100644
--- a/libs/dice/open_dice/src/retry.rs
+++ b/libs/dice/open_dice/src/retry.rs
@@ -23,7 +23,6 @@
 };
 use crate::error::{DiceError, Result};
 use crate::ops::generate_certificate;
-#[cfg(feature = "alloc")]
 use alloc::vec::Vec;
 #[cfg(feature = "serde_derive")]
 use serde_derive::{Deserialize, Serialize};
diff --git a/libs/libclient_vm_csr/src/lib.rs b/libs/libclient_vm_csr/src/lib.rs
index 77cfea9..e5a6036 100644
--- a/libs/libclient_vm_csr/src/lib.rs
+++ b/libs/libclient_vm_csr/src/lib.rs
@@ -20,9 +20,7 @@
     iana, CborSerializable, CoseKey, CoseKeyBuilder, CoseSign, CoseSignBuilder, CoseSignature,
     CoseSignatureBuilder, HeaderBuilder,
 };
-use diced_open_dice::{
-    derive_cdi_leaf_priv, sign, DiceArtifacts, PrivateKey, DICE_COSE_KEY_ALG_VALUE,
-};
+use diced_open_dice::{derive_cdi_leaf_priv, sign, DiceArtifacts, PrivateKey, VM_KEY_ALGORITHM};
 use openssl::{
     bn::{BigNum, BigNumContext},
     ec::{EcGroup, EcKey, EcKeyRef},
@@ -93,8 +91,7 @@
     cdi_leaf_priv: &PrivateKey,
     attestation_key: &EcKeyRef<Private>,
 ) -> Result<CoseSign> {
-    let dice_key_alg = cbor_util::dice_cose_key_alg(DICE_COSE_KEY_ALG_VALUE)?;
-    let cdi_leaf_sig_headers = build_signature_headers(dice_key_alg);
+    let cdi_leaf_sig_headers = build_signature_headers(VM_KEY_ALGORITHM.into());
     let attestation_key_sig_headers = build_signature_headers(ATTESTATION_KEY_ALGO);
     let aad = &[];
     let signed_data = CoseSignBuilder::new()
diff --git a/libs/libservice_vm_requests/src/rkp.rs b/libs/libservice_vm_requests/src/rkp.rs
index 7de7cd5..2c26b16 100644
--- a/libs/libservice_vm_requests/src/rkp.rs
+++ b/libs/libservice_vm_requests/src/rkp.rs
@@ -28,7 +28,7 @@
 use core::result;
 use coset::{AsCborValue, CoseSign1, CoseSign1Builder, HeaderBuilder};
 use diced_open_dice::{
-    derive_cdi_leaf_priv, kdf, sign, DiceArtifacts, PrivateKey, DICE_COSE_KEY_ALG_VALUE,
+    derive_cdi_leaf_priv, kdf, sign, DiceArtifacts, PrivateKey, VM_KEY_ALGORITHM,
 };
 use log::{debug, error};
 use service_vm_comm::{EcdsaP256KeyPair, GenerateCertificateRequestParams, RequestProcessingError};
@@ -152,8 +152,7 @@
         error!("Failed to derive the CDI_Leaf_Priv: {e}");
         RequestProcessingError::InternalError
     })?;
-    let dice_key_alg = cbor_util::dice_cose_key_alg(DICE_COSE_KEY_ALG_VALUE)?;
-    let protected = HeaderBuilder::new().algorithm(dice_key_alg).build();
+    let protected = HeaderBuilder::new().algorithm(VM_KEY_ALGORITHM.into()).build();
     let signed_data = CoseSign1Builder::new()
         .protected(protected)
         .payload(cbor_util::serialize(payload)?)