Merge "Switch compsvc to use authfs_service"
diff --git a/apkverify/Android.bp b/apkverify/Android.bp
new file mode 100644
index 0000000..8a98320
--- /dev/null
+++ b/apkverify/Android.bp
@@ -0,0 +1,21 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_library {
+    name: "libapkverify",
+    host_supported: true,
+    crate_name: "apkverify",
+    srcs: ["src/lib.rs"],
+    prefer_rlib: true,
+    edition: "2018",
+    rustlibs: [
+        "libanyhow",
+        "libbyteorder",
+        "libbytes",
+        "liblog_rust",
+        "libring",
+        "libx509_parser",
+        "libzip",
+    ],
+}
diff --git a/apkverify/src/bytes_ext.rs b/apkverify/src/bytes_ext.rs
new file mode 100644
index 0000000..5efb33c
--- /dev/null
+++ b/apkverify/src/bytes_ext.rs
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * 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.
+ */
+
+//! Provides extension methods Bytes::read<T>(), which calls back ReadFromBytes::read_from_byte()
+
+use anyhow::{bail, Result};
+use bytes::{Buf, Bytes};
+use std::ops::Deref;
+
+#[derive(Clone, Debug)]
+pub struct LengthPrefixed<T> {
+    inner: T,
+}
+
+impl<T> Deref for LengthPrefixed<T> {
+    type Target = T;
+    fn deref(&self) -> &Self::Target {
+        &self.inner
+    }
+}
+
+pub trait BytesExt {
+    fn read<T: ReadFromBytes>(&mut self) -> Result<T>;
+}
+
+impl BytesExt for Bytes {
+    fn read<T: ReadFromBytes>(&mut self) -> Result<T> {
+        T::read_from_bytes(self)
+    }
+}
+
+pub trait ReadFromBytes {
+    fn read_from_bytes(buf: &mut Bytes) -> Result<Self>
+    where
+        Self: Sized;
+}
+
+impl ReadFromBytes for u32 {
+    fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
+        Ok(buf.get_u32_le())
+    }
+}
+
+impl<T: ReadFromBytes> ReadFromBytes for Vec<T> {
+    fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
+        let mut result = vec![];
+        while buf.has_remaining() {
+            result.push(buf.read()?);
+        }
+        Ok(result)
+    }
+}
+
+impl<T: ReadFromBytes> ReadFromBytes for LengthPrefixed<T> {
+    fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
+        let mut inner = read_length_prefixed_slice(buf)?;
+        let inner = inner.read()?;
+        Ok(LengthPrefixed { inner })
+    }
+}
+
+impl ReadFromBytes for Bytes {
+    fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
+        Ok(buf.slice(..))
+    }
+}
+
+fn read_length_prefixed_slice(buf: &mut Bytes) -> Result<Bytes> {
+    if buf.remaining() < 4 {
+        bail!(
+            "Remaining buffer too short to contain length of length-prefixed field. Remaining: {}",
+            buf.remaining()
+        );
+    }
+    let len = buf.get_u32_le() as usize;
+    if len > buf.remaining() {
+        bail!(
+            "length-prefixed field longer than remaining buffer. Field length: {}, remaining: {}",
+            len,
+            buf.remaining()
+        );
+    }
+    Ok(buf.split_to(len))
+}
diff --git a/apkverify/src/lib.rs b/apkverify/src/lib.rs
new file mode 100644
index 0000000..9930099
--- /dev/null
+++ b/apkverify/src/lib.rs
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * 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.
+ */
+
+//! Verifies APK/APEX signing with v2/v3 scheme
+
+mod bytes_ext;
+mod sigutil;
+mod v3;
+mod ziputil;
+
+use anyhow::Result;
+use std::path::Path;
+
+/// Verifies APK/APEX signing with v2/v3 scheme
+pub fn verify<P: AsRef<Path>>(path: P) -> Result<()> {
+    // TODO(jooyung) fallback to v2 when v3 not found
+    v3::verify(path)
+}
diff --git a/apkverify/src/sigutil.rs b/apkverify/src/sigutil.rs
new file mode 100644
index 0000000..9de794a
--- /dev/null
+++ b/apkverify/src/sigutil.rs
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * 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.
+ */
+
+//! Utilities for Signature Verification
+
+use anyhow::{anyhow, bail, Result};
+use byteorder::{LittleEndian, ReadBytesExt};
+use bytes::{Buf, Bytes};
+use std::io::{Read, Seek, SeekFrom};
+
+use crate::ziputil::zip_sections;
+
+const APK_SIG_BLOCK_MIN_SIZE: u32 = 32;
+const APK_SIG_BLOCK_MAGIC: u128 = 0x3234206b636f6c4220676953204b5041;
+
+// TODO(jooyung): introduce type
+pub const SIGNATURE_RSA_PSS_WITH_SHA256: u32 = 0x0101;
+pub const SIGNATURE_RSA_PSS_WITH_SHA512: u32 = 0x0102;
+pub const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0103;
+pub const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512: u32 = 0x0104;
+pub const SIGNATURE_ECDSA_WITH_SHA256: u32 = 0x0201;
+pub const SIGNATURE_ECDSA_WITH_SHA512: u32 = 0x0202;
+pub const SIGNATURE_DSA_WITH_SHA256: u32 = 0x0301;
+pub const SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0421;
+pub const SIGNATURE_VERITY_ECDSA_WITH_SHA256: u32 = 0x0423;
+pub const SIGNATURE_VERITY_DSA_WITH_SHA256: u32 = 0x0425;
+
+// TODO(jooyung): introduce type
+const CONTENT_DIGEST_CHUNKED_SHA256: u32 = 1;
+const CONTENT_DIGEST_CHUNKED_SHA512: u32 = 2;
+const CONTENT_DIGEST_VERITY_CHUNKED_SHA256: u32 = 3;
+#[allow(unused)]
+const CONTENT_DIGEST_SHA256: u32 = 4;
+
+pub struct SignatureInfo {
+    pub signature_block: Bytes,
+}
+
+/// Returns the APK Signature Scheme block contained in the provided file for the given ID
+/// and the additional information relevant for verifying the block against the file.
+pub fn find_signature<F: Read + Seek>(f: F, block_id: u32) -> Result<SignatureInfo> {
+    let (mut f, sections) = zip_sections(f)?;
+
+    let (signing_block, _signing_block_offset) =
+        find_signing_block(&mut f, sections.central_directory_offset)?;
+
+    // TODO(jooyung): propagate NotFound error so that verification can fallback to V2
+    let signature_scheme_block = find_signature_scheme_block(signing_block, block_id)?;
+    Ok(SignatureInfo { signature_block: signature_scheme_block })
+}
+
+fn find_signing_block<T: Read + Seek>(
+    reader: &mut T,
+    central_directory_offset: u32,
+) -> Result<(Bytes, u32)> {
+    // FORMAT:
+    // OFFSET       DATA TYPE  DESCRIPTION
+    // * @+0  bytes uint64:    size in bytes (excluding this field)
+    // * @+8  bytes payload
+    // * @-24 bytes uint64:    size in bytes (same as the one above)
+    // * @-16 bytes uint128:   magic
+    if central_directory_offset < APK_SIG_BLOCK_MIN_SIZE {
+        bail!(
+            "APK too small for APK Signing Block. ZIP Central Directory offset: {}",
+            central_directory_offset
+        );
+    }
+    reader.seek(SeekFrom::Start((central_directory_offset - 24) as u64))?;
+    let size_in_footer = reader.read_u64::<LittleEndian>()? as u32;
+    if reader.read_u128::<LittleEndian>()? != APK_SIG_BLOCK_MAGIC {
+        bail!("No APK Signing Block before ZIP Central Directory")
+    }
+    let total_size = size_in_footer + 8;
+    let signing_block_offset = central_directory_offset
+        .checked_sub(total_size)
+        .ok_or_else(|| anyhow!("APK Signing Block size out of range: {}", size_in_footer))?;
+    reader.seek(SeekFrom::Start(signing_block_offset as u64))?;
+    let size_in_header = reader.read_u64::<LittleEndian>()? as u32;
+    if size_in_header != size_in_footer {
+        bail!(
+            "APK Signing Block sizes in header and footer do not match: {} vs {}",
+            size_in_header,
+            size_in_footer
+        );
+    }
+    reader.seek(SeekFrom::Start(signing_block_offset as u64))?;
+    let mut buf = vec![0u8; total_size as usize];
+    reader.read_exact(&mut buf)?;
+    Ok((Bytes::from(buf), signing_block_offset))
+}
+
+fn find_signature_scheme_block(buf: Bytes, block_id: u32) -> Result<Bytes> {
+    // FORMAT:
+    // OFFSET       DATA TYPE  DESCRIPTION
+    // * @+0  bytes uint64:    size in bytes (excluding this field)
+    // * @+8  bytes pairs
+    // * @-24 bytes uint64:    size in bytes (same as the one above)
+    // * @-16 bytes uint128:   magic
+    let mut pairs = buf.slice(8..(buf.len() - 24));
+    let mut entry_count = 0;
+    while pairs.has_remaining() {
+        entry_count += 1;
+        if pairs.remaining() < 8 {
+            bail!("Insufficient data to read size of APK Signing Block entry #{}", entry_count);
+        }
+        let length = pairs.get_u64_le();
+        let mut pair = pairs.split_to(length as usize);
+        let id = pair.get_u32_le();
+        if id == block_id {
+            return Ok(pair);
+        }
+    }
+    // TODO(jooyung): return NotFound error
+    bail!("No APK Signature Scheme block in APK Signing Block with ID: {}", block_id)
+}
+
+pub fn is_supported_signature_algorithm(algorithm_id: u32) -> bool {
+    matches!(
+        algorithm_id,
+        SIGNATURE_RSA_PSS_WITH_SHA256
+            | SIGNATURE_RSA_PSS_WITH_SHA512
+            | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256
+            | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512
+            | SIGNATURE_ECDSA_WITH_SHA256
+            | SIGNATURE_ECDSA_WITH_SHA512
+            | SIGNATURE_DSA_WITH_SHA256
+            | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256
+            | SIGNATURE_VERITY_ECDSA_WITH_SHA256
+            | SIGNATURE_VERITY_DSA_WITH_SHA256
+    )
+}
+
+fn to_content_digest_algorithm(algorithm_id: u32) -> Result<u32> {
+    match algorithm_id {
+        SIGNATURE_RSA_PSS_WITH_SHA256
+        | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256
+        | SIGNATURE_ECDSA_WITH_SHA256
+        | SIGNATURE_DSA_WITH_SHA256 => Ok(CONTENT_DIGEST_CHUNKED_SHA256),
+        SIGNATURE_RSA_PSS_WITH_SHA512
+        | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512
+        | SIGNATURE_ECDSA_WITH_SHA512 => Ok(CONTENT_DIGEST_CHUNKED_SHA512),
+        SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256
+        | SIGNATURE_VERITY_ECDSA_WITH_SHA256
+        | SIGNATURE_VERITY_DSA_WITH_SHA256 => Ok(CONTENT_DIGEST_VERITY_CHUNKED_SHA256),
+        _ => bail!("Unknown signature algorithm: {}", algorithm_id),
+    }
+}
+
+pub fn rank_signature_algorithm(algo: u32) -> Result<u32> {
+    rank_content_digest_algorithm(to_content_digest_algorithm(algo)?)
+}
+
+fn rank_content_digest_algorithm(id: u32) -> Result<u32> {
+    match id {
+        CONTENT_DIGEST_CHUNKED_SHA256 => Ok(0),
+        CONTENT_DIGEST_VERITY_CHUNKED_SHA256 => Ok(1),
+        CONTENT_DIGEST_CHUNKED_SHA512 => Ok(2),
+        _ => bail!("Unknown digest algorithm: {}", id),
+    }
+}
diff --git a/apkverify/src/v3.rs b/apkverify/src/v3.rs
new file mode 100644
index 0000000..91043ab
--- /dev/null
+++ b/apkverify/src/v3.rs
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * 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.
+ */
+
+//! Verifies APK Signature Scheme V3
+
+// TODO(jooyung) remove this
+#![allow(dead_code)]
+
+use anyhow::{anyhow, bail, Result};
+use bytes::Bytes;
+use std::fs::File;
+use std::ops::Range;
+use std::path::Path;
+
+use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes};
+use crate::sigutil::*;
+
+pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
+
+// TODO(jooyung): get "ro.build.version.sdk"
+const SDK_INT: u32 = 31;
+
+/// Data model for Signature Scheme V3
+/// https://source.android.com/security/apksigning/v3#verification
+
+type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>;
+
+struct Signer {
+    signed_data: LengthPrefixed<Bytes>, // not verified yet
+    min_sdk: u32,
+    max_sdk: u32,
+    signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
+    public_key: LengthPrefixed<SubjectPublicKeyInfo>,
+}
+
+impl Signer {
+    fn sdk_range(&self) -> Range<u32> {
+        self.min_sdk..self.max_sdk
+    }
+}
+
+struct SignedData {
+    digests: LengthPrefixed<Vec<LengthPrefixed<Digest>>>,
+    certificates: LengthPrefixed<Vec<LengthPrefixed<X509Certificate>>>,
+    min_sdk: u32,
+    max_sdk: u32,
+    additional_attributes: LengthPrefixed<Vec<LengthPrefixed<AdditionalAttributes>>>,
+}
+
+impl SignedData {
+    fn sdk_range(&self) -> Range<u32> {
+        self.min_sdk..self.max_sdk
+    }
+}
+
+#[derive(Debug)]
+struct Signature {
+    signature_algorithm_id: u32,
+    signature: LengthPrefixed<Bytes>,
+}
+
+struct Digest {
+    signature_algorithm_id: u32,
+    digest: LengthPrefixed<Bytes>,
+}
+
+type SubjectPublicKeyInfo = Bytes;
+type X509Certificate = Bytes;
+type AdditionalAttributes = Bytes;
+
+/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the certificates
+/// associated with each signer.
+pub fn verify<P: AsRef<Path>>(path: P) -> Result<()> {
+    let f = File::open(path.as_ref())?;
+    let signature = find_signature(f, APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
+    verify_signature(&signature.signature_block)?;
+    Ok(())
+}
+
+/// Verifies the contents of the provided APK file against the provided APK Signature Scheme v3
+/// Block.
+fn verify_signature(block: &Bytes) -> Result<()> {
+    // parse v3 scheme block
+    let signers = block.slice(..).read::<Signers>()?;
+
+    // find supported by platform
+    let mut supported =
+        signers.iter().filter(|s| s.sdk_range().contains(&SDK_INT)).collect::<Vec<_>>();
+
+    // there should be exactly one
+    if supported.len() != 1 {
+        bail!("APK Signature Scheme V3 only supports one signer: {} signers found.", signers.len())
+    }
+
+    // and it should be verified
+    supported.pop().unwrap().verify()?;
+
+    Ok(())
+}
+
+impl Signer {
+    fn verify(&self) -> Result<()> {
+        // 1. Choose the strongest supported signature algorithm ID from signatures. The strength
+        //    ordering is up to each implementation/platform version.
+        let strongest: &Signature = self
+            .signatures
+            .iter()
+            .filter(|sig| is_supported_signature_algorithm(sig.signature_algorithm_id))
+            .max_by_key(|sig| rank_signature_algorithm(sig.signature_algorithm_id).unwrap())
+            .ok_or_else(|| anyhow!("No supported signatures found"))?;
+
+        // 2. Verify the corresponding signature from signatures against signed data using public key.
+        //    (It is now safe to parse signed data.)
+        verify_signed_data(&self.signed_data, strongest, &self.public_key)?;
+
+        // It is now safe to parse signed data.
+        let signed_data: SignedData = self.signed_data.slice(..).read()?;
+
+        // 3. Verify the min and max SDK versions in the signed data match those specified for the
+        //    signer.
+        if self.sdk_range() != signed_data.sdk_range() {
+            bail!("SDK versions mismatch between signed and unsigned in v3 signer block.");
+        }
+        // TODO(jooyung) 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
+        // TODO(jooyung) 5. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
+        // TODO(jooyung) 6. Verify that the computed digest is identical to the corresponding digest from digests.
+        // TODO(jooyung) 7. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
+        // TODO(jooyung) 8. If the proof-of-rotation attribute exists for the signer verify that the struct is valid and this signer is the last certificate in the list.
+        Ok(())
+    }
+}
+
+fn verify_signed_data(
+    data: &Bytes,
+    signature: &Signature,
+    public_key: &SubjectPublicKeyInfo,
+) -> Result<()> {
+    use ring::signature;
+    let (_, key_info) = x509_parser::x509::SubjectPublicKeyInfo::from_der(public_key.as_ref())?;
+    let verification_alg: &dyn signature::VerificationAlgorithm =
+        match signature.signature_algorithm_id {
+            SIGNATURE_RSA_PSS_WITH_SHA256 => &signature::RSA_PSS_2048_8192_SHA256,
+            SIGNATURE_RSA_PSS_WITH_SHA512 => &signature::RSA_PSS_2048_8192_SHA512,
+            SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256 | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256 => {
+                &signature::RSA_PKCS1_2048_8192_SHA256
+            }
+            SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512 => &signature::RSA_PKCS1_2048_8192_SHA512,
+            SIGNATURE_ECDSA_WITH_SHA256 | SIGNATURE_VERITY_ECDSA_WITH_SHA256 => {
+                &signature::ECDSA_P256_SHA256_ASN1
+            }
+            // TODO(b/190343842) not implemented signature algorithm
+            SIGNATURE_ECDSA_WITH_SHA512
+            | SIGNATURE_DSA_WITH_SHA256
+            | SIGNATURE_VERITY_DSA_WITH_SHA256 => {
+                bail!(
+                    "TODO(b/190343842) not implemented signature algorithm: {:#x}",
+                    signature.signature_algorithm_id
+                );
+            }
+            _ => bail!("Unsupported signature algorithm: {:#x}", signature.signature_algorithm_id),
+        };
+    let key = signature::UnparsedPublicKey::new(verification_alg, key_info.subject_public_key.data);
+    key.verify(data.as_ref(), signature.signature.as_ref())?;
+    Ok(())
+}
+
+// ReadFromBytes implementations
+// TODO(jooyung): add derive macro: #[derive(ReadFromBytes)]
+
+impl ReadFromBytes for Signer {
+    fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
+        Ok(Self {
+            signed_data: buf.read()?,
+            min_sdk: buf.read()?,
+            max_sdk: buf.read()?,
+            signatures: buf.read()?,
+            public_key: buf.read()?,
+        })
+    }
+}
+
+impl ReadFromBytes for SignedData {
+    fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
+        Ok(Self {
+            digests: buf.read()?,
+            certificates: buf.read()?,
+            min_sdk: buf.read()?,
+            max_sdk: buf.read()?,
+            additional_attributes: buf.read()?,
+        })
+    }
+}
+
+impl ReadFromBytes for Signature {
+    fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
+        Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
+    }
+}
+
+impl ReadFromBytes for Digest {
+    fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
+        Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
+    }
+}
diff --git a/apkverify/src/ziputil.rs b/apkverify/src/ziputil.rs
new file mode 100644
index 0000000..28ecf87
--- /dev/null
+++ b/apkverify/src/ziputil.rs
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * 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.
+ */
+
+//! Utilities for zip handling
+
+use anyhow::{bail, Result};
+use bytes::Buf;
+use std::io::{Read, Seek, SeekFrom};
+use zip::ZipArchive;
+
+const EOCD_MIN_SIZE: usize = 22;
+const EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET: usize = 16;
+const EOCD_MAGIC: u32 = 0x06054b50;
+
+#[derive(Debug, PartialEq)]
+pub struct ZipSections {
+    pub central_directory_offset: u32,
+    pub central_directory_size: u32,
+    pub eocd_offset: u32,
+    pub eocd_size: u32,
+}
+
+/// Discover the layout of a zip file.
+pub fn zip_sections<R: Read + Seek>(mut reader: R) -> Result<(R, ZipSections)> {
+    // open a zip to parse EOCD
+    let archive = ZipArchive::new(reader)?;
+    let eocd_size = archive.comment().len() + EOCD_MIN_SIZE;
+    if archive.offset() != 0 {
+        bail!("Invalid ZIP: offset should be 0, but {}.", archive.offset());
+    }
+    // retrieve reader back
+    reader = archive.into_inner();
+    // the current position should point EOCD offset
+    let eocd_offset = reader.seek(SeekFrom::Current(0))?;
+    let mut eocd = vec![0u8; eocd_size as usize];
+    reader.read_exact(&mut eocd)?;
+    if (&eocd[0..]).get_u32_le() != EOCD_MAGIC {
+        bail!("Invalid ZIP: ZipArchive::new() should point EOCD after reading.");
+    }
+    let central_directory_offset = get_central_directory_offset(&eocd)?;
+    let central_directory_size = eocd_offset as u32 - central_directory_offset;
+    Ok((
+        reader,
+        ZipSections {
+            central_directory_offset,
+            central_directory_size,
+            eocd_offset: eocd_offset as u32,
+            eocd_size: eocd_size as u32,
+        },
+    ))
+}
+
+fn get_central_directory_offset(buf: &[u8]) -> Result<u32> {
+    if buf.len() < EOCD_MIN_SIZE {
+        bail!("Invalid EOCD size: {}", buf.len());
+    }
+    Ok((&buf[EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET..]).get_u32_le())
+}
diff --git a/apkverify/tests/apkverify_test.rs b/apkverify/tests/apkverify_test.rs
new file mode 100644
index 0000000..03db61a
--- /dev/null
+++ b/apkverify/tests/apkverify_test.rs
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * 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.
+ */
+
+use apkverify::verify;
+
+#[test]
+fn test_verify_v3() {
+    assert!(verify("tests/data/test.apex").is_ok());
+}
diff --git a/apkverify/tests/data/README.md b/apkverify/tests/data/README.md
new file mode 100644
index 0000000..df40af6
--- /dev/null
+++ b/apkverify/tests/data/README.md
@@ -0,0 +1,12 @@
+test.apex is copied from ADBD apex built in AOSP.
+
+```sh
+$ apksigner verify -v test.apex
+Verifies
+Verified using v1 scheme (JAR signing): false
+Verified using v2 scheme (APK Signature Scheme v2): false
+Verified using v3 scheme (APK Signature Scheme v3): true
+Verified using v4 scheme (APK Signature Scheme v4): false
+Verified for SourceStamp: false
+Number of signers: 1
+```
\ No newline at end of file
diff --git a/apkverify/tests/data/test.apex b/apkverify/tests/data/test.apex
new file mode 100644
index 0000000..0e6a576
--- /dev/null
+++ b/apkverify/tests/data/test.apex
Binary files differ
diff --git a/microdroid_manager/Android.bp b/microdroid_manager/Android.bp
index 0ea5d87..a082beb 100644
--- a/microdroid_manager/Android.bp
+++ b/microdroid_manager/Android.bp
@@ -10,6 +10,7 @@
     prefer_rlib: true,
     rustlibs: [
         "libanyhow",
+        "libapkverify",
         "libkernlog",
         "liblibc",
         "liblog_rust",
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index 2586737..fa456e8 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -17,7 +17,8 @@
 mod ioutil;
 mod metadata;
 
-use anyhow::{anyhow, bail, Result};
+use anyhow::{anyhow, bail, Context, Result};
+use apkverify::verify;
 use log::{error, info, warn};
 use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
 use rustutils::system_properties::PropertyWatcher;
@@ -30,12 +31,19 @@
 use vsock::VsockStream;
 
 const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
+const DM_MOUNTED_APK_PATH: &str = "/dev/block/mapper/microdroid-apk";
 
 fn main() -> Result<()> {
     kernlog::init()?;
     info!("started.");
 
     let metadata = metadata::load()?;
+
+    if let Err(err) = verify_payloads() {
+        error!("failed to verify payload: {}", err);
+        // TODO(jooyung): should stop the boot process if verification fails
+    }
+
     if !metadata.payload_config_path.is_empty() {
         let config = load_config(Path::new(&metadata.payload_config_path))?;
 
@@ -56,6 +64,19 @@
     Ok(())
 }
 
+// TODO(jooyung): v2/v3 full verification can be slow. Consider multithreading.
+fn verify_payloads() -> Result<()> {
+    // We don't verify APEXes since apexd does.
+
+    // should wait APK to be dm-verity mounted by apkdmverity
+    ioutil::wait_for_file(DM_MOUNTED_APK_PATH, WAIT_TIMEOUT)?;
+    verify(DM_MOUNTED_APK_PATH).context(format!("failed to verify {}", DM_MOUNTED_APK_PATH))?;
+
+    info!("payload verification succeeded.");
+    // TODO(jooyung): collect public keys and store them in instance.img
+    Ok(())
+}
+
 fn load_config(path: &Path) -> Result<VmPayloadConfig> {
     info!("loading config from {:?}...", path);
     let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)?;
diff --git a/virtualizationservice/src/payload.rs b/virtualizationservice/src/payload.rs
index 338e9a2..75ba6c7 100644
--- a/virtualizationservice/src/payload.rs
+++ b/virtualizationservice/src/payload.rs
@@ -85,7 +85,12 @@
         version: 1,
         apexes: apexes
             .iter()
-            .map(|apex| ApexPayload { name: apex.name.clone(), ..Default::default() })
+            .enumerate()
+            .map(|(i, apex)| ApexPayload {
+                name: apex.name.clone(),
+                partition_name: format!("microdroid-apex-{}", i),
+                ..Default::default()
+            })
             .collect(),
         apk: Some(ApkPayload {
             name: "apk".to_owned(),