add apkverify lib to verify APK/APEX signatures

`verify(apk)` is an entry for a Signature Verification of APK/APEX.

For now, it only parses signing block and does barely no verification
yet. Verification will be implemented in follow-up changes.

Cargo.toml is added for `cargo test`, but will be removed when
Android.bp is added.

Bug: 190343842
Test: cargo test
Change-Id: Ib95128e021e8da50a015d302c9c394a8b5a98957
diff --git a/apkverify/Cargo.toml b/apkverify/Cargo.toml
new file mode 100644
index 0000000..589056b
--- /dev/null
+++ b/apkverify/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "apkverify"
+version = "0.1.0"
+authors = ["Jooyung Han <jooyung@google.com>"]
+edition = "2018"
+
+[dependencies]
+anyhow = { path = "../../../../external/rust/crates/anyhow" }
+bytes = { path = "../../../../external/rust/crates/bytes" }
+byteorder = { path = "../../../../external/rust/crates/byteorder" }
+zip = { version = "0.5", path = "../../../../external/rust/crates/zip" }
diff --git a/apkverify/src/bytes_ext.rs b/apkverify/src/bytes_ext.rs
new file mode 100644
index 0000000..61848ad
--- /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)]
+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..9ea0e14
--- /dev/null
+++ b/apkverify/src/lib.rs
@@ -0,0 +1,30 @@
+/*
+ * 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;
+
+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..de3d0dd
--- /dev/null
+++ b/apkverify/src/sigutil.rs
@@ -0,0 +1,184 @@
+/*
+ * 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;
+use std::io::Read;
+use zip::spec::CentralDirectoryEnd as EndOfCentralDirectory;
+
+const APK_SIG_BLOCK_MIN_SIZE: u32 = 32;
+const APK_SIG_BLOCK_MAGIC: u128 = 0x3234206b636f6c4220676953204b5041;
+
+// TODO(jooyung): introduce type
+const SIGNATURE_RSA_PSS_WITH_SHA256: u32 = 0x0101;
+const SIGNATURE_RSA_PSS_WITH_SHA512: u32 = 0x0102;
+const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0103;
+const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512: u32 = 0x0104;
+const SIGNATURE_ECDSA_WITH_SHA256: u32 = 0x0201;
+const SIGNATURE_ECDSA_WITH_SHA512: u32 = 0x0202;
+const SIGNATURE_DSA_WITH_SHA256: u32 = 0x0301;
+const SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0421;
+const SIGNATURE_VERITY_ECDSA_WITH_SHA256: u32 = 0x0423;
+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 signing_block_offset: u32,
+    pub signature_block: Bytes,
+    pub eocd_offset: u32,
+    pub eocd: EndOfCentralDirectory,
+}
+
+/// 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 + io::Seek>(f: &mut F, block_id: u32) -> Result<SignatureInfo> {
+    let (eocd, eocd_offset) = EndOfCentralDirectory::find_and_parse(f)?;
+    if eocd.disk_number != eocd.disk_with_central_directory {
+        bail!("Support for multi-disk files is not implemented");
+    }
+    // TODO(jooyung): reject zip64 file
+    let (signing_block, signing_block_offset) =
+        find_signing_block(f, eocd.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 {
+        signing_block_offset,
+        signature_block: signature_scheme_block,
+        eocd_offset: eocd_offset as u32,
+        eocd,
+    })
+}
+
+fn find_signing_block<T: Read + io::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(io::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(io::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(io::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 {
+    match 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 => true,
+        _ => false,
+    }
+}
+
+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..75551db
--- /dev/null
+++ b/apkverify/src/v3.rs
@@ -0,0 +1,183 @@
+/*
+ * 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
+
+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::{find_signature, is_supported_signature_algorithm, rank_signature_algorithm};
+
+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<Bytes>,
+}
+
+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
+    }
+}
+
+struct Signature {
+    signature_algorithm_id: u32,
+    signature: LengthPrefixed<Bytes>,
+}
+
+struct Digest {
+    signature_algorithm_id: u32,
+    digest: LengthPrefixed<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 mut f = File::open(path.as_ref())?;
+    let signature = find_signature(&mut 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_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_data(_data: &Bytes, _signature: &Signature, _public_key: &Bytes) -> Result<()> {
+    // TODO(jooyung): verify signed_data with signature/public key
+    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/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