diff --git a/.gitignore b/.gitignore index dd38009..b720faa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ +# macOS Finder metadata +.DS_Store .idea/ *.iml .DS_Store -.agent/ +.agent/ \ No newline at end of file diff --git a/niap-cc/niap-android-cert-ext/.gitignore b/niap-cc/niap-android-cert-ext/.gitignore new file mode 100644 index 0000000..8af82cb --- /dev/null +++ b/niap-cc/niap-android-cert-ext/.gitignore @@ -0,0 +1,42 @@ +# Project exclude paths + +# Packaging output +dist/ + +# Gradle +.gradle/ +.kotlin/ +.claude/ +build/ + +# IntelliJ IDEA +.idea/ +*.iml + +# Android Studio +.idea/ +local.properties + +# macOS +.DS_Store + +# Log files +*.log + +# Java class files +*.class + +# Generated files +**/build/ + +# Keystore files +*.jks + +# Environment variables +.env +adb_key.* +*.hprof +bin/ + +# TLS lab reproduction harness generated artifacts +tools/tls-lab-repro/out/ diff --git a/niap-cc/niap-android-cert-ext/AGENTS.md b/niap-cc/niap-android-cert-ext/AGENTS.md new file mode 100644 index 0000000..d40a7aa --- /dev/null +++ b/niap-cc/niap-android-cert-ext/AGENTS.md @@ -0,0 +1,114 @@ +# Project Knowledge for Agent Execution + +This document contains architectural context, workflows, and guidelines for LLM agents to develop, run, and verify security test cases in this repository. + +--- + +## 1. Starting and Stopping TestBed Core (MCP Server) +This project integrates with a desktop-based automation runner and MCP server hosted by the `testbed-core` application on port `11452` (`localhost:11452`). The server must be active for the agent to interface with physical devices or emulators. + +### How to Start the Server +Open a separate terminal window, navigate to the `testbed-core` repository directory, and start the desktop program: + +```bash +cd ../testbed-core +./gradlew :composeApp:run +``` + +### How to Stop (Kill) the Server +To prevent port collisions, dual-instance conflicts, or general socket errors (`Address already in use`), identify and force-kill any running processes holding port `11452`. It is recommended to perform this cleanup before launching automated runs: + +```bash +# Force-kill processes listening on port 11452 +lsof -t -i :11452 | xargs kill -9 +``` + +--- + +## 2. Referencing Security Documents (MDFPP-CC) +To ensure test accuracy and compliance with security requirements, review the target criteria documented under the `docs/` folder (such as [FIA_XCU_EXT.1.md](docs/FIA_XCU_EXT.1.md) or related Common Criteria files). + +If the document references are empty or need to be synchronized with the remote requirements repository, run: + +```bash +git submodule update --init --recursive +``` + +--- + +## 3. Document-Driven Test Development (Supreme Directive) +The core operating principle of this project is **strict adherence of test implementations to the security requirements documents**: +* Before generating or modifying any JUnit test suites, the LLM agent **must** read the relevant functional requirements and test case evaluation criteria from the target files in the `docs/` folder. +* The written JUnit test assertions must align perfectly with the Pass/Fail decision boundaries defined in the criteria. + +--- + +## 4. Test Development and Execution Workflow +When developing and running security test suites, follow this structured workflow (refer to the main tool references for deeper API mechanics): + +1. **Requirements Reference**: Retrieve target specifications from the target documents in `docs/`. +2. **Test Generation**: Author the Kotlin/Java test suites inside the `agent-test` module (e.g., under `org.example.plugin.fiax509`). Ensure all log entries adhere to the logging design patterns (using helpers like `logi` or `logp`). +3. **Compilation and Loading**: + * Compile the JUnit plugin JAR: + ```bash + ./gradlew :agent-test:jar + ``` + * Invoke the `junit_test_reload` MCP tool to notify the server and load the newly compiled test definitions. +4. **Execution and Monitoring**: + * Trigger execution using the `junit_test_execute` MCP tool (passing target class and method arguments). + * Poll `junit_test_receive` to stream log messages in real-time and capture structural exit states (Pass/Fail reports and stack traces). + +--- + +## 5. Automation MCP Tools & Specifications +The following MCP tools are exposed by the `testbed-core` interface for automated workflow execution: + +* **`junit_test_reload`**: Reloads and updates the JUnit plugin JAR context on the server. +* **`junit_test_list`**: Returns a list of all current tests loaded in the environment (as a JSON array). +* **`junit_test_execute`**: Accepts a class name and optional method identifier to begin execution. +* **`junit_test_receive`**: Retrieves current logs (`status: "Running"`) or finalized structural details (`status: "Finished"`, Pass/Fail indicator, exception details). + +> [!NOTE] +> `junit_test_receive` supports active streaming. For long-running operations (e.g., processes taking over 2 minutes), safely poll `junit_test_receive` to track task execution progress. + +--- + +## 6. Utilizing Timers for Passive Wait States +When the agent is required to enter a wait state (e.g. waiting for a compilation step, a background script, or multi-stage device deployments to complete), **always schedule a 60-second timer using the `schedule` tool** rather than generating repeated active prompt-and-response loops. This saves token budgets and resources. + +--- + +## 7. Configuring the Local EST Test Server (libest) +For testing security certificate acquisitions (EST protocol) and client-side mutual TLS actions, run a local mock container based on **Cisco libest** and NGINX (configured under `est-server/`). +* See [est-server/README.md](est-server/README.md) for full docker deployment guidelines. +* Ensure the environment signature algorithm is configured to **SHA-384** (via `EST_CERT_PROFILE=niap`) to properly satisfy Common Criteria / NIAP verification criteria during automated runs. + +--- + +## 8. Lesson Learned: Never Depend on Non-SDK (Hidden) Platform APIs in App-Level Code + +**Incident (2026-12, lab resubmission work)**: To read stapled OCSP responses, the app-level library reflected on the *concrete* platform session class (`session.javaClass.getMethod("getStatusResponses")`, which resolves to the hidden `com.android.org.conscrypt.Java7ExtendedSSLSession`). All JVM unit tests passed, but on a stock-policy Android 16 device the call was denied by hidden-API enforcement (`hiddenapi: ... api=blocked ... using reflection: denied`), the exception was swallowed, and every TLS connection failed with a misleading "server did not staple an OCSP response" error. Earlier development devices most likely had hidden-API enforcement relaxed (`hidden_api_policy`), which hides this class of bug (for example, the older `NiapKeyManager` reflection into `android.security.net.config.RemotePrivateKey` can only work in that state). Evaluation labs test on stock-policy devices. + +**Rules for code that must run on stock devices (App-Level track: `cert-lib`, `cert-manager`, `validator-test-app`, `cert-test-app`)**: +1. **Public SDK APIs only.** Do not use `Class.forName("com.android.โ€ฆ")`, `com.android.org.conscrypt.*`, `android.security.net.config.*`, `getDeclaredMethod` / `getDeclaredField` / `setAccessible` against platform classes, or any other non-SDK member. +2. **If reflection is unavoidable** (e.g. to stay compatible with older API levels), look the member up on the **public declaring type** (e.g. `ExtendedSSLSession::class.java.getMethod("getStatusResponses")`), never on `obj.javaClass` of a platform-provided object. +3. **Never swallow API-access failures** (`NoSuchMethodException`/`NoSuchMethodError`, `LinkageError`, `SecurityException`, hidden-API denials). Fail closed with a distinct, explicit error message so the real cause is visible. +4. **Verification devices must use default hidden-API enforcement.** Before any device verification, check: + ```bash + adb shell settings get global hidden_api_policy # must print: null + adb shell settings get global hidden_api_policy_pre_p_apps # must print: null + adb shell settings get global hidden_api_policy_p_apps # must print: null + ``` + If any of them was relaxed for debugging, restore it with `adb shell settings delete global ` before testing. Never relax it on a device used for verification or for producing evidence. +5. **Scan for hidden-API usage in every device run.** Collect the app's `hiddenapi` log lines (e.g. `adb logcat -d | grep -i hiddenapi | grep -E "com.example.niap|com.android.niap"`). Any `denied` line is a test failure; `Accessing hidden ...` warnings must be removed before submission. +6. **JVM unit tests are not enough.** They do not enforce hidden-API restrictions or use the platform TLS stack. Any change touching platform TLS/crypto objects (`SSLSession`, `SSLSocket`, `SSLEngine`, JCA providers, KeyStore) is only "done" after it has been verified on a stock-policy device (e.g. with `tools/tls-lab-repro`). + +> Platform-private APIs are only acceptable in code that ships inside the platform image itself (platform builds / platform-signed privileged components), never in this app-level library or its apps. + +**Hidden-API guard**: Two automated checks enforce these rules across the four app-level modules (`cert-lib`, `cert-manager`, `validator-test-app`, `cert-test-app`). Run the static source scanner with `tools/check-no-hidden-api.sh` (per-line exemptions require `// hidden-api-check: allow ` and are printed in the report), and run Android Lint with `PrivateApi`/`DiscouragedPrivateApi`/`SoonBlockedPrivateApi`/`BlockedPrivateApi` set to errors via: +```bash +./gradlew --console=plain -PskipTestbedCopy=true \ + :cert-lib:lintDebug :validator-test-app:lintStrictDebug \ + :cert-manager:lintDebug :cert-test-app:lintDebug +``` +`tools/package-submission.sh` runs both guards automatically and aborts before building artifacts if either fails. diff --git a/niap-cc/niap-android-cert-ext/LICENSE b/niap-cc/niap-android-cert-ext/LICENSE new file mode 100644 index 0000000..4a5bca6 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. for the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. for the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. for the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 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. diff --git a/niap-cc/niap-android-cert-ext/README.md b/niap-cc/niap-android-cert-ext/README.md new file mode 100644 index 0000000..18a880d --- /dev/null +++ b/niap-cc/niap-android-cert-ext/README.md @@ -0,0 +1,424 @@ +# NIAP Android Certificate Extension & Lifecycle Validator + +A comprehensive Android security framework and service designed to enforce strict **NIAP (National Information Assurance Partnership)** Common Criteria requirements for TLS transport security, X.509 certificate validation, and secure certificate lifecycle management. + +For formal evaluated-configuration guidance (AGD), see [docs/AGD-TLS-guidance.md](docs/AGD-TLS-guidance.md). + +--- + +## ๐Ÿ“– Background & Problem + +By default, Android's core TLS/security provider (**Conscrypt**) is optimized for general web traffic and does not enforce the stringent constraints defined in the [NIAP X.509 Functional Package (FIA_X509_EXT.1 / FIA_XCU_EXT.1)](https://www.niap-ccevs.org/static_html/protection-profile/511/Functional%20Package%20for%20X.509_v1.0.html) and TLS client requirements (`FCS_TLSC_EXT.1`). For example: +* It permits signature algorithms and key lengths weaker than SHA-384 / 3072-bit RSA. +* It does not mandate essential extensions like Authority Key Identifier (AKID), Subject Key Identifier (SKID), or specific Key Usages. +* It does not strictly restrict wildcard SAN alignments on critical Top-Level Domains (TLDs). +* It advertises and negotiates unapproved TLS 1.3 cipher suites (such as `TLS_CHACHA20_POLY1305_SHA256`) and does not hard-fail on missing or invalid stapled OCSP responses. + +This framework addresses these gaps by providing: +1. **A strict validation and TLS enforcement layer** (`cert-lib`) that enforces protocol versions, cipher suite allowlists, Extended Master Secret (EMS), X.509 profile checks, and hard-fail offline stapled OCSP revocation checking. +2. **A secure, hardware-backed certificate manager service** (`cert-manager`) supporting standardized protocols like **EST (Enrollment over Secure Transport)** for acquiring and managing enterprise/government-issued credentials while keeping private key material safely isolated in secure hardware. + +--- + +## ๐Ÿ›๏ธ System Architecture & Module Layout + +The project is structured into modular units, separating core validator logic, stateful lifecycle services, interactive test applications, automated device-level test runners, and evaluation tooling. + +``` +niap-android-cert-ext/ +โ”œโ”€โ”€ cert-lib/ # Core Android library (TLS/X.509 Validator & Client Manager API) +โ”œโ”€โ”€ cert-manager/ # Foreground Service & signing oracle (EST client & KeyStore engine) +โ”œโ”€โ”€ validator-test-app/ # WorkManager-based network testing application (strict/relaxed flavors) +โ”œโ”€โ”€ cert-test-app/ # Interactive Jetpack Compose application for manual verification +โ”œโ”€โ”€ agent-test/ # JUnit automated test suites designed for TestBed Core +โ”œโ”€โ”€ est-server/ # Pre-configured local EST test environment (Cisco libest & NGINX) +โ”œโ”€โ”€ tools/ +โ”‚ โ”œโ”€โ”€ tls-lab-repro/ # Host-side OpenSSL + adb TLS/OCSP/mTLS/resumption test harness +โ”‚ โ””โ”€โ”€ package-submission.sh # Reproducible NIAP submission packaging script +โ””โ”€โ”€ docs/ + โ””โ”€โ”€ AGD-TLS-guidance.md # Administrator / Developer Guidance (AGD) for evaluated TLS use +``` + +### 1. Core Validation & TLS Enforcement (`cert-lib`) +The foundation of the project, providing strict TLS and X.509 enforcement: +* **`NiapTlsPolicy`**: Single source of truth for the built-in NIAP-approved cipher suite allowlist (`APPROVED_SUITES`), protocol version selection, and XML allowlist validation. +* **`VerifiableSSLSocketFactory`**: Wraps the platform Conscrypt `SSLSocketFactory` to enforce protocol versions, cipher suite allowlists (including wire-level `ServerHello` validation for TLS 1.3), and mandatory Extended Master Secret (EMS) on TLS 1.2. +* **`NiapCertValidator`**: Processes certificate chains and verifies signature algorithms, key strengths, basic constraints, required EKUs, mandatory extensions, and wildcard SAN constraints. +* **`NiapX509TrustManager` & `OcspStapleValidator`**: A session-aware `X509ExtendedTrustManager` that wraps platform/custom trust managers, runs `NiapCertValidator` checks, and enforces hard-fail offline stapled OCSP verification (RFC 6066 / `FIA_X509_EXT.1.1`). +* **`NiapCertHelper`**: High-level orchestrator that parses policy configuration from XML resources, caches `SSLContext` / `SSLSocketFactory` stacks for session resumption, and configures `OkHttpClient` and `HttpsURLConnection` (including mutual TLS via `X509KeyManager`). +* **`NiapCertManager` & `NiapKeyManager`**: Client-side integration API that enables consumer applications to use hardware-backed cryptographic identities from the `cert-manager` service via standard JCA interfaces without handling raw private keys. + +### 2. Lifecycle Service (`cert-manager`) +A background service package configured as a Foreground Service (`NiapCertService`) that acts as a secure certificate repository and remote signing oracle: +* **Protocol-Agnostic Acquisition**: Implements key generation (ECDSA P-384 / RSA 3072) inside the secure **Android KeyStore** and requests certificates from external servers via **EST (RFC 7030)**. +* **Remote Signing Provider**: Exposes a custom `RemoteSigningProvider` and standard AIDL service interface (`INiapCertManager.aidl`). When a client app makes mTLS calls, cryptographic signatures are delegated to the service via a secure Binder IPC channel. **Private key material never leaves the secure service context.** +* **Validation & Storage**: Validates incoming certificates against local policies before writing them into the secure KeyStore engine. + +### 3. Interactive Client (`cert-test-app`) +A Jetpack Compose-based user application created for developers and evaluators to: +* Configure connection settings (EST endpoints, target mTLS servers, CA credentials). +* Trigger interactive certificate enrollment, view real-time state machines, inspect cryptographic metadata (Subject, Issuer, Serial, Signature Algorithm, Validity). +* Test live mTLS endpoints and view detailed client logs immediately. + +### 4. Automated Testbed (`agent-test`) +A JUnit test suite designed to register and execute device-level test cases in collaboration with the **TestBed Core** automation system: +* **`FiaX509ValidatorTest`** (`NiapValidatorTest` class): Installs strict/relaxed flavors of `validator-test-app` and tests endpoints to verify that non-compliant certificates are blocked in strict mode and accepted in relaxed mode. +* **`CertManagerTest`**: Automates full-cycle local EST enrollment, sets up ADB reverse tunnels, validates state transitions, and conducts mutual TLS authentications against local mock services. + +--- + +## ๐Ÿ”’ TLS, Revocation, Mutual TLS & Session Resumption Policy + +### Platform-Version-Dependent Behavior (API โ‰ค 36 vs. API 37+) + +Device verification on Android 16 (API 36) proved that on **API 36 and below** there is no public SDK API for applications to read stapled OCSP responses from an `SSLSession`: the concrete Conscrypt session method is a blocked hidden API, and `javax.net.ssl.ExtendedSSLSession.getStatusResponses()` does not exist at runtime (it is public API only starting in **API 37** per the Android SDK API-version metadata). + +Because TLS 1.3 encrypts the server certificate and `status_request` extensions, an app-level library cannot read a TLS 1.3 stapled OCSP response off the wire without platform API support. `cert-lib` therefore adapts its protocol posture based on whether `ExtendedSSLSession.getStatusResponses()` is available at runtime: + +| Capability / Behavior | Android 16 and below (API โ‰ค 36) | Android 17 and above (API 37+)* | +|---|---|---| +| **Protocols offered** | **TLS 1.2 only**, regardless of ``. TLS 1.3 is not offered. | **TLS 1.2 + TLS 1.3** by default (`false`), or **TLS 1.2 only** when `true`. | +| **How the OCSP staple is read** | Parsed from the plaintext TLS 1.2 `CertificateStatus` handshake message on the wire (`SSLSocket`). | Read via the public `javax.net.ssl.ExtendedSSLSession.getStatusResponses()` API. | +| **TLS 1.3-only servers** | **Unreachable** โ€” handshake fails (`protocol_version`) because TLS 1.3 is not offered. | **Reachable** (subject to NIAP cipher allowlist and valid stapled OCSP response). | +| **Cipher suite advertisement** | Only allowlisted TLS 1.2 suites are advertised; no TLS 1.3 suites (including `TLS_CHACHA20_POLY1305_SHA256`) are advertised at all. | When TLS 1.3 is enabled, platform Conscrypt always advertises `TLS_AES_128_GCM_SHA256`, `TLS_AES_256_GCM_SHA384`, and `TLS_CHACHA20_POLY1305_SHA256`; `cert-lib` rejects any non-allowlisted suite selected by the server. | +| **`SSLEngine`-based connections** | **Fail closed** โ€” cannot read staples without the public platform API. | Supported via `ExtendedSSLSession.getStatusResponses()`. | +| **Revocation policy** | OCSP stapling only, hard-fail (no CRL / online OCSP fallback). | OCSP stapling only, hard-fail (no CRL / online OCSP fallback). | + +*\*API 37+ behavior has yet to be verified on an Android 17 device.* + +> **Need TLS 1.3 with mandatory OCSP stapling on API โ‰ค 36?** +> The **OS-integrated (platform) version** is required on Android 16 and below, because only platform code can access the encrypted TLS 1.3 stapled OCSP response inside the TLS stack. + +### TLS Protocol & Cipher Suite Enforcement +* **Enabled Protocols**: On **API 37+**, **TLS 1.3** and **TLS 1.2** are enabled by default (`false`), and setting `true` pins connections strictly to **TLS 1.2**. On **API โ‰ค 36**, `cert-lib` automatically restricts connections to **TLS 1.2 only** regardless of `` so that stapled OCSP responses can be read from the plaintext TLS 1.2 `CertificateStatus` message. TLS 1.1 and earlier are disabled by the Android platform (`minSdk = 32+`). +* **Built-in Cipher Allowlist (`NiapTlsPolicy.APPROVED_SUITES`)**: The AEAD subset of the NIST SP 800-52 Rev. 2 recommended cipher suites supported by the platform TLS stack (AES-CCM suites are also SP 800-52 Rev. 2-approved but are not offered by the platform TLS stack; ChaCha20-Poly1305 is not a FIPS-approved algorithm and is therefore refused): + * **TLS 1.3** *(API 37+ only)*: `TLS_AES_128_GCM_SHA256` (`0x1301`), `TLS_AES_256_GCM_SHA384` (`0x1302`) + * **TLS 1.2**: `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` (`0xC02B`), `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256` (`0xC02F`), `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` (`0xC02C`), `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` (`0xC030`) +* **XML Allowlist Narrowing**: `` may only narrow `NiapTlsPolicy.APPROVED_SUITES` further (for example, AES-256-only if an evaluation requires it). Omitting it or leaving it empty applies the full built-in allowlist. Specifying any unknown or non-approved cipher suite fails configuration loading (`NiapCertHelper.fromConfig()`) with `IllegalArgumentException`. +* **TLS 1.2 Enforcement**: The configured TLS 1.2 allowlist is applied directly to the socket and `ConnectionSpec`, so only approved TLS 1.2 suites are advertised in `ClientHello`. +* **TLS 1.3 Platform Limitation (API 37+)**: On API 37+ when TLS 1.3 is enabled, the platform TLS stack (Conscrypt) always advertises `TLS_AES_128_GCM_SHA256`, `TLS_AES_256_GCM_SHA384`, and `TLS_CHACHA20_POLY1305_SHA256` in `ClientHello`; applications cannot remove individual TLS 1.3 suites from `ClientHello`. To enforce the NIAP allowlist, `VerifiableSSLSocketFactory` inspects the `ServerHello` on the wire and immediately aborts the handshake (sending a fatal `handshake_failure` alert and throwing `SSLHandshakeException`) if the server selects any suite outside the allowlist. Thus, `TLS_CHACHA20_POLY1305_SHA256` may be advertised in `ClientHello` on API 37+ when TLS 1.3 is enabled, but it is **never negotiated**. On API โ‰ค 36 (or on API 37+ with `true`), TLS 1.3 is not offered and no TLS 1.3 suites appear in `ClientHello`. +* **Extended Master Secret (EMS, RFC 7627)**: Required on all TLS 1.2 connections by default (`true`). If a TLS 1.2 `ServerHello` omits the EMS extension (`0x0017`), the handshake is rejected with a fatal alert and `SSLHandshakeException`. + +### Certificate Revocation (Hard-Fail OCSP Stapling Only) +* **Mechanism**: Offline **OCSP stapling only** (RFC 6066 `status_request`). `cert-lib` performs **no CRL checks**, **no active OCSP network fetching**, and **no outbound network access** for revocation (`PKIXRevocationChecker.Option.ONLY_END_ENTITY` and `NO_FALLBACK`). +* **Hard-Fail Default (No Override)**: `NiapX509TrustManager` + `OcspStapleValidator` unconditionally reject connections if a stapled OCSP response is missing, revoked, unknown, stale/expired, malformed, or fails signature/chain verification. On API โ‰ค 36, staples are read from the plaintext TLS 1.2 `CertificateStatus` message for `SSLSocket` connections (and `SSLEngine` connections fail closed); on API 37+, staples are read via `ExtendedSSLSession.getStatusResponses()`. There is no developer flag to disable or soft-fail stapled OCSP checking. +* **OCSP Signature & Signer Key Rules (`FIA_X509_EXT.1.1`)**: + * Permitted OCSP response signature algorithms: `ecdsa-with-SHA384` (`1.2.840.10045.4.3.3`), `ecdsa-with-SHA512` (`1.2.840.10045.4.3.4`), `sha384WithRSAEncryption` (`1.2.840.113549.1.1.12`), `sha512WithRSAEncryption` (`1.2.840.113549.1.1.13`). + * Permitted OCSP signer keys (embedded responder certificate or issuing CA): **EC P-384 / P-521** or **RSA โ‰ฅ 3072 bits**. +* **Resumed Sessions**: Resumed TLS sessions do not re-invoke `checkServerTrusted`, so certificate and stapled OCSP checks execute on full handshakes only. +* **Operational Note**: Servers whose CA does not provide OCSP (for example, Let's Encrypt discontinued OCSP service in 2025) or servers that do not staple a compliant OCSP response cannot be used with `cert-lib`. + +### Mutual TLS (Client Certificate Authentication) +* **Direct `X509KeyManager` Support**: Pass an `X509KeyManager` to the `NiapCertHelper` overloads (`openConnection`, `createSSLSocketFactory`, or `configureOkHttp`). +* **Hardware-Backed Service Credentials**: Use `NiapCertManager.getSslSocketFactory(alias, trustedCaPem, requireExtendedMasterSecret)` (or pass `certManager.getKeyManager(alias)` to `NiapCertHelper`) for keys held by `cert-manager`. Both paths enforce the full NIAP TLS, cipher, EMS, and OCSP stapling policy. +* **Deprecation**: `NiapCertManager.getSslContext()` is `@Deprecated` because a raw `SSLContext` cannot enforce socket-level cipher allowlists, protocol pinning, or EMS. + +### TLS Session Resumption +* Handled by the platform TLS stack (TLS 1.2 session tickets / session IDs on all supported API levels; TLS 1.3 PSK / `NewSessionTicket` on API 37+ when TLS 1.3 is enabled) whenever the same `NiapCertHelper` instance is reused. +* `NiapCertHelper` caches one `SSLContext`, `NiapX509TrustManager`, and `VerifiableSSLSocketFactory` per `(TrustAnchorOptions, SHA-256(anchor certs), keyManager identity, requireEms)`. +* Calling `NiapCertHelper.resetInstance()` clears the cache and destroys the shared session cache; avoid calling it between requests when session resumption is expected. + +### Error Reporting +Handshake and validation failures surface as `javax.net.ssl.SSLHandshakeException` (wrapping `CertificateException` / `CertPathValidatorException` for certificate and OCSP failures) with diagnostic messages such as: +* TLS 1.3-only server on API โ‰ค 36: + `javax.net.ssl.SSLHandshakeException: ... TLSV1_ALERT_PROTOCOL_VERSION` (TLS 1.2 only is offered when `ExtendedSSLSession.getStatusResponses()` is unavailable) +* Platform OCSP staple API unavailable (e.g. `SSLEngine` on API โ‰ค 36): + `Revocation status unavailable: platform API (ExtendedSSLSession.getStatusResponses) unavailable` (fail-closed) +* Cipher suite rejected (API 37+ TLS 1.3): + `javax.net.ssl.SSLHandshakeException: Server selected cipher suite 0x1303 (TLS_CHACHA20_POLY1305_SHA256), which is not in the NIAP allowlist` +* Missing TLS 1.2 Extended Master Secret: + `javax.net.ssl.SSLHandshakeException: TLS ServerHello (0x303) omitted mandatory extended_master_secret (EMS) extension` +* Missing OCSP staple: + `Revocation status unavailable: server did not staple an OCSP response (OCSP stapling is required)` +* Revoked or invalid OCSP staple: + `Stapled OCSP verification failed (REVOKED): ...` +* Non-compliant OCSP signature algorithm: + `OCSP response signature algorithm OID 1.2.840.10045.4.3.2 is not permitted by FIA_X509_EXT.1.1 (allowed: [1.2.840.10045.4.3.3, 1.2.840.10045.4.3.4, 1.2.840.113549.1.1.12, 1.2.840.113549.1.1.13])` + +--- + +## โš™๏ธ Declarative Security Policy Configuration + +Validation and TLS rules are loaded declaratively from `res/xml/niap_security_config.xml` (application resources override the library default in `cert-lib/src/main/res/xml/niap_security_config.xml`). + +```xml + + + + true + + + + *.COM + *.NET + *.ORG + *.GOV + *.EDU + + + + + TLS_AES_128_GCM_SHA256 + TLS_AES_256_GCM_SHA384 + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + + + + BOTH_CA + + + false + + + true + + + true + + + true + + + serverAuth + + + true + +``` + +> **Note on `` and ``:** +> * On **API 37+**, `false` enables both **TLS 1.3** and **TLS 1.2**; set it to `true` to pin connections to **TLS 1.2 only** and prevent TLS 1.3 suites from being advertised in `ClientHello`. On **API โ‰ค 36**, `cert-lib` always runs **TLS 1.2 only** regardless of `` (see *Platform-Version-Dependent Behavior* above). +> * `` defaults to `true` and must remain `true` in evaluated configurations to enforce RFC 7627 EMS on TLS 1.2 handshakes. + +--- + +## ๐Ÿš€ Getting Started + +### Prerequisites +* **JDK 17** configured in your development environment. +* **Android SDK** with Platform-34 tools. +* **OpenSSL 3.x / 4.x**, `adb`, `perl`, and `python3` (if running `tools/tls-lab-repro`). +* **Docker** & **Docker Compose** (if running the local mock EST server). + +### ๐Ÿ› ๏ธ 1. Building the Modules + +To run `cert-lib` unit tests and build the release AAR: +```bash +./gradlew :cert-lib:testDebugUnitTest :cert-lib:assembleRelease +``` + +To build the background service and test applications: +```bash +# Background lifecycle service +./gradlew :cert-manager:assembleDebug + +# Validator test app (strict & relaxed flavors) +./gradlew :validator-test-app:assembleStrictDebug :validator-test-app:assembleRelaxedDebug + +# Interactive EST/mTLS test app +./gradlew :cert-test-app:assembleDebug + +# Automated JUnit test plugin for TestBed Core +./gradlew :agent-test:jar +``` + +#### Gradle Properties for TestBed Core Integration +By default, `settings.gradle.kts` auto-detects a sibling `testbedui-plugins/common-utils` directory (`..` or `../../..`) as `testbedRoot`, and the `assembleDebug` tasks for `cert-manager`, `validator-test-app`, and `cert-test-app` copy their debug APKs to `/testbed-core/composeApp/resources/`. + +Two Gradle properties control this behavior for standalone or CI builds: +* **`-PskipTestbedCopy=true`**: Disables the `copyApkToCore` task so builds do not write outside the repository. +* **`-PtestbedRoot=/path/to/workspace`**: Explicitly sets the root directory containing `testbedui-plugins/common-utils` and `testbed-core`. + +```bash +# Example: standalone build without copying APKs to TestBed Core +./gradlew -PskipTestbedCopy=true :cert-lib:assembleRelease :validator-test-app:assembleStrictDebug +``` + +--- + +## ๐Ÿ’ป Integration Guide + +### 1. HTTPS Client Connections (using `NiapCertHelper`) + +Reuse the singleton `NiapCertHelper` instance across requests so the cached `SSLContext` and TLS session cache are preserved for session resumption. + +#### For OkHttp Clients: +```kotlin +val helper = NiapCertHelper.getInstance(context) +val okHttpClient = helper.configureOkHttp(OkHttpClient.Builder()).build() + +// With custom trust anchors and/or client certificate (mTLS): +val mtlsClient = helper.configureOkHttp( + builder = OkHttpClient.Builder(), + trustAnchors = mapOf("ca" to caInputStream), + options = NiapCertHelper.TrustAnchorOptions.USER_CA_ONLY, + keyManager = clientKeyManager // X509KeyManager, or null for server-auth only +).build() +``` + +#### For Standard `HttpsURLConnection`: +```kotlin +val url = URL("https://example.gov") +val helper = NiapCertHelper.getInstance(context) + +// Server-auth only, or pass keyManager for mTLS: +val connection = helper.openConnection(url, keyManager = clientKeyManager) +connection.hostnameVerifier = HostnameVerifier { hostname, session -> + helper.checkHostname(hostname, session) + true +} +connection.connect() +``` + +### 2. Hardware-Backed Credentials & mTLS (using `NiapCertManager`) + +Connect to the background lifecycle service to use enrolled certificates without exposing private keys to the application process. Always use `getSslSocketFactory(...)` or pass `getKeyManager(alias)` into `NiapCertHelper` so full NIAP TLS policy is enforced (do **not** use the deprecated `getSslContext(...)`). + +```kotlin +val certManager = NiapCertManager(context) + +if (certManager.hasEnrollment("my_secure_identity")) { + // Option A: Obtain a policy-enforcing SSLSocketFactory directly + val socketFactory = certManager.getSslSocketFactory( + alias = "my_secure_identity", + trustedCaPem = serverRootPem, + requireExtendedMasterSecret = true + ) + + // Option B: Pass the service-backed X509KeyManager into NiapCertHelper (OkHttp) + val helper = NiapCertHelper.getInstance(context) + val keyManager = certManager.getKeyManager("my_secure_identity") + val client = helper.configureOkHttp( + builder = OkHttpClient.Builder(), + trustAnchors = mapOf("ca" to serverRootPem.byteInputStream()), + options = NiapCertHelper.TrustAnchorOptions.USER_CA_ONLY, + keyManager = keyManager + ).build() +} +``` + +--- + +## ๐Ÿ“ฑ Using `validator-test-app` + +`validator-test-app` (`com.example.niap.cert.ext.testapp`, built in `strict` and `relaxed` flavors) exercises `cert-lib` over both `HttpsURLConnection` and `OkHttp`. On launch it displays and logs a build identifier (`versionName`, build time, and git SHA) to confirm which build is installed on the device. + +### Supported Intent Extras (`com.example.niap.cert.ext.testapp/.MainActivity`) + +| Extra | Type / Values | Default | Description | +|---|---|---|---| +| `openurl` | `String` | *(required)* | Target HTTPS URL (e.g. `https://localhost:9443/`). | +| `type` | `http` \| `okhttp3` | `http` | Client stack: `HttpsURLConnection` (`http`) or `OkHttp` (`okhttp3`). | +| `ca_b64` | `String` (base64) | *(optional)* | Base64-encoded X.509 trust anchor certificate. | +| `client_p12_b64` | `String` (base64) | *(optional)* | Base64-encoded PKCS#12 keystore containing a client certificate and private key for mTLS. | +| `client_p12_pass` | `String` | `changeit` | Password for the `client_p12_b64` PKCS#12 keystore. | +| `repeat` | `Int` (`N`) | `1` | Sends `N` sequential requests on fresh connections sharing one session cache; logs a per-request line with protocol, cipher, session ID, and `resumed=`. | + +### Example `adb` Invocations + +```bash +# 1. Baseline HTTPS request with a custom trust anchor (HttpsURLConnection) +CA_B64="$(tr -d '\r\n' < tools/tls-lab-repro/out/pki/ca.b64)" +adb shell am start -S -W -n com.example.niap.cert.ext.testapp/.MainActivity \ + -e openurl "https://localhost:9443/" \ + -e type http \ + -e ca_b64 "$CA_B64" + +# 2. Mutual TLS request with a PKCS#12 client certificate (OkHttp) +CLIENT_P12_B64="$(tr -d '\r\n' < tools/tls-lab-repro/out/pki/client.p12.b64)" +adb shell am start -S -W -n com.example.niap.cert.ext.testapp/.MainActivity \ + -e openurl "https://localhost:9443/" \ + -e type okhttp3 \ + -e ca_b64 "$CA_B64" \ + -e client_p12_b64 "$CLIENT_P12_B64" \ + -e client_p12_pass changeit + +# 3. Session resumption test (2 sequential requests sharing one session cache) +adb shell am start -S -W -n com.example.niap.cert.ext.testapp/.MainActivity \ + -e openurl "https://localhost:9443/" \ + -e type http \ + -e ca_b64 "$CA_B64" \ + -e repeat 2 +``` + +--- + +## ๐Ÿงช TLS Lab Reproduction Tooling (`tools/tls-lab-repro`) + +The repository includes a reusable host-side OpenSSL + `adb` harness under [`tools/tls-lab-repro/`](tools/tls-lab-repro/README.md) for reproducing and verifying TLS cipher suite enforcement, stapled OCSP validation, mutual TLS, and session resumption on a connected Android device without external network dependencies. + +```bash +# 1. Forward device localhost:9443 to host OpenSSL s_server +adb reverse tcp:9443 tcp:9443 + +# 2. Generate P-384 / ecdsa-with-SHA384 test PKI, OCSP staples, and client PKCS#12 +./tools/tls-lab-repro/gen_pki.sh + +# 3. Run the full verification matrix across http and okhttp3 +./tools/tls-lab-repro/run_matrix.sh +``` + +`run_matrix.sh` automatically queries `adb shell getprop ro.build.version.sdk` and selects `expected_fixed_api36.tsv` on API โ‰ค 36 devices or `expected_fixed.tsv` on API 37+ devices (overridable via `EXPECTED=api36|api37|`). Results and raw server/client traces are written to `tools/tls-lab-repro/out/` (including `out/matrix_report.md`, which records the detected API level and expected profile used). See [tools/tls-lab-repro/README.md](tools/tls-lab-repro/README.md) for single-case (`run_case.sh`), resumption (`run_resumption.sh`), and evaluation-lab reuse instructions. + +--- + +## ๐Ÿ“ฆ Packaging a NIAP Submission + +Use `tools/package-submission.sh` to build, unit-test, and package the app-level library and test APKs into a reproducible submission directory (default `dist/`): + +```bash +# Requires a clean git working tree (pass --allow-dirty to override during local drafts) +./tools/package-submission.sh [outdir] +``` + +The script invokes Gradle with `-PskipTestbedCopy=true`, runs `:cert-lib:testDebugUnitTest`, builds `:cert-lib:assembleRelease`, `:validator-test-app:assembleStrictDebug`, `:validator-test-app:assembleRelaxedDebug`, `:cert-manager:assembleDebug`, and `:cert-test-app:assembleDebug`, and outputs: +* `cert-lib-release.aar` +* `validator-test-app-strict-debug.apk` & `validator-test-app-relaxed-debug.apk` +* `cert-manager-debug.apk` & `cert-test-app-debug.apk` +* `niap-android-cert-ext.zip` (app-level repository source archive) +* `niap-cert-lib-release.zip` (`cert-lib` source + `cert-lib-release.aar` + `LICENSE` + `README.md`) +* `MANIFEST.txt` (UTC timestamp, git commit/branch, tool versions, byte sizes) +* `SHA256SUMS` (SHA-256 digests of all packaged files and `MANIFEST.txt`) + +To update the submission copy in `security-certification-resources/niap-cc/niap-android-cert-ext` (a separate repository), follow [docs/SUBMISSION.md](docs/SUBMISSION.md). Always package from this repository and copy the result there; never edit or package inside the copy. + +--- + +## ๐Ÿ”ฌ Mock EST & Testbed Verification + +For full EST enrollment and TestBed Core automation: + +### 1. Start the Local Compliance EST Server +The `est-server` directory contains a pre-packaged environment executing **Cisco libest** and **NGINX**. It generates compliant ECDSA P-384 certificates signed with SHA-384. + +```bash +cd est-server +# Configure EST_CERT_PROFILE=niap in docker-compose.yml to enable full compliance mode +docker compose up -d +``` + +### 2. Configure Port Forwarding for Testing +```bash +adb reverse tcp:8443 tcp:8443 # EST HTTPS Endpoint (libest/NGINX) +adb reverse tcp:8081 tcp:8081 # Strict mTLS test endpoint +adb reverse tcp:8080 tcp:8080 # HTTP admin / CA cert download endpoint +``` + +### 3. Run Automated TestBed Suite +Ensure the **TestBed Core** desktop application and MCP server are launched on `localhost:11452`, then run the JUnit test plugins: +* Execute `NiapValidatorTest` in the `agent-test` module to verify strict vs. relaxed validation behavior on actual devices. +* Execute `CertManagerTest` to launch an automated flow: installing test apps, establishing ADB reversals, performing EST registrations, validating KeyStore operations, and testing mTLS endpoints. + +--- + +## ๐Ÿ“„ License + +This project is licensed under the Apache License, Version 2.0 - see the [LICENSE](LICENSE) file for details. diff --git a/niap-cc/niap-android-cert-ext/agent-test/build.gradle.kts b/niap-cc/niap-android-cert-ext/agent-test/build.gradle.kts new file mode 100644 index 0000000..d9844a3 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/agent-test/build.gradle.kts @@ -0,0 +1,109 @@ +/* + * Copyright 2026 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. + */ + +import java.io.File + +plugins { + kotlin("jvm") +} + +kotlin { + jvmToolchain(21) +} + +val testbedRoot = gradle.extra["testbedRoot"] as File + +dependencies { + // 1. ๆœฌไฝ“ใฎใ‚ณใƒณใƒ‘ใ‚คใƒซๆธˆใฟใ‚ฏใƒฉใ‚นใ‚’ๅ‚็…ง + compileOnly(files(File(testbedRoot, "testbed-core/composeApp/build/classes/kotlin/jvm/main"))) + implementation(project(":common-utils")) + + // 2. ใƒ†ใ‚นใƒˆๅฎŸ่กŒใซๅฟ…่ฆใชๆœ€ๅฐ้™ใฎไพๅญ˜้–ขไฟ‚ + implementation("junit:junit:4.13.2") + implementation("com.malinskiy.adam:adam:0.5.10") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0") + + // Packet analysis + implementation("io.pkts:pkts-core:3.0.2") + implementation("com.squareup.okhttp3:mockwebserver:4.12.0") + implementation("org.bouncycastle:bcpkix-jdk18on:1.77") +} + +configurations.all { + resolutionStrategy { + force("org.jetbrains.kotlin:kotlin-stdlib:2.2.0") + force("org.jetbrains.kotlin:kotlin-stdlib-jdk8:2.2.0") + force("org.jetbrains.kotlin:kotlin-stdlib-jdk7:2.2.0") + force("org.jetbrains.kotlin:kotlin-reflect:2.2.0") + } +} + +tasks.jar { + val pluginName = project.name + archiveFileName.set("niap-cert-validator-test.jar") + + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) }) { + exclude("META-INF/*.SF") + exclude("META-INF/*.DSA") + exclude("META-INF/*.RSA") + } + destinationDirectory.set(File(testbedRoot, "testbed-core/composeApp/plugins/$pluginName")) +} + +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 +} + +tasks.withType().configureEach { + compilerOptions { + jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21) + } +} + +tasks.register("generateTestList") { + dependsOn("compileKotlin") + val srcDir = file("src/main/kotlin") + val listFile = layout.buildDirectory.file("generated/testbed/META-INF/testbed-tests.list") + + inputs.dir(srcDir).withPropertyName("sourceDirectory") + outputs.file(listFile).withPropertyName("outputListFile") + + doLast { + val out = listFile.get().asFile + out.parentFile.mkdirs() + + out.printWriter().use { writer -> + srcDir.walk().filter { it.isFile && it.extension == "kt" }.forEach { file -> + val text = file.readText() + + if (text.contains("@Test") && !text.contains("@Ignore")) { + val pkg = Regex("package\\s+([a-zA-Z0-9_.]+)").find(text)?.groupValues?.get(1) ?: "" + val cls = Regex("class\\s+([a-zA-Z0-9_]+)").find(text)?.groupValues?.get(1) ?: "" + if (cls.isNotEmpty()) { + writer.println("$pkg.$cls") + } + } + } + } + } +} + +tasks.named("jar") { + dependsOn("generateTestList") + from(layout.buildDirectory.dir("generated/testbed")) +} diff --git a/niap-cc/niap-android-cert-ext/agent-test/src/main/kotlin/org/example/plugin/fiax509/CertManagerTest.kt b/niap-cc/niap-android-cert-ext/agent-test/src/main/kotlin/org/example/plugin/fiax509/CertManagerTest.kt new file mode 100644 index 0000000..84050a6 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/agent-test/src/main/kotlin/org/example/plugin/fiax509/CertManagerTest.kt @@ -0,0 +1,202 @@ +/* + * Copyright 2026 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. + */ + +package org.example.plugin.fiax509 + +import org.example.plugin.utils.ADSRPTestWatcher +import org.example.plugin.utils.TestAssertLogger +import org.example.plugin.utils.SFR +import org.example.plugin.utils.SFRCheckList +import org.example.plugin.utils.* +import org.example.project.JUnitBridge +import com.malinskiy.adam.request.shell.v1.ShellCommandRequest +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ErrorCollector +import org.junit.rules.TestName +import org.junit.rules.TestWatcher +import org.example.project.adb.rules.AdbDeviceRule +import com.malinskiy.adam.AndroidDebugBridgeClient +import java.io.File +import org.hamcrest.core.IsEqual + +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.MockResponse +import okio.Buffer +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder +import java.math.BigInteger +import java.util.Date +import javax.security.auth.x500.X500Principal +import java.security.KeyPairGenerator +import java.security.spec.ECGenParameterSpec + +@SFR("FIA_XCU_EXT", "Verify NiapCertManager EST enrollment workflow", category = "network") +class CertManagerTest { + + companion object { + @BeforeClass + @JvmStatic + fun setupCheckList() { + SFRCheckList.register("FIA_XCU_EXT.2.1", "Verify certificate acquisition via EST") + SFRCheckList.register("FIA_XCU_EXT.2.2", "Verify mTLS client authentication with enrolled certificate") + } + } + + @get:Rule + val adb = AdbDeviceRule() + private val client: AndroidDebugBridgeClient by lazy { adb.adb } + + @get:Rule + val watcher: TestWatcher by lazy { ADSRPTestWatcher(adb) } + @get:Rule + val testname: TestName = TestName() + + private val a: TestAssertLogger by lazy { TestAssertLogger(testname) } + @get:Rule + val errs: ErrorCollector = ErrorCollector() + + @Test + fun testEstEnrollmentFlow() { + log("Starting testEstEnrollmentFlow targeting local Cisco libest native server on port 8085...") + val resp = runEnrollTest() + log("Logs: ${resp.workerLogs}") + + // Expect complete workflow success ending in READY state + errs.checkThat(a.msg("EST enrollment workflow should complete and enter READY state"), resp.workerLogs.contains("READY"), IsEqual(true)) + SFRCheckList.pass("FIA_XCU_EXT.2.1") + } + + @Test + fun testEnrollAndVerifyMtls() { + log("Starting testEnrollAndVerifyMtls: enroll then verify mTLS with enrolled certificate") + val serial = adb.deviceSerial + var mtlsLogs = "" + + runBlocking { + // 1. Install latest APK + val serviceApk = File(JUnitBridge.resourceDir, "cert-manager-debug.apk") + val retService = AdamUtils.installApk(client, serial, serviceApk, true) + Assert.assertTrue("Failed to install service app: $retService", retService.startsWith("Success")) + + // 2. ADB reverse port forwarding + try { + Runtime.getRuntime().exec(arrayOf("adb", "-s", serial, "reverse", "tcp:8443", "tcp:8443")).waitFor() + Runtime.getRuntime().exec(arrayOf("adb", "-s", serial, "reverse", "tcp:8080", "tcp:8080")).waitFor() + log("ADB reverse configured") + } catch (e: Exception) { + log("Warning: adb reverse failed: ${e.message}") + } + + // 3. Clear logcat and enroll + client.execute(ShellCommandRequest("logcat -c"), serial) + val enrollCmd = "am start -a android.intent.action.MAIN " + + "-n com.example.niap.cert.ext.manager/com.android.niap.cert.service.ManagerActivity " + + "-e action enroll -e alias test_client_cert " + + "-e estUrl https://localhost:8443/.well-known/est/ " + + "-e authToken estuser:estpwd -e subjectDn CN=TestUser" + client.execute(ShellCommandRequest(enrollCmd), serial) + Thread.sleep(15000) + + val enrollLogs = String(client.execute(ShellCommandRequest("logcat -d"), serial).stdout) + val enrolled = enrollLogs.contains("Enrollment succeeded: READY") + Assert.assertTrue("Enrollment must succeed before mTLS test", enrolled) + log("Enrollment confirmed: READY") + + // 4. Clear logcat and run mTLS verification + client.execute(ShellCommandRequest("logcat -c"), serial) + val mtlsCmd = "am start -a android.intent.action.MAIN --activity-clear-task " + + "-n com.example.niap.cert.ext.manager/com.android.niap.cert.service.ManagerActivity " + + "-e action verifyMtls -e alias test_client_cert " + + "-e protectedUrl https://localhost:8443/protected/" + client.execute(ShellCommandRequest(mtlsCmd), serial) + Thread.sleep(10000) + + val logcatResult = client.execute(ShellCommandRequest("logcat -d"), serial) + mtlsLogs = String(logcatResult.stdout).split("\n") + .filter { it.contains("ManagerActivity") || it.contains("NiapCertManager") } + .joinToString("\n") + } + + log("mTLS logs: $mtlsLogs") + errs.checkThat( + a.msg("mTLS should return HTTP 200 with enrolled certificate"), + mtlsLogs.contains("MTLS_RESULT: HTTP 200"), + IsEqual(true) + ) + SFRCheckList.pass("FIA_XCU_EXT.2.2") + } + + private fun runEnrollTest(): TestResult { + var workerLogsStr: String = "" + val serial = adb.deviceSerial + + runBlocking { + // 1. Install Service APK + val serviceApk = File(JUnitBridge.resourceDir, "cert-manager-debug.apk") + val retService = AdamUtils.installApk(client, serial, serviceApk, true) + Assert.assertTrue("Failed to install service app: $retService", retService.startsWith("Success")) + + // 2. Setup ADB reverse port forwarding for NGINX EST server (8443) and admin HTTP (8080) + try { + Runtime.getRuntime().exec(arrayOf("adb", "-s", serial, "reverse", "tcp:8443", "tcp:8443")).waitFor() + Runtime.getRuntime().exec(arrayOf("adb", "-s", serial, "reverse", "tcp:8080", "tcp:8080")).waitFor() + log("ADB reverse configured: tcp:8443 (EST/HTTPS), tcp:8080 (admin/HTTP)") + } catch (e: Exception) { + log("Warning: Failed to configure adb reverse: ${e.message}") + } + + // 3. CA cert is fetched by ManagerActivity directly from http://localhost:8080/cacert.pem + // (port 8080 is reverse-forwarded above, no push needed) + log("CA cert will be downloaded on-device from http://localhost:8080/cacert.pem") + + // 4. Clear logcat before test + client.execute(ShellCommandRequest("logcat -c"), serial) + + // 5. Launch ManagerActivity in automation mode (clear-task ensures a fresh onCreate) + val cmd = "am start -a android.intent.action.MAIN --activity-clear-task " + + "-n com.example.niap.cert.ext.manager/com.android.niap.cert.service.ManagerActivity " + + "-e action enroll " + + "-e alias test_client_cert " + + "-e estUrl https://localhost:8443/.well-known/est/ " + + "-e authToken estuser:estpwd " + + "-e subjectDn CN=TestUser" + client.execute(ShellCommandRequest(cmd), serial) + + // 6. Wait for enrollment to complete (service bind up to 10s + CA download + EST) + Thread.sleep(25000) + + // 7. Read relevant log lines + val logcatResult = client.execute(ShellCommandRequest("logcat -d"), serial) + val logcatOutput = String(logcatResult.stdout) + workerLogsStr = logcatOutput.split("\n") + .filter { + it.contains("ManagerActivity") || it.contains("EstClient") || + it.contains("NiapCertOrchestrator") || it.contains("NiapCertService") || + it.contains("NiapCertManager") + } + .joinToString("\n") + } + return TestResult(workerLogsStr) + } + + data class TestResult(val workerLogs: String) +} diff --git a/niap-cc/niap-android-cert-ext/agent-test/src/main/kotlin/org/example/plugin/fiax509/FiaX509ValidatorTest.kt b/niap-cc/niap-android-cert-ext/agent-test/src/main/kotlin/org/example/plugin/fiax509/FiaX509ValidatorTest.kt new file mode 100644 index 0000000..794965d --- /dev/null +++ b/niap-cc/niap-android-cert-ext/agent-test/src/main/kotlin/org/example/plugin/fiax509/FiaX509ValidatorTest.kt @@ -0,0 +1,133 @@ +/* + * Copyright 2026 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. + */ + +package org.example.plugin.fiax509 + +import org.example.plugin.utils.ADSRPTestWatcher +import org.example.plugin.utils.TestAssertLogger +import org.example.plugin.utils.SFR +import org.example.plugin.utils.SFRCheckList +import org.example.plugin.utils.* +import org.example.project.JUnitBridge +import com.malinskiy.adam.request.shell.v1.ShellCommandRequest +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ErrorCollector +import org.junit.rules.TestName +import org.junit.rules.TestWatcher +import org.example.project.adb.rules.AdbDeviceRule +import com.malinskiy.adam.AndroidDebugBridgeClient +import java.io.File +import org.hamcrest.core.IsEqual + +@SFR("FIA_X509_EXT", "Verify NiapCertValidator functionality", category = "network") +class NiapValidatorTest { + + companion object { + @BeforeClass + @JvmStatic + fun setupCheckList() { + SFRCheckList.register("FIA_X509_EXT.1.1", "Verify algorithm constraints (SHA-384)") + } + } + + @get:Rule + val adb = AdbDeviceRule() + private val client: AndroidDebugBridgeClient by lazy { adb.adb } + + @get:Rule + val watcher: TestWatcher by lazy { ADSRPTestWatcher(adb) } + @get:Rule + val testname: TestName = TestName() + + private val a: TestAssertLogger by lazy { TestAssertLogger(testname) } + @get:Rule + val errs: ErrorCollector = ErrorCollector() + + @Test + fun testGoogleCertRejected() { + log("Starting testGoogleCertRejected...") + val hostName = "https://www.google.com" + val resp = runTest(hostName) + + log("Logs: ${resp.workerLogs}") + + // We expect failure because Google uses SHA-256 + errs.checkThat(a.msg("Connection should fail for Google cert due to SHA-256"), resp.workerLogs.contains("CertificateException: Signature algorithm must use SHA-384"), IsEqual(true)) + + SFRCheckList.pass("FIA_X509_EXT.1.1") + } + + @Test + fun testGoogleCertRejectedOkHttp() { + log("Starting testGoogleCertRejectedOkHttp...") + val hostName = "https://www.google.com" + val resp = runTest(hostName, "okhttp3") + + log("Logs: ${resp.workerLogs}") + + // We expect failure because Google uses SHA-256 + errs.checkThat(a.msg("Connection should fail for Google cert due to SHA-256 (OkHttp)"), resp.workerLogs.contains("CertificateException: Signature algorithm must use SHA-384"), IsEqual(true)) + + SFRCheckList.pass("FIA_X509_EXT.1.1") + } + + @Test + fun testGoogleCertAcceptedInRelaxedMode() { + log("Starting testGoogleCertAcceptedInRelaxedMode...") + val hostName = "https://www.google.com" + val resp = runTest(hostName, "http", "relaxed") + + log("Logs: ${resp.workerLogs}") + + // We expect success because we disabled strict algorithm checks in relaxed flavor + errs.checkThat(a.msg("Connection should succeed in relaxed mode"), resp.workerLogs.contains("Response Code: 200"), IsEqual(true)) + } + + private fun runTest(testurl: String, type: String = "http", flavor: String = "strict"): TestResult { + var workerLogsStr: String = "" + val serial = adb.deviceSerial + + runBlocking { + val apkName = "validator-test-app-$flavor-debug.apk" + val appApk = File(JUnitBridge.resourceDir, apkName) + val ret = AdamUtils.installApk(client, serial, appApk, true) + Assert.assertTrue("Failed to install test app: ${ret}", ret.startsWith("Success")) + + client.execute(ShellCommandRequest("am force-stop com.example.niap.cert.ext.testapp"), serial) + Thread.sleep(2000) + + val cmd = "am start -a android.intent.action.MAIN -n com.example.niap.cert.ext.testapp/.MainActivity -e openurl '$testurl' -e type $type" + client.execute(ShellCommandRequest(cmd), serial) + + // Wait for logs + Thread.sleep(5000) // Simple wait instead of waitLogcatLine for robustness in this scratch test + + // Read logs to find the result + val logcatResult = client.execute(ShellCommandRequest("su 0 logcat -d"), serial) + val logcatOutput = String(logcatResult.stdout) + workerLogsStr = logcatOutput.split("\n").filter { it.contains("NetworkWorker") }.joinToString("\n") + } + return TestResult(workerLogsStr) + } + + data class TestResult(val workerLogs: String) +} diff --git a/niap-cc/niap-android-cert-ext/build.gradle.kts b/niap-cc/niap-android-cert-ext/build.gradle.kts new file mode 100644 index 0000000..9cd1d08 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/build.gradle.kts @@ -0,0 +1,26 @@ +/* + * Copyright 2026 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. + */ + +plugins { + id("com.android.application") version "8.2.0" apply false + id("com.android.library") version "8.2.0" apply false + id("org.jetbrains.kotlin.android") version "2.2.0" apply false + id("org.jetbrains.kotlin.jvm") version "2.2.0" apply false +} + +tasks.register("clean", Delete::class) { + delete(rootProject.buildDir) +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/build.gradle.kts b/niap-cc/niap-android-cert-ext/cert-lib/build.gradle.kts new file mode 100644 index 0000000..d073a50 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/build.gradle.kts @@ -0,0 +1,55 @@ +/* + * Copyright 2026 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. + */ + +plugins { + id("com.android.library") + id("org.jetbrains.kotlin.android") +} + +android { + namespace = "com.android.niap.cert.validator" + compileSdk = 34 + + defaultConfig { + minSdk = 32 + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = "1.8" + } + buildFeatures { + aidl = true + } + lint { + error += setOf( + "PrivateApi", + "DiscouragedPrivateApi", + "SoonBlockedPrivateApi", + "BlockedPrivateApi" + ) + abortOnError = true + } +} + +dependencies { + implementation("androidx.core:core-ktx:1.12.0") + compileOnly("com.squareup.okhttp3:okhttp:4.12.0") + testImplementation("junit:junit:4.13.2") +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/AndroidManifest.xml b/niap-cc/niap-android-cert-ext/cert-lib/src/main/AndroidManifest.xml new file mode 100644 index 0000000..ea1f705 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/AndroidManifest.xml @@ -0,0 +1,18 @@ + + + + diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/aidl/com/android/niap/cert/manager/IEnrollmentCallback.aidl b/niap-cc/niap-android-cert-ext/cert-lib/src/main/aidl/com/android/niap/cert/manager/IEnrollmentCallback.aidl new file mode 100644 index 0000000..838a45b --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/aidl/com/android/niap/cert/manager/IEnrollmentCallback.aidl @@ -0,0 +1,32 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.manager; + +/** + * Asynchronous result channel for INiapCertManager.requestCertificate. + * + * The service invokes exactly one of onSuccess / onError per enrollment. + * If the service dies before either is called, the caller-side + * IBinder.linkToDeath() hook synthesises an onError. + */ +oneway interface IEnrollmentCallback { + /** Enrollment completed: certificate is stored and ready to use. */ + void onSuccess(in byte[] certificateData); + + /** Enrollment failed: [errorMessage] is human-readable diagnostic text. */ + void onError(String errorMessage); +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/aidl/com/android/niap/cert/manager/INiapCertManager.aidl b/niap-cc/niap-android-cert-ext/cert-lib/src/main/aidl/com/android/niap/cert/manager/INiapCertManager.aidl new file mode 100644 index 0000000..82ad263 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/aidl/com/android/niap/cert/manager/INiapCertManager.aidl @@ -0,0 +1,56 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.manager; + +import android.os.Bundle; +import com.android.niap.cert.manager.IEnrollmentCallback; +import com.android.niap.cert.manager.IRevocationCallback; + +interface INiapCertManager { + /** + * Async enrollment with callback. Service invokes exactly one of + * callback.onSuccess(certData) or callback.onError(message). + * Replaces the old polling-based requestCertificate. + */ + void enroll( + String alias, + String estServerUrl, + String authToken, + String subjectDn, + in List sans, + String keyType, + String sigAlg, + String trustedCaPem, + in Bundle validatorConfig, + IEnrollmentCallback callback + ); + + /** Async revocation with callback. */ + void revoke(String alias, IRevocationCallback callback); + + /** Whether an enrollment for [alias] exists in the service KeyStore. */ + boolean hasEnrollment(String alias); + + /** Returns DER-encoded leaf certificate for [alias], or empty if none. */ + byte[] getCertificateData(String alias); + + /** + * Signs pre-hashed digest bytes with the key bound to alias (NONEwithECDSA). + * The service acts as a signing oracle; callers own the TLS/HTTP flow. + */ + byte[] sign(String alias, in byte[] digestBytes); +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/aidl/com/android/niap/cert/manager/IRevocationCallback.aidl b/niap-cc/niap-android-cert-ext/cert-lib/src/main/aidl/com/android/niap/cert/manager/IRevocationCallback.aidl new file mode 100644 index 0000000..2398137 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/aidl/com/android/niap/cert/manager/IRevocationCallback.aidl @@ -0,0 +1,29 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.manager; + +/** + * Asynchronous result channel for INiapCertManager.requestRevocation. + * + * The service invokes exactly one of onSuccess / onError per revocation. + * If the service dies before either is called, the caller-side + * IBinder.linkToDeath() hook synthesises an onError. + */ +oneway interface IRevocationCallback { + void onSuccess(); + void onError(String errorMessage); +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/INiapCertManager.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/INiapCertManager.kt new file mode 100644 index 0000000..e649122 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/INiapCertManager.kt @@ -0,0 +1,62 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.manager + +import android.os.IInterface + +enum class KeyType(val keyAlgorithm: String, val parameterSpecName: String?, val keySize: Int?) { + EC_P384(android.security.keystore.KeyProperties.KEY_ALGORITHM_EC, "secp384r1", null), + EC_P256(android.security.keystore.KeyProperties.KEY_ALGORITHM_EC, "secp256r1", null), + RSA_3072(android.security.keystore.KeyProperties.KEY_ALGORITHM_RSA, null, 3072), + RSA_2048(android.security.keystore.KeyProperties.KEY_ALGORITHM_RSA, null, 2048) +} + +enum class SigAlg(val algorithmName: String) { + SHA384_ECDSA("SHA384withECDSA"), + SHA256_ECDSA("SHA256withECDSA"), + SHA384_RSA("SHA384withRSA"), + SHA256_RSA("SHA256withRSA") +} + +data class CsrSpec( + val keyType: KeyType = KeyType.EC_P384, + val sigAlg: SigAlg = SigAlg.SHA384_ECDSA +) + +data class ValidatorConfig( + val strictSigAlg: Boolean = true, + val enforceCaConstraints: Boolean = true, + val enforceMandatoryExtensions: Boolean = true, + val enforceEku: Boolean = true +) + +data class EnrollmentRequest( + val alias: String, + val estServerUrl: String, + val authToken: String, + val subjectDn: String, + val sans: List = emptyList(), + val csrSpec: CsrSpec = CsrSpec(), + val trustedCaPem: String = "", + val validatorConfig: ValidatorConfig = ValidatorConfig() +) + +/** Thrown via the enroll() future on enrollment failure (network, validation, etc.). */ +class EnrollmentException(message: String) : Exception(message) + +/** Thrown via the revoke() future on revocation failure. */ +class RevocationException(message: String) : Exception(message) diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/MtlsKeyProvider.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/MtlsKeyProvider.kt new file mode 100644 index 0000000..8bda062 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/MtlsKeyProvider.kt @@ -0,0 +1,49 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.manager + +import java.security.cert.X509Certificate + +/** + * Abstraction over key storage backends for mTLS client authentication. + * + * Implementations: + * - Cert-manager backed (service-resident keys, signing via AIDL) โ€” the default, + * wired through [NiapCertManager.getKeyManager] and [NiapKeyManager]. + * - [KeyChainMtlsKeyProvider]: system KeyChain (keys accessible cross-process). + * Not yet implemented โ€” kept as a stub for a future installToKeyChain() flow. + */ +interface MtlsKeyProvider { + fun getCertificateChain(alias: String): Array? + /** Sign pre-hashed digest bytes; algorithm is NONEwithECDSA (Conscrypt convention). */ + fun sign(alias: String, digestBytes: ByteArray): ByteArray +} + +/** + * KeyChain-backed provider: the key lives in the system credential store and is + * accessible cross-process, so signing runs directly in the caller's process. + * + * TODO: implement once KeyChain enrollment flow is added. + */ +class KeyChainMtlsKeyProvider(private val context: android.content.Context) : MtlsKeyProvider { + override fun getCertificateChain(alias: String): Array? = + android.security.KeyChain.getCertificateChain(context, alias) + + override fun sign(alias: String, digestBytes: ByteArray): ByteArray { + throw UnsupportedOperationException("KeyChain signing not yet implemented") + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/NiapCertManager.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/NiapCertManager.kt new file mode 100644 index 0000000..ee78718 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/NiapCertManager.kt @@ -0,0 +1,318 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.manager + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.IBinder +import android.util.Log +import okhttp3.OkHttpClient +import okhttp3.Request +import java.security.KeyStore +import java.security.Security +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CopyOnWriteArraySet +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import javax.net.ssl.SSLContext +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509TrustManager + +/** + * Public entry point for apps. Hides the AIDL Service behind a standard, + * Future-based API and provides JCA components ([getKeyManager], [getSslContext]) + * so apps can use enrolled certificates with any HTTPS stack โ€” without needing + * to know that a separate Service exists. + * + * Threading: methods are safe to call from any thread. The first call lazily + * binds the Service; binding is held for the lifetime of this [NiapCertManager] + * instance until [close] is called. + */ +class NiapCertManager(private val context: Context) { +@Volatile private var service: INiapCertManager? = null +@Volatile private var latch = CountDownLatch(1) +@Volatile private var isBinding = false + + + /** + * Pending enrollment futures. We keep a strong reference to each callback's + * future here so that if the Service dies mid-enrollment, the death recipient + * can fail every outstanding future deterministically. + */ + private val pendingFutures = CopyOnWriteArraySet>() + + private val deathRecipient = IBinder.DeathRecipient { + Log.w("NiapCertManager", "Service binder died; failing ${pendingFutures.size} pending future(s)") + service = null + val err = IllegalStateException("cert-manager service died during operation") + pendingFutures.forEach { it.completeExceptionally(err) } + pendingFutures.clear() + } + + init { + if (Security.getProvider("NiapRemoteSigning") == null) { + Security.insertProviderAt(RemoteSigningProvider(), 1) + } + } + + private val connection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName?, binder: IBinder?) { + Log.d("NiapCertManager", "Service connected") + val proxy = INiapCertManager.Stub.asInterface(binder) + service = proxy + try { + binder?.linkToDeath(deathRecipient, 0) + } catch (e: Exception) { + Log.w("NiapCertManager", "linkToDeath failed: ${e.message}") + } + isBinding = false + latch.countDown() + } + + override fun onServiceDisconnected(name: ComponentName?) { + Log.d("NiapCertManager", "Service disconnected") + service = null + isBinding = false + } + } + + internal fun bindService(): Boolean { + if (service != null || isBinding) return true + isBinding = true + if (latch.count == 0L) latch = CountDownLatch(1) + val intent = Intent("com.android.niap.cert.service.BIND").apply { + setPackage("com.example.niap.cert.ext.manager") + } + Log.d("NiapCertManager", "Initiating bindService to com.example.niap.cert.ext.manager") + return context.bindService(intent, connection, Context.BIND_AUTO_CREATE) + } + + /** Release the Service binding; further calls will rebind lazily. */ + fun close() { + if (service != null) { + try { context.unbindService(connection) } catch (e: Exception) { + Log.w("NiapCertManager", "unbindService failed: ${e.message}") + } + service = null + isBinding = false + } + } + + /** + * Async enrollment. The returned [CompletableFuture] completes with the + * enrolled DER-encoded leaf certificate on success, or completes + * exceptionally on validation/network errors or Service death. + */ + fun enroll(request: EnrollmentRequest): CompletableFuture { + val future = CompletableFuture() + pendingFutures.add(future) + try { + ensureServiceConnected() + val svc = service ?: throw IllegalStateException("Service not connected") + val configBundle = android.os.Bundle().apply { + putBoolean("strictSigAlg", request.validatorConfig.strictSigAlg) + putBoolean("enforceCaConstraints", request.validatorConfig.enforceCaConstraints) + putBoolean("enforceMandatoryExtensions", request.validatorConfig.enforceMandatoryExtensions) + putBoolean("enforceEku", request.validatorConfig.enforceEku) + } + val cb = object : IEnrollmentCallback.Stub() { + override fun onSuccess(certificateData: ByteArray) { + pendingFutures.remove(future) + future.complete(certificateData) + } + override fun onError(errorMessage: String?) { + pendingFutures.remove(future) + future.completeExceptionally(EnrollmentException(errorMessage ?: "Unknown error")) + } + } + svc.enroll( + request.alias, request.estServerUrl, request.authToken, request.subjectDn, + request.sans, request.csrSpec.keyType.name, request.csrSpec.sigAlg.name, + request.trustedCaPem, configBundle, cb + ) + } catch (e: Exception) { + pendingFutures.remove(future) + future.completeExceptionally(e) + } + return future + } + + /** Async revocation. Future completes with Unit on success. */ + fun revoke(alias: String): CompletableFuture { + val future = CompletableFuture() + pendingFutures.add(future) + try { + ensureServiceConnected() + val svc = service ?: throw IllegalStateException("Service not connected") + val cb = object : IRevocationCallback.Stub() { + override fun onSuccess() { + pendingFutures.remove(future) + future.complete(Unit) + } + override fun onError(errorMessage: String?) { + pendingFutures.remove(future) + future.completeExceptionally(RevocationException(errorMessage ?: "Unknown error")) + } + } + svc.revoke(alias, cb) + } catch (e: Exception) { + pendingFutures.remove(future) + future.completeExceptionally(e) + } + return future + } + + /** True if an enrolled certificate for [alias] is available. */ + fun hasEnrollment(alias: String): Boolean { + ensureServiceConnected() + return service?.hasEnrollment(alias) ?: false + } + + /** Returns the DER-encoded leaf certificate, or null if no enrollment exists. */ + fun getCertificate(alias: String): X509Certificate? { + ensureServiceConnected() + val bytes = service?.getCertificateData(alias) ?: return null + if (bytes.isEmpty()) return null + return CertificateFactory.getInstance("X.509") + .generateCertificate(java.io.ByteArrayInputStream(bytes)) as? X509Certificate + } + + /** + * Returns a standard [javax.net.ssl.X509KeyManager] for the enrolled certificate. + * + * The returned KeyManager can be plugged directly into [SSLContext.init] and used + * with any HTTP/TLS stack (OkHttp, HttpsURLConnection, โ€ฆ). The private key material + * never leaves the cert-manager service โ€” signing is delegated transparently via + * the AIDL `sign()` oracle, hidden behind the standard JCA interface. + */ + fun getKeyManager(alias: String): javax.net.ssl.X509KeyManager { + ensureServiceConnected() + val svc = service ?: throw IllegalStateException("Service not connected") + val certBytes = svc.getCertificateData(alias) + require(certBytes.isNotEmpty()) { "No certificate found for alias '$alias'" } + val cert = java.security.cert.CertificateFactory.getInstance("X.509") + .generateCertificate(java.io.ByteArrayInputStream(certBytes)) as X509Certificate + return NiapKeyManager(alias, arrayOf(cert)) { digest -> svc.sign(alias, digest) } + } + + /** + * Convenience: builds an [SSLContext] initialised with the enrolled cert's + * KeyManager and (optionally) a TrustManager derived from [trustedCaPem]. + * If [trustedCaPem] is null, system trust anchors are used. + */ + @Deprecated( + message = "A raw SSLContext cannot enforce socket-level NIAP TLS policy (cipher allowlist, protocol pinning, EMS). " + + "Use getSslSocketFactory() or NiapCertHelper with getKeyManager() instead.", + replaceWith = ReplaceWith("getSslSocketFactory(alias, trustedCaPem)") + ) + fun getSslContext(alias: String, trustedCaPem: String? = null): SSLContext { + val km = getKeyManager(alias) + val tms = if (trustedCaPem.isNullOrBlank()) null else arrayOf(buildTrustManager(trustedCaPem)) + return SSLContext.getInstance("TLS").apply { init(arrayOf(km), tms, null) } + } + + /** + * Returns an [javax.net.ssl.SSLSocketFactory] backed by [com.android.niap.cert.validator.NiapCertHelper] + * using the enrolled client certificate ([getKeyManager]) and enforcing the full NIAP TLS policy + * (certificate/revocation validation, cipher suite allowlist, protocol versions, and EMS). + */ + fun getSslSocketFactory( + alias: String, + trustedCaPem: String? = null, + requireExtendedMasterSecret: Boolean = true + ): javax.net.ssl.SSLSocketFactory { + val helper = com.android.niap.cert.validator.NiapCertHelper.getInstance(context) + val km = getKeyManager(alias) + val (options, anchors) = buildTrustAnchorParams(trustedCaPem) + return helper.getOrCreateTlsStack( + options = options, + trustAnchors = anchors, + keyManager = km, + requireEmsOverride = requireExtendedMasterSecret + ).socketFactory + } + + /** + * Performs an mTLS GET request to [protectedUrl] using the enrolled certificate + * with full NIAP TLS policy and standard hostname verification. + * + * Returns "HTTP \n" or "ERROR\n". + */ + fun verifyMtls(alias: String, protectedUrl: String, trustedCaPem: String): String { + return try { + val helper = com.android.niap.cert.validator.NiapCertHelper.getInstance(context) + val km = getKeyManager(alias) + val (options, anchors) = buildTrustAnchorParams(trustedCaPem) + val client = helper.configureOkHttp( + builder = OkHttpClient.Builder(), + trustAnchors = anchors, + options = options, + keyManager = km + ).build() + val response = client.newCall(Request.Builder().url(protectedUrl).get().build()).execute() + val code = response.code + val body = response.body?.string()?.trim() ?: "" + Log.d("NiapCertManager", "verifyMtls result: HTTP $code") + "HTTP $code\n$body" + } catch (e: Exception) { + Log.e("NiapCertManager", "verifyMtls error: ${e.message}", e) + "ERROR\n${e.message ?: e.javaClass.simpleName}" + } + } + + // ------------------------------------------------------------------------- + // Internal helpers + // ------------------------------------------------------------------------- + + private fun buildTrustAnchorParams( + trustedCaPem: String? + ): Pair?> { + return if (trustedCaPem.isNullOrBlank()) { + com.android.niap.cert.validator.NiapCertHelper.TrustAnchorOptions.SYSTEM_CA_ONLY to null + } else { + com.android.niap.cert.validator.NiapCertHelper.TrustAnchorOptions.USER_CA_ONLY to + mapOf("ca" to trustedCaPem.byteInputStream()) + } + } + + private fun buildTrustManager(caPem: String): X509TrustManager { + val cf = CertificateFactory.getInstance("X.509") + val caCert = cf.generateCertificate(caPem.byteInputStream()) as X509Certificate + val trustStore = KeyStore.getInstance(KeyStore.getDefaultType()).apply { + load(null, null) + setCertificateEntry("ca", caCert) + } + val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + .apply { init(trustStore) } + return tmf.trustManagers[0] as X509TrustManager + } + + private fun ensureServiceConnected() { + if (service == null) { + bindService() + val connected = latch.await(10, TimeUnit.SECONDS) + if (!connected) { + Log.e("NiapCertManager", "Timeout waiting for service binding") + isBinding = false + } + } + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/NiapKeyManager.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/NiapKeyManager.kt new file mode 100644 index 0000000..2ba28e7 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/NiapKeyManager.kt @@ -0,0 +1,66 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.manager + +import java.net.Socket +import java.security.Principal +import java.security.PrivateKey +import java.security.cert.X509Certificate +import java.security.interfaces.ECPublicKey +import javax.net.ssl.SSLEngine +import javax.net.ssl.X509ExtendedKeyManager + +/** + * Standard [X509ExtendedKeyManager] backed by an enrolled certificate whose + * private key lives in the cert-manager service. Callers can plug this + * directly into any [javax.net.ssl.SSLContext] / OkHttp / HttpsURLConnection + * stack โ€” the signing-oracle plumbing is hidden behind the standard JCA + * interface. + * + * Construction is cheap; the actual signing happens lazily inside + * [RemoteSignatureSpi] via [RemotePrivateKey.signingFn] when the TLS stack + * calls Signature.sign(). + */ +internal class NiapKeyManager( + private val alias: String, + private val certificateChain: Array, + signingFn: (ByteArray) -> ByteArray +) : X509ExtendedKeyManager() { + + private val remoteKey: RemotePrivateKey + + init { + require(certificateChain.isNotEmpty()) { "Empty certificate chain for alias '$alias'" } + val params = (certificateChain[0].publicKey as? ECPublicKey)?.params + ?: throw IllegalArgumentException( + "NiapKeyManager only supports EC keys; cert for '$alias' has " + + "${certificateChain[0].publicKey.algorithm}" + ) + remoteKey = RemotePrivateKey(alias, params, signingFn) + } + + override fun chooseClientAlias(keyType: Array?, issuers: Array?, socket: Socket?) = alias + override fun chooseEngineClientAlias(keyType: Array?, issuers: Array?, engine: SSLEngine?) = alias + override fun chooseServerAlias(keyType: String?, issuers: Array?, socket: Socket?) = null + override fun chooseEngineServerAlias(keyType: String?, issuers: Array?, engine: SSLEngine?) = null + + override fun getCertificateChain(alias: String?): Array = certificateChain + override fun getPrivateKey(alias: String?): PrivateKey = remoteKey + + override fun getClientAliases(keyType: String?, issuers: Array?) = arrayOf(alias) + override fun getServerAliases(keyType: String?, issuers: Array?) = null +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/RemoteSigningProvider.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/RemoteSigningProvider.kt new file mode 100644 index 0000000..1c52fd1 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/manager/RemoteSigningProvider.kt @@ -0,0 +1,100 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.manager + +import java.io.ByteArrayOutputStream +import java.security.PrivateKey +import java.security.Provider +import java.security.PublicKey +import java.security.SignatureSpi +import java.security.interfaces.ECKey +import java.security.spec.ECParameterSpec + +/** + * Marker key that carries the alias, EC curve params, and a per-instance + * signing function. The private key material itself never leaves the + * cert-manager service; this object is only a routing handle for JCA. + * + * Conscrypt requires the key to implement [ECKey] so it can derive the TLS + * signing algorithm (ecdsa_secp384r1_sha384 etc.) from the curve. + * + * The [signingFn] is invoked by [RemoteSignatureSpi.engineSign] with the + * pre-hashed digest bytes; implementations typically delegate to the + * cert-manager service over AIDL. + */ +internal class RemotePrivateKey( + val alias: String, + private val params: ECParameterSpec, + val signingFn: (ByteArray) -> ByteArray +) : PrivateKey, ECKey { + override fun getAlgorithm() = "EC" + override fun getFormat() = null + override fun getEncoded() = null // key material stays in the oracle + override fun getParams() = params +} + +/** + * [SignatureSpi] for "NONEwithECDSA". Buffers update bytes during the TLS + * handshake and invokes the [RemotePrivateKey.signingFn] captured in + * [engineInitSign] on [engineSign]. No thread-local state; each Signature + * instance is bound to one [RemotePrivateKey], so concurrent handshakes + * are independent. + */ +class RemoteSignatureSpi : SignatureSpi() { + private val buffer = ByteArrayOutputStream() + private var signingFn: ((ByteArray) -> ByteArray)? = null + + override fun engineInitSign(privateKey: PrivateKey?) { + signingFn = (privateKey as? RemotePrivateKey)?.signingFn + ?: throw java.security.InvalidKeyException( + "RemoteSignatureSpi requires a RemotePrivateKey; got ${privateKey?.javaClass?.name}" + ) + buffer.reset() + } + + override fun engineInitVerify(publicKey: PublicKey?) {} + override fun engineUpdate(b: Byte) { buffer.write(b.toInt()) } + override fun engineUpdate(b: ByteArray, off: Int, len: Int) { buffer.write(b, off, len) } + + override fun engineSign(): ByteArray { + val fn = signingFn + ?: throw java.security.SignatureException("engineSign called before engineInitSign") + return fn(buffer.toByteArray()).also { buffer.reset() } + } + + override fun engineVerify(sigBytes: ByteArray?) = false + override fun engineSetParameter(param: String?, value: Any?) {} + @Suppress("OVERRIDE_DEPRECATION") + override fun engineGetParameter(param: String?) = null +} + +/** + * JCA [Provider] registered once at library init. Handles "NONEwithECDSA" + * only for [RemotePrivateKey] instances via [Service.supportsParameter]; + * all other keys fall through to the next provider in the chain. + */ +internal class RemoteSigningProvider : Provider("NiapRemoteSigning", 1.0, "") { + init { + val svc = object : Service( + this, "Signature", "NONEwithECDSA", + RemoteSignatureSpi::class.java.name, null, null + ) { + override fun supportsParameter(key: Any?) = key is RemotePrivateKey + } + putService(svc) + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapCertHelper.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapCertHelper.kt new file mode 100644 index 0000000..7bead1f --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapCertHelper.kt @@ -0,0 +1,616 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.validator + +import android.content.Context +import android.util.Log +import org.xmlpull.v1.XmlPullParser +import java.io.InputStream +import java.net.URL +import java.security.KeyStore +import java.security.MessageDigest +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import java.util.concurrent.ConcurrentHashMap +import javax.net.ssl.HttpsURLConnection +import javax.net.ssl.SSLContext +import javax.net.ssl.SSLSession +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509KeyManager +import javax.net.ssl.X509TrustManager +import okhttp3.ConnectionSpec +import okhttp3.OkHttpClient +import okhttp3.TlsVersion + +/** + * Helper class to create secure network objects using NiapCertValidator. + * + * Caches one [SSLContext] and wrapped [SSLSocketFactory] per unique configuration + * (trust-anchor policy, anchor certificate encodings, key-manager identity, and EMS setting) + * so repeated [openConnection] and [configureOkHttp] calls share the TLS client session cache + * (enabling TLS session resumption) and connection pools. + */ +class NiapCertHelper private constructor( + private val validator: NiapCertValidator = NiapCertValidator(), + private val allowedCipherSuites: List = NiapTlsPolicy.APPROVED_SUITES, + private val trustAnchorPolicy: TrustAnchorOptions = TrustAnchorOptions.BOTH_CA, + private val enforceTls12: Boolean = false, + private val requireExtendedMasterSecret: Boolean = true +) { + enum class TrustAnchorOptions { + USER_CA_ONLY, + BOTH_CA, + SYSTEM_CA_ONLY + } + + internal data class TlsStack( + val sslContext: SSLContext, + val trustManager: NiapX509TrustManager, + val socketFactory: SSLSocketFactory + ) + + private class IdentityKey(val ref: Any?) { + override fun equals(other: Any?): Boolean = other is IdentityKey && ref === other.ref + override fun hashCode(): Int = System.identityHashCode(ref) + } + + private data class StackCacheKey( + val options: TrustAnchorOptions, + val anchorDigestHex: String, + val keyManagerIdentity: IdentityKey, + val requireEms: Boolean + ) + + private val stackCache = ConcurrentHashMap() + + internal fun clearCache() { + stackCache.clear() + } + + internal fun cacheSizeForTesting(): Int = stackCache.size + + /** + * Validates that the URL uses HTTPS. + */ + fun validateUrl(url: String) { + validator.validateUrl(url) + } + + companion object { + @Volatile + private var instance: NiapCertHelper? = null + + /** + * Resets the singleton instance and clears cached SSLContexts / socket factories. + */ + fun resetInstance() { + synchronized(this) { + instance?.clearCache() + instance = null + } + } + + internal fun clearActiveCaches() { + synchronized(this) { + instance?.clearCache() + } + } + + internal fun createForTesting( + validator: NiapCertValidator = NiapCertValidator(), + allowedCipherSuites: List = NiapTlsPolicy.APPROVED_SUITES, + trustAnchorPolicy: TrustAnchorOptions = TrustAnchorOptions.BOTH_CA, + enforceTls12: Boolean = false, + requireExtendedMasterSecret: Boolean = true + ): NiapCertHelper = NiapCertHelper( + validator = validator, + allowedCipherSuites = allowedCipherSuites, + trustAnchorPolicy = trustAnchorPolicy, + enforceTls12 = enforceTls12, + requireExtendedMasterSecret = requireExtendedMasterSecret + ) + + /** + * Gets the singleton instance of NiapCertHelper, initializing it from XML config if necessary. + */ + fun getInstance(context: Context): NiapCertHelper { + return instance ?: synchronized(this) { + instance ?: fromConfig(context).also { instance = it } + } + } + /** + * Creates a NiapCertHelper by loading configuration from res/xml/niap_security_config.xml. + */ + fun fromConfig(context: Context): NiapCertHelper { + val resId = context.resources.getIdentifier("niap_security_config", "xml", context.packageName) + val parser = if (resId != 0) { + context.resources.getXml(resId) + } else { + val libResId = context.resources.getIdentifier("niap_security_config", "xml", "com.android.niap.cert.validator") + if (libResId != 0) { + context.resources.getXml(libResId) + } else { + throw IllegalStateException("niap_security_config.xml not found") + } + } + + var strictSigAlg = true + val prohibitedTlds = mutableSetOf() + val allowedCiphers = mutableListOf() + var trustAnchorPolicy = TrustAnchorOptions.BOTH_CA + var enforceMandatoryExtensions = true + var enforceEku = true + var enforceCaConstraints = true + var enforceTls12 = false + var requireExtendedMasterSecret = true + var requiredEkus = listOf("serverAuth") + + var eventType = parser.eventType + var currentTag = "" + + while (eventType != XmlPullParser.END_DOCUMENT) { + when (eventType) { + XmlPullParser.START_TAG -> { + currentTag = parser.name + } + XmlPullParser.TEXT -> { + val text = parser.text.trim() + if (text.isNotEmpty()) { + when (currentTag) { + "niap-rfc8603-strict-sigalg" -> { + strictSigAlg = text.toBoolean() + } + "tld" -> { + prohibitedTlds.add(text) + } + "cipher" -> { + allowedCiphers.add(text) + } + "trust-anchor-policy" -> { + trustAnchorPolicy = TrustAnchorOptions.valueOf(text.uppercase()) + } + "enforce-mandatory-extensions" -> { + enforceMandatoryExtensions = text.toBoolean() + } + "enforce-eku" -> { + enforceEku = text.toBoolean() + } + "enforce-ca-constraints" -> { + enforceCaConstraints = text.toBoolean() + } + "enforce-tls-1-2" -> { + enforceTls12 = text.toBoolean() + } + "require-extended-master-secret" -> { + requireExtendedMasterSecret = text.toBoolean() + } + "required-eku" -> { + requiredEkus = text.split(",").map { it.trim() }.filter { it.isNotEmpty() } + } + } + } + } + XmlPullParser.END_TAG -> { + currentTag = "" + } + } + eventType = parser.next() + } + + + val validator = NiapCertValidator( + strictSigAlg = strictSigAlg, + prohibitedTldWildcards = prohibitedTlds, + enforceCaConstraints = enforceCaConstraints, + enforceMandatoryExtensions = enforceMandatoryExtensions, + enforceEku = enforceEku, + requiredEkus = requiredEkus + ) + val resolvedSuites = NiapTlsPolicy.resolveAllowedCipherSuites(allowedCiphers) + return NiapCertHelper( + validator, + resolvedSuites, + trustAnchorPolicy, + enforceTls12, + requireExtendedMasterSecret + ) + } + } + + private fun parseTrustAnchors( + trustAnchors: Map? + ): List> { + if (trustAnchors.isNullOrEmpty()) return emptyList() + val cf = CertificateFactory.getInstance("X.509") + return trustAnchors.map { (alias, stream) -> + alias to (cf.generateCertificate(stream) as X509Certificate) + } + } + + private fun computeAnchorsDigest(anchors: List>): String { + if (anchors.isEmpty()) return "" + val perCert = anchors.map { (_, cert) -> sha256Hex(cert.encoded) }.sorted() + val md = MessageDigest.getInstance("SHA-256") + perCert.forEach { md.update(it.toByteArray(Charsets.UTF_8)) } + return md.digest().joinToString("") { "%02x".format(it) } + } + + private fun sha256Hex(bytes: ByteArray): String { + val digest = MessageDigest.getInstance("SHA-256").digest(bytes) + return digest.joinToString("") { "%02x".format(it) } + } + + private fun createTrustManager( + options: TrustAnchorOptions, + parsedAnchors: List> + ): X509TrustManager { + val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + + return when (options) { + TrustAnchorOptions.SYSTEM_CA_ONLY -> { + tmf.init(null as KeyStore?) + tmf.trustManagers.first { it is X509TrustManager } as X509TrustManager + } + TrustAnchorOptions.USER_CA_ONLY -> { + val store = KeyStore.getInstance(KeyStore.getDefaultType()) + store.load(null, null) + for ((alias, cert) in parsedAnchors) { + store.setCertificateEntry(alias, cert) + } + tmf.init(store) + tmf.trustManagers.first { it is X509TrustManager } as X509TrustManager + } + TrustAnchorOptions.BOTH_CA -> { + tmf.init(null as KeyStore?) + val systemTm = tmf.trustManagers.first { it is X509TrustManager } as X509TrustManager + if (parsedAnchors.isEmpty()) { + return systemTm + } + val store = KeyStore.getInstance(KeyStore.getDefaultType()) + store.load(null, null) + for ((alias, cert) in parsedAnchors) { + store.setCertificateEntry(alias, cert) + } + val userTmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + userTmf.init(store) + val userTm = userTmf.trustManagers.first { it is X509TrustManager } as X509TrustManager + + CombinedTrustManager(systemTm, userTm) + } + } + } + + internal fun getOrCreateTlsStack( + options: TrustAnchorOptions = trustAnchorPolicy, + trustAnchors: Map? = null, + keyManager: X509KeyManager? = null, + requireEmsOverride: Boolean? = null + ): TlsStack { + val parsedAnchors = parseTrustAnchors(trustAnchors) + val effectiveOptions = if (options == TrustAnchorOptions.BOTH_CA && parsedAnchors.isEmpty()) { + TrustAnchorOptions.SYSTEM_CA_ONLY + } else { + options + } + val effectiveRequireEms = requireEmsOverride ?: requireExtendedMasterSecret + val key = StackCacheKey( + options = effectiveOptions, + anchorDigestHex = computeAnchorsDigest(parsedAnchors), + keyManagerIdentity = IdentityKey(keyManager), + requireEms = effectiveRequireEms + ) + return stackCache.computeIfAbsent(key) { + val effectiveTls12 = NiapTlsPolicy.effectiveEnforceTls12(enforceTls12) + val baseTm = createTrustManager(effectiveOptions, parsedAnchors) + val niapTrustManager = NiapX509TrustManager(baseTm, validator) + val sslContext = if (effectiveTls12) { + SSLContext.getInstance("TLSv1.2") + } else { + SSLContext.getInstance("TLS") + } + val kms = keyManager?.let { arrayOf(it) } + sslContext.init(kms, arrayOf(niapTrustManager), null) + + val suiteNames = NiapTlsPolicy.suiteNamesForPolicy(allowedCipherSuites, effectiveTls12) + val protocols = NiapTlsPolicy.allowedProtocols(effectiveTls12) + val wrappedFactory = VerifiableSSLSocketFactory( + delegate = sslContext.socketFactory, + allowedCipherSuites = suiteNames, + requireExtendedMasterSecret = effectiveRequireEms, + enabledProtocols = protocols + ) + TlsStack(sslContext, niapTrustManager, wrappedFactory) + } + } + + fun createSSLSocketFactory(): SSLSocketFactory = + getOrCreateTlsStack(trustAnchorPolicy, null, null).socketFactory + + fun createSSLSocketFactory(keyManager: X509KeyManager?): SSLSocketFactory = + getOrCreateTlsStack(trustAnchorPolicy, null, keyManager).socketFactory + + fun createSSLSocketFactory( + trustAnchors: Map, + options: TrustAnchorOptions = trustAnchorPolicy + ): SSLSocketFactory = + getOrCreateTlsStack(options, trustAnchors, null).socketFactory + + fun createSSLSocketFactory( + trustAnchors: Map?, + options: TrustAnchorOptions = trustAnchorPolicy, + keyManager: X509KeyManager? + ): SSLSocketFactory = + getOrCreateTlsStack(options, trustAnchors, keyManager).socketFactory + + /** + * Opens a [HttpsURLConnection] for the given URL and applies NIAP security settings, + * reusing the cached [SSLContext] and [SSLSocketFactory] for session resumption and pooling. + */ + fun openConnection(url: URL): HttpsURLConnection = + openConnection(url, null, trustAnchorPolicy, null) + + /** + * Opens a [HttpsURLConnection] using an optional client-certificate [X509KeyManager]. + */ + fun openConnection(url: URL, keyManager: X509KeyManager?): HttpsURLConnection = + openConnection(url, null, trustAnchorPolicy, keyManager) + + /** + * Opens a [HttpsURLConnection] with optional custom trust anchors and client-certificate + * [X509KeyManager], reusing the cached [SSLContext] and [SSLSocketFactory]. + */ + fun openConnection( + url: URL, + trustAnchors: Map?, + options: TrustAnchorOptions = trustAnchorPolicy, + keyManager: X509KeyManager? = null + ): HttpsURLConnection { + val connection = url.openConnection() as HttpsURLConnection + connection.sslSocketFactory = getOrCreateTlsStack(options, trustAnchors, keyManager).socketFactory + return connection + } + + /** + * Verifies the hostname against the SSL session. + */ + fun checkHostname(hostname: String, session: SSLSession) { + validator.checkHostname(hostname, session) + } + + fun configureOkHttp(builder: OkHttpClient.Builder): OkHttpClient.Builder = + configureOkHttp(builder, getOrCreateTlsStack(trustAnchorPolicy, null, null)) + + fun configureOkHttp( + builder: OkHttpClient.Builder, + keyManager: X509KeyManager? + ): OkHttpClient.Builder = + configureOkHttp(builder, getOrCreateTlsStack(trustAnchorPolicy, null, keyManager)) + + fun configureOkHttp( + builder: OkHttpClient.Builder, + trustAnchors: Map, + options: TrustAnchorOptions = trustAnchorPolicy + ): OkHttpClient.Builder = + configureOkHttp(builder, getOrCreateTlsStack(options, trustAnchors, null)) + + fun configureOkHttp( + builder: OkHttpClient.Builder, + trustAnchors: Map?, + options: TrustAnchorOptions = trustAnchorPolicy, + keyManager: X509KeyManager? + ): OkHttpClient.Builder = + configureOkHttp(builder, getOrCreateTlsStack(options, trustAnchors, keyManager)) + + internal fun configureOkHttp(builder: OkHttpClient.Builder, stack: TlsStack): OkHttpClient.Builder { + val effectiveTls12 = NiapTlsPolicy.effectiveEnforceTls12(enforceTls12) + val suiteNames = NiapTlsPolicy.suiteNamesForPolicy(allowedCipherSuites, effectiveTls12) + val connectionSpecBuilder = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) + if (effectiveTls12) { + connectionSpecBuilder.tlsVersions(TlsVersion.TLS_1_2) + } else { + connectionSpecBuilder.tlsVersions(TlsVersion.TLS_1_3, TlsVersion.TLS_1_2) + } + connectionSpecBuilder.cipherSuites(*suiteNames) + + return builder + .sslSocketFactory(stack.socketFactory, stack.trustManager) + .connectionSpecs(listOf(connectionSpecBuilder.build())) + } + + internal class CombinedTrustManager( + private val systemTm: X509TrustManager, + private val customTm: X509TrustManager + ) : javax.net.ssl.X509ExtendedTrustManager() { + + override fun checkClientTrusted( + chain: Array?, + authType: String? + ) { + runWithFallback( + primary = { customTm.checkClientTrusted(chain, authType) }, + fallback = { systemTm.checkClientTrusted(chain, authType) } + ) + } + + override fun checkClientTrusted( + chain: Array?, + authType: String?, + socket: java.net.Socket? + ) { + runWithFallback( + primary = { delegateClient(customTm, chain, authType, socket) }, + fallback = { delegateClient(systemTm, chain, authType, socket) } + ) + } + + override fun checkClientTrusted( + chain: Array?, + authType: String?, + engine: javax.net.ssl.SSLEngine? + ) { + runWithFallback( + primary = { delegateClient(customTm, chain, authType, engine) }, + fallback = { delegateClient(systemTm, chain, authType, engine) } + ) + } + + override fun checkServerTrusted( + chain: Array?, + authType: String? + ) { + runWithFallback( + primary = { customTm.checkServerTrusted(chain, authType) }, + fallback = { systemTm.checkServerTrusted(chain, authType) } + ) + } + + override fun checkServerTrusted( + chain: Array?, + authType: String?, + socket: java.net.Socket? + ) { + runWithFallback( + primary = { delegateServer(customTm, chain, authType, socket) }, + fallback = { delegateServer(systemTm, chain, authType, socket) } + ) + } + + override fun checkServerTrusted( + chain: Array?, + authType: String?, + engine: javax.net.ssl.SSLEngine? + ) { + runWithFallback( + primary = { delegateServer(customTm, chain, authType, engine) }, + fallback = { delegateServer(systemTm, chain, authType, engine) } + ) + } + + override fun getAcceptedIssuers(): Array { + return systemTm.acceptedIssuers + customTm.acceptedIssuers + } + + private inline fun runWithFallback(primary: () -> Unit, fallback: () -> Unit) { + try { + primary() + } catch (e: java.security.cert.CertificateException) { + if (isTrustAnchorNotFound(e)) { + fallback() + } else { + throw e + } + } + } + + private fun delegateClient( + tm: X509TrustManager, + chain: Array?, + authType: String?, + socket: java.net.Socket? + ) { + if (tm is javax.net.ssl.X509ExtendedTrustManager) { + tm.checkClientTrusted(chain, authType, socket) + } else { + tm.checkClientTrusted(chain, authType) + } + } + + private fun delegateClient( + tm: X509TrustManager, + chain: Array?, + authType: String?, + engine: javax.net.ssl.SSLEngine? + ) { + if (tm is javax.net.ssl.X509ExtendedTrustManager) { + tm.checkClientTrusted(chain, authType, engine) + } else { + tm.checkClientTrusted(chain, authType) + } + } + + private fun delegateServer( + tm: X509TrustManager, + chain: Array?, + authType: String?, + socket: java.net.Socket? + ) { + if (tm is javax.net.ssl.X509ExtendedTrustManager) { + tm.checkServerTrusted(chain, authType, socket) + } else { + tm.checkServerTrusted(chain, authType) + } + } + + private fun delegateServer( + tm: X509TrustManager, + chain: Array?, + authType: String?, + engine: javax.net.ssl.SSLEngine? + ) { + if (tm is javax.net.ssl.X509ExtendedTrustManager) { + tm.checkServerTrusted(chain, authType, engine) + } else { + tm.checkServerTrusted(chain, authType) + } + } + + companion object { + internal fun isTrustAnchorNotFound(error: Throwable): Boolean { + var sawAnchorNotFound = false + var current: Throwable? = error + var depth = 0 + while (current != null && depth < 16) { + when (current) { + is java.security.cert.CertificateExpiredException, + is java.security.cert.CertificateNotYetValidException, + is java.security.cert.CertificateRevokedException -> return false + + is java.security.cert.CertPathValidatorException -> { + val reason = current.reason + if (reason == java.security.cert.PKIXReason.NO_TRUST_ANCHOR) { + sawAnchorNotFound = true + } else if (reason != java.security.cert.CertPathValidatorException.BasicReason.UNSPECIFIED) { + return false + } + } + + is java.security.cert.CertPathBuilderException -> { + sawAnchorNotFound = true + } + } + + val msg = current.message?.lowercase() + if (msg != null && ( + msg.contains("trust anchor for certification path not found") || + msg.contains("trust anchor not found") || + msg.contains("unable to find valid certification path") || + msg.contains("no trust anchor") || + msg.contains("pkix path building failed") + ) + ) { + sawAnchorNotFound = true + } + + current = current.cause + depth++ + } + return sawAnchorNotFound + } + } + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapCertValidator.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapCertValidator.kt new file mode 100644 index 0000000..43afa12 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapCertValidator.kt @@ -0,0 +1,250 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.validator + +import android.util.Log +import java.security.cert.X509Certificate +import java.security.interfaces.ECPublicKey +import java.security.interfaces.RSAPublicKey + +import java.security.cert.CertificateException +import java.security.cert.CertificateParsingException +import java.security.cert.CertPathValidator +import java.security.cert.PKIXParameters +import java.security.cert.PKIXRevocationChecker +import java.security.cert.CertificateFactory +import java.security.cert.CertPath +import java.util.EnumSet +import javax.net.ssl.SSLSession +import javax.net.ssl.HttpsURLConnection +import java.security.KeyStore +import java.security.cert.CertPathValidatorException +import java.security.GeneralSecurityException + +class NiapCertValidator( + private val strictSigAlg: Boolean = true, + private val prohibitedTldWildcards: Set = setOf("*.COM", "*.NET", "*.ORG"), + private val enforceCaConstraints: Boolean = true, + private val enforceMandatoryExtensions: Boolean = true, + private val enforceEku: Boolean = true, + private val requiredEkus: List = listOf("serverAuth") +) { + + fun validateCertificate(chain: Array) { + if (chain.isEmpty()) { + throw IllegalArgumentException("Certificate chain is empty") + } + + val leafCert = chain[0] + + // 1. Algorithm Constraints (RFC 8603 CNSA) + + + checkAlgorithmConstraints(leafCert) + + // 2. Mandatory Extension Checks + + + checkMandatoryExtensions(leafCert) + + // 3. Field Enforcement (Basic Constraints, EKU, Name Constraints) + + + checkFieldEnforcement(chain) + + // 4. TLD Wildcard Check (Carried over from SecureURL) + + + checkTldWildcards(leafCert) + + // 5. Revocation Checks (OCSP / CRL) + + + checkRevocation(leafCert) + } + + fun validateUrl(urlString: String) { + // Enforce HTTPS (blocking non-secure connections) + if (urlString.startsWith("http://", ignoreCase = true)) { + throw CertificateException("Insecure HTTP connections are blocked: $urlString") + } + + // If no protocol, assume https + val url = if (!urlString.contains("://")) { + "https://$urlString" + } else { + urlString + } + // Hostname validation will be done by Conscrypt or OkHttp + } + + private fun checkTldWildcards(cert: X509Certificate) { + try { + val subAltNames = cert.subjectAlternativeNames + if (subAltNames != null) { + for (tldList in subAltNames) { + if (tldList.size >= 2) { + val dnsName = tldList[1].toString().uppercase() + if (prohibitedTldWildcards.contains(dnsName)) { + throw CertificateException("Failed wildcard TLD check: $dnsName") + } + } + } + } + } catch (e: CertificateParsingException) { + throw CertificateException("Failed to parse SANs", e) + } + } + + private fun checkAlgorithmConstraints(cert: X509Certificate) { + + if (!strictSigAlg) return + + val sigAlgName = cert.sigAlgName + val pubKey = cert.publicKey + + // Enforce SHA-384 or SHA-512 with ECDSA or RSA (RFC 8603) + if (!sigAlgName.contains("SHA384", ignoreCase = true) && + !sigAlgName.contains("SHA512", ignoreCase = true)) { + throw CertificateException("Signature algorithm must use SHA-384 or SHA-512: $sigAlgName") + } + + if (pubKey is RSAPublicKey) { + if (pubKey.modulus.bitLength() < 3072) { + throw CertificateException("RSA key size must be 3072 bits or greater") + } + } else if (pubKey is ECPublicKey) { + // Check field size (P-384 has field size 384) + val params = pubKey.params + if (params == null || params.curve.field.fieldSize < 384) { + throw CertificateException("EC key size must be 384 bits or greater") + } + } else { + throw CertificateException( + "Unsupported public key type: ${pubKey.algorithm} (only RSA >= 3072 and EC >= 384 are permitted)" + ) + } + } + + private fun checkMandatoryExtensions(cert: X509Certificate) { + if (!enforceMandatoryExtensions) return + + val nonCriticalOids = cert.nonCriticalExtensionOIDs ?: emptySet() + val criticalOids = cert.criticalExtensionOIDs ?: emptySet() + val allOids = nonCriticalOids + criticalOids + + // OIDs referenced from FIA_X509_EXT.1.2 in MDFPP (Mobile Device Fundamentals Protection Profile) + val mandatoryOids = listOf( + "2.5.29.35", // Authority Key Identifier. Required by FIA_X509_EXT.1.2 + "2.5.29.14", // Subject Key Identifier. Required by FIA_X509_EXT.1.2 + "2.5.29.15" // Key Usage. Required by FIA_X509_EXT.1.2 + ) + + for (oid in mandatoryOids) { + if (!allOids.contains(oid)) { + throw CertificateException("Mandatory extension missing: $oid (Required by FIA_X509_EXT.1.2)") + } + } + } + + private fun checkFieldEnforcement(chain: Array) { + val leafCert = chain[0] + runCatching { + android.util.Log.d("NiapCertValidator", "DEBUG checkFieldEnforcement: enforceEku=$enforceEku eku=${leafCert.extendedKeyUsage}") + } + + // 1. Extended Key Usage (EKU) Check + // Required by FIA_X509_EXT.1.1 or related evaluation activities in MDFPP. + if (enforceEku) { + val eku = leafCert.extendedKeyUsage + if (eku != null) { + for (reqEku in requiredEkus) { + val targetOid = mapEkuNameToOid(reqEku) + if (!eku.contains(targetOid)) { + throw CertificateException("Leaf certificate missing required EKU: $reqEku ($targetOid)") + } + } + } else { + throw CertificateException("Leaf certificate missing Extended Key Usage extension") + } + } + + // Basic Constraints Check + if (enforceCaConstraints) { + val basicConstraints = leafCert.basicConstraints + if (basicConstraints >= 0) { + throw CertificateException("Leaf certificate must not be a CA (Enforced by FIA_X509_EXT.1.2 / Basic Constraints)") + } + } + } + + private fun mapEkuNameToOid(name: String): String { + return when (name.lowercase()) { + "serverauth" -> "1.3.6.1.5.5.7.3.1" + "clientauth" -> "1.3.6.1.5.5.7.3.2" + "codesigning" -> "1.3.6.1.5.5.7.3.3" + "emailprotection" -> "1.3.6.1.5.5.7.3.4" + "timestamping" -> "1.3.6.1.5.5.7.3.8" + "ocspsigning" -> "1.3.6.1.5.5.7.3.9" + else -> name // Assume it's already an OID if not recognized + } + } + + private fun checkRevocation(cert: X509Certificate) { + // Offline stapled OCSP revocation verification is enforced in NiapX509TrustManager + // where the TLS handshake SSLSession (and its stapled status_request responses) is available. + } + + fun checkCertPath(chain: Array) { + val leafCerts = chain.filter { !isRootCA(it) } + if (leafCerts.isEmpty()) { + throw CertificateException("No non-root certificates found in chain") + } + val certFactory = CertificateFactory.getInstance("X.509") + val path = certFactory.generateCertPath(leafCerts) + + val ks = KeyStore.getInstance("AndroidCAStore") + ks.load(null, null) + + val cpv = CertPathValidator.getInstance("PKIX") + val params = PKIXParameters(ks) + params.isRevocationEnabled = true + + val checker = cpv.revocationChecker as PKIXRevocationChecker + checker.options = EnumSet.of(PKIXRevocationChecker.Option.NO_FALLBACK) + params.addCertPathChecker(checker) + + try { + cpv.validate(path, params) + } catch (e: CertPathValidatorException) { + throw CertificateException("CertPath validation failed", e) + } catch (e: GeneralSecurityException) { + throw CertificateException("Security exception during CertPath validation", e) + } + } + + fun checkHostname(hostname: String, session: SSLSession) { + val hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier() + if (!hostnameVerifier.verify(hostname, session)) { + throw CertificateException("Hostname verification failed for $hostname") + } + } + + private fun isRootCA(cert: X509Certificate): Boolean { + return cert.subjectDN.name == cert.issuerDN.name + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapTlsPolicy.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapTlsPolicy.kt new file mode 100644 index 0000000..6c76996 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapTlsPolicy.kt @@ -0,0 +1,278 @@ +/* + * Copyright 2026 Google LLC + * + * 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. + */ + +package com.android.niap.cert.validator + +import android.content.Context +import android.content.pm.ApplicationInfo +import android.os.Build +import android.util.Log +import java.util.Locale +import java.util.concurrent.atomic.AtomicBoolean +import javax.net.ssl.ExtendedSSLSession + +/** + * Single source of truth for the NIAP TLS protocol and cipher suite policy. + * + * The built-in [APPROVED_SUITES] table is the AEAD subset of the NIST SP 800-52 Rev. 2 + * recommended cipher suites supported by the platform TLS stack (AES-CCM suites are also + * SP 800-52 Rev. 2-approved but are not offered by the platform TLS stack; ChaCha20-Poly1305 + * is not a FIPS-approved algorithm and is therefore refused). + * + * XML `` configuration may only narrow this list further (for example, + * AES-256-only if an evaluation requires it); unknown or non-approved cipher suite names are + * rejected when loading configuration. + */ +object NiapTlsPolicy { + + private const val TAG = "NiapTlsPolicy" + + @Volatile + internal var overridePublicStapleApiAvailable: Boolean? = null + + @Volatile + private var forceTls12WireCapture: Boolean = false + + private val tls12FallbackWarningLogged = AtomicBoolean(false) + + private val detectedPublicStapleApi: Boolean by lazy { + val available = try { + ExtendedSSLSession::class.java.getMethod("getStatusResponses") + true + } catch (_: NoSuchMethodException) { + false + } catch (_: LinkageError) { + false + } + runCatching { + val sdkInt = try { + Build.VERSION.SDK_INT + } catch (_: Throwable) { + -1 + } + Log.i( + TAG, + "Platform OCSP staple capability: ExtendedSSLSession.getStatusResponses() " + + "available=$available (SDK_INT=$sdkInt)" + ) + } + available + } + + /** + * Whether the platform exposes the public [ExtendedSSLSession.getStatusResponses] API + * (Android API 37+ / JDK 9+) and the test-only wire-capture override is not active. + * Computed once per process; injectable for unit tests. + */ + val isPublicStapleApiAvailable: Boolean + get() = if (forceTls12WireCapture) { + false + } else { + overridePublicStapleApiAvailable ?: detectedPublicStapleApi + } + + /** + * True when [setForceTls12WireCaptureForTesting] has been enabled in a debuggable build. + */ + val isForceTls12WireCaptureEnabled: Boolean + get() = forceTls12WireCapture + + /** + * TEST-ONLY switch that forces the API <= 36 code path (TLS 1.2 only + plaintext + * wire-captured `CertificateStatus` OCSP staple) even on platforms where the public + * [ExtendedSSLSession.getStatusResponses] API exists (API 37+). + * + * Honoured ONLY when the calling application is debuggable (`ApplicationInfo.FLAG_DEBUGGABLE`); + * throws [IllegalStateException] in non-debuggable builds. Invalidates cached + * [NiapCertHelper] SSLContexts whenever the state changes. + */ + fun setForceTls12WireCaptureForTesting(context: Context, enabled: Boolean) { + val isDebuggable = (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0 + setForceTls12WireCaptureForTesting(isDebuggable, enabled) + } + + internal fun setForceTls12WireCaptureForTesting(isDebuggable: Boolean, enabled: Boolean) { + if (!isDebuggable) { + throw IllegalStateException( + "NiapTlsPolicy.setForceTls12WireCaptureForTesting() is only permitted in debuggable builds " + + "(ApplicationInfo.FLAG_DEBUGGABLE is not set)" + ) + } + val previous = forceTls12WireCapture + forceTls12WireCapture = enabled + if (enabled) { + runCatching { + Log.w( + TAG, + "TEST MODE WARNING: forcing TLS 1.2 wire-capture OCSP path " + + "(simulating API <= 36; debuggable test-only hook, not part of evaluated configuration)" + ) + } + } + if (previous != enabled) { + NiapCertHelper.clearActiveCaches() + } + } + + /** + * Resets test-only overrides and one-time warning state. + */ + internal fun resetCapabilityStateForTesting() { + overridePublicStapleApiAvailable = null + forceTls12WireCapture = false + tls12FallbackWarningLogged.set(false) + } + + data class CipherSuite( + val name: String, + val codePoint: Int, + val isTls13: Boolean + ) + + /** + * Built-in approved cipher suites with IANA code points: the AEAD subset of the + * NIST SP 800-52 Rev. 2 recommended cipher suites supported by the platform TLS stack. + */ + val APPROVED_SUITES: List = listOf( + // TLS 1.3 + CipherSuite("TLS_AES_128_GCM_SHA256", 0x1301, isTls13 = true), + CipherSuite("TLS_AES_256_GCM_SHA384", 0x1302, isTls13 = true), + // TLS 1.2 + CipherSuite("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", 0xC02B, isTls13 = false), + CipherSuite("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", 0xC02F, isTls13 = false), + CipherSuite("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", 0xC02C, isTls13 = false), + CipherSuite("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", 0xC030, isTls13 = false) + ) + + private val APPROVED_BY_NAME: Map = + APPROVED_SUITES.associateBy { it.name } + + private val KNOWN_SUITE_NAMES: Map = buildMap { + APPROVED_SUITES.forEach { put(it.codePoint, it.name) } + // Common non-approved suites for clear diagnostic messages + put(0x1303, "TLS_CHACHA20_POLY1305_SHA256") + put(0x1304, "TLS_AES_128_CCM_SHA256") + put(0x1305, "TLS_AES_128_CCM_8_SHA256") + put(0xCCA8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256") + put(0xCCA9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256") + put(0xC013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA") + put(0xC014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA") + put(0xC009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA") + put(0xC00A, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA") + put(0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA") + put(0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA") + put(0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256") + put(0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384") + } + + val DEFAULT_SUITE_NAMES: Array = APPROVED_SUITES.map { it.name }.toTypedArray() + + val DEFAULT_PROTOCOLS: Array = arrayOf("TLSv1.3", "TLSv1.2") + + /** + * Returns whether connections must be pinned to TLS 1.2 only. + * + * When [publicStapleApiAvailable] is false (Android API <= 36), TLS 1.3 stapled OCSP + * responses are encrypted and inaccessible to apps via public APIs, so TLS 1.2 is + * enforced unconditionally (with wire-level `CertificateStatus` capture). + */ + fun effectiveEnforceTls12( + enforceTls12: Boolean, + publicStapleApiAvailable: Boolean = isPublicStapleApiAvailable + ): Boolean { + if (!publicStapleApiAvailable) { + if (!enforceTls12 && tls12FallbackWarningLogged.compareAndSet(false, true)) { + runCatching { + Log.w( + TAG, + "Pinning TLS to TLSv1.2 only: TLS 1.3 stapled OCSP responses are not " + + "accessible to apps through a public API before API 37. " + + "Using TLS 1.2 plaintext CertificateStatus wire capture." + ) + } + } + return true + } + return enforceTls12 + } + + fun allowedProtocols( + enforceTls12: Boolean, + publicStapleApiAvailable: Boolean = isPublicStapleApiAvailable + ): Array = + if (effectiveEnforceTls12(enforceTls12, publicStapleApiAvailable)) { + arrayOf("TLSv1.2") + } else { + arrayOf("TLSv1.3", "TLSv1.2") + } + + /** + * Validates and resolves configured `` entries against [APPROVED_SUITES]. + * + * - Empty or null list returns [APPROVED_SUITES]. + * - Any unknown or non-approved cipher suite name throws [IllegalArgumentException]. + */ + fun resolveAllowedCipherSuites(configuredNames: List?): List { + if (configuredNames.isNullOrEmpty()) { + return APPROVED_SUITES + } + val resolved = ArrayList(configuredNames.size) + val seen = HashSet() + for (raw in configuredNames) { + val name = raw.trim() + if (name.isEmpty()) continue + val suite = APPROVED_BY_NAME[name] + ?: throw IllegalArgumentException( + "Cipher suite '$name' is not in the NIAP-approved allowlist. " + + "Approved suites: ${APPROVED_SUITES.joinToString(", ") { it.name }}" + ) + if (seen.add(suite.name)) { + resolved.add(suite) + } + } + return if (resolved.isEmpty()) APPROVED_SUITES else resolved + } + + fun suiteNamesForPolicy( + suites: List, + enforceTls12: Boolean, + publicStapleApiAvailable: Boolean = isPublicStapleApiAvailable + ): Array { + val tls12Only = effectiveEnforceTls12(enforceTls12, publicStapleApiAvailable) + val filtered = if (tls12Only) suites.filter { !it.isTls13 } else suites + return filtered.map { it.name }.toTypedArray() + } + + fun tls12SuiteNames(suites: List): Array = + suites.filter { !it.isTls13 }.map { it.name }.toTypedArray() + + fun codePointsForNames( + suiteNames: Array, + allowTls13: Boolean = true + ): Set { + val resolved = resolveAllowedCipherSuites(suiteNames.toList()) + return resolved + .filter { allowTls13 || !it.isTls13 } + .map { it.codePoint } + .toSet() + } + + fun describeCipherSuite(codePoint: Int): String { + val hex = String.format(Locale.US, "0x%04X", codePoint and 0xFFFF) + val name = KNOWN_SUITE_NAMES[codePoint and 0xFFFF] + return if (name != null) "$hex ($name)" else hex + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapX509TrustManager.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapX509TrustManager.kt new file mode 100644 index 0000000..a3c43fd --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/NiapX509TrustManager.kt @@ -0,0 +1,238 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.validator + +import android.util.Log +import java.lang.reflect.InvocationTargetException +import java.net.Socket +import java.security.cert.CertificateException +import java.security.cert.X509Certificate +import javax.net.ssl.ExtendedSSLSession +import javax.net.ssl.SSLEngine +import javax.net.ssl.SSLSession +import javax.net.ssl.SSLSocket +import javax.net.ssl.X509ExtendedTrustManager +import javax.net.ssl.X509TrustManager + +/** + * Session-aware [X509ExtendedTrustManager] that delegates chain building/verification to [delegate], + * applies [NiapCertValidator] checks, and enforces hard-fail offline OCSP stapling verification + * (RFC 6066 / FIA_X509_EXT.1.1) on server handshakes. + * + * Note on TLS session resumption: resumed TLS sessions do not re-invoke [checkServerTrusted], + * so certificate and stapled OCSP revocation checks run only on full handshakes. + */ +class NiapX509TrustManager( + private val delegate: X509TrustManager, + private val validator: NiapCertValidator = NiapCertValidator() +) : X509ExtendedTrustManager() { + + override fun checkClientTrusted(chain: Array?, authType: String?) { + delegate.checkClientTrusted(chain, authType) + } + + override fun checkClientTrusted( + chain: Array?, + authType: String?, + socket: Socket? + ) { + if (delegate is X509ExtendedTrustManager) { + delegate.checkClientTrusted(chain, authType, socket) + } else { + delegate.checkClientTrusted(chain, authType) + } + } + + override fun checkClientTrusted( + chain: Array?, + authType: String?, + engine: SSLEngine? + ) { + if (delegate is X509ExtendedTrustManager) { + delegate.checkClientTrusted(chain, authType, engine) + } else { + delegate.checkClientTrusted(chain, authType) + } + } + + override fun checkServerTrusted(chain: Array?, authType: String?) { + delegate.checkServerTrusted(chain, authType) + if (chain != null) { + validator.validateCertificate(chain) + } + throw CertificateException( + "Revocation status unavailable: no TLS session available to verify the stapled OCSP response " + + "(use a session-aware X509ExtendedTrustManager call)" + ) + } + + override fun checkServerTrusted( + chain: Array?, + authType: String?, + socket: Socket? + ) { + if (delegate is X509ExtendedTrustManager) { + delegate.checkServerTrusted(chain, authType, socket) + } else { + delegate.checkServerTrusted(chain, authType) + } + if (chain != null) { + validator.validateCertificate(chain) + val sslSocket = socket as? SSLSocket + verifyStapledOcsp(chain, sslSocket?.handshakeSession, sslSocket) + } + } + + override fun checkServerTrusted( + chain: Array?, + authType: String?, + engine: SSLEngine? + ) { + if (delegate is X509ExtendedTrustManager) { + delegate.checkServerTrusted(chain, authType, engine) + } else { + delegate.checkServerTrusted(chain, authType) + } + if (chain != null) { + validator.validateCertificate(chain) + verifyStapledOcsp(chain, engine?.handshakeSession, sslSocket = null) + } + } + + override fun getAcceptedIssuers(): Array { + return delegate.acceptedIssuers + } + + private fun verifyStapledOcsp( + chain: Array, + session: SSLSession?, + sslSocket: SSLSocket? + ) { + val leafStaple = if (NiapTlsPolicy.isPublicStapleApiAvailable) { + runCatching { + Log.i(TAG, "OCSP staple source: public API (ExtendedSSLSession.getStatusResponses)") + } + val responses = when (val result = readStatusResponses(session)) { + is StapleReadResult.Available -> result.responses + is StapleReadResult.Unavailable -> throw CertificateException(result.reason, result.cause) + } + responses.firstOrNull { it.isNotEmpty() } + ?: throw CertificateException( + "Revocation status unavailable: server did not staple an OCSP response (OCSP stapling is required)" + ) + } else { + val forcedNote = if (NiapTlsPolicy.isForceTls12WireCaptureEnabled) " [forced test mode]" else "" + runCatching { + Log.i(TAG, "OCSP staple source: TLS 1.2 wire capture (CertificateStatus)$forcedNote") + } + if (sslSocket == null) { + throw CertificateException( + "Revocation status unavailable: stapled OCSP responses are not accessible on this platform version " + + "for SSLEngine connections" + ) + } + val capture = WireOcspRegistry.lookup(sslSocket) + ?: throw CertificateException( + "Revocation status unavailable: stapled OCSP responses are not accessible on this platform version " + + "for this connection (untracked SSLSocket)" + ) + if (capture.negotiatedTls13 || session?.protocol.equals("TLSv1.3", ignoreCase = true)) { + throw CertificateException( + "Revocation status unavailable: stapled OCSP responses are not accessible on this platform version " + + "for TLSv1.3 connections" + ) + } + capture.ocspResponse?.takeIf { it.isNotEmpty() } + ?: throw CertificateException( + "Revocation status unavailable: server did not staple an OCSP response (OCSP stapling is required)" + ) + } + OcspStapleValidator.verify( + chain = chain, + stapledResponse = leafStaple, + acceptedIssuers = delegate.acceptedIssuers + ) + } + + internal sealed interface StapleReadResult { + data class Available(val responses: List) : StapleReadResult + data class Unavailable(val reason: String, val cause: Throwable? = null) : StapleReadResult + } + + companion object { + private const val TAG = "NiapX509TrustManager" + + internal fun readStatusResponses(session: SSLSession?): StapleReadResult { + if (session == null) { + return StapleReadResult.Unavailable( + "Revocation status unavailable: unable to read the stapled OCSP response from the TLS session " + + "(platform API unavailable: no handshake session)" + ) + } + if (session !is ExtendedSSLSession) { + runCatching { + Log.e( + TAG, + "Handshake session ${session.javaClass.name} does not extend ExtendedSSLSession; " + + "cannot read stapled OCSP responses" + ) + } + return StapleReadResult.Unavailable( + "Revocation status unavailable: unable to read the stapled OCSP response from the TLS session " + + "(platform API unavailable)" + ) + } + return try { + StapleReadResult.Available(readViaPublicApi(session)) + } catch (e: InvocationTargetException) { + val target = e.targetException ?: e + runCatching { + Log.e(TAG, "ExtendedSSLSession.getStatusResponses() threw an error", target) + } + StapleReadResult.Unavailable( + "Revocation status unavailable: unable to read the stapled OCSP response from the TLS session " + + "(platform API unavailable)", + target + ) + } catch (e: LinkageError) { + runCatching { + Log.e(TAG, "Failed to read stapled OCSP responses from ExtendedSSLSession.getStatusResponses()", e) + } + StapleReadResult.Unavailable( + "Revocation status unavailable: unable to read the stapled OCSP response from the TLS session " + + "(platform API unavailable)", + e + ) + } catch (e: Exception) { + runCatching { + Log.e(TAG, "Failed to read stapled OCSP responses from ExtendedSSLSession.getStatusResponses()", e) + } + StapleReadResult.Unavailable( + "Revocation status unavailable: unable to read the stapled OCSP response from the TLS session " + + "(platform API unavailable)", + e + ) + } + } + + private fun readViaPublicApi(session: ExtendedSSLSession): List { + val method = ExtendedSSLSession::class.java.getMethod("getStatusResponses") + val raw = method.invoke(session) as? List<*> ?: return emptyList() + return raw.mapNotNull { it as? ByteArray } + } + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/OcspStapleValidator.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/OcspStapleValidator.kt new file mode 100644 index 0000000..9ae89e2 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/OcspStapleValidator.kt @@ -0,0 +1,379 @@ +/* + * Copyright 2026 Google LLC + * + * 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. + */ + +package com.android.niap.cert.validator + +import java.io.ByteArrayInputStream +import java.math.BigInteger +import java.security.GeneralSecurityException +import java.security.cert.CertPathValidator +import java.security.cert.CertPathValidatorException +import java.security.cert.CertPathValidatorException.BasicReason +import java.security.cert.CertificateException +import java.security.cert.CertificateFactory +import java.security.cert.PKIXParameters +import java.security.cert.PKIXReason +import java.security.cert.PKIXRevocationChecker +import java.security.cert.TrustAnchor +import java.security.cert.X509Certificate +import java.security.interfaces.ECPublicKey +import java.security.interfaces.RSAPublicKey +import java.util.EnumSet + +/** + * Verifies a server-stapled OCSP response offline (no network access, hard fail) + * using PKIX [PKIXRevocationChecker] and enforces FIA_X509_EXT.1.1 OCSP signature + * and signer key constraints. + */ +internal object OcspStapleValidator { + + private const val OID_ID_PKIX_OCSP_BASIC = "1.3.6.1.5.5.7.48.1.1" + + private val ALLOWED_OCSP_SIG_OIDS: Set = setOf( + "1.2.840.10045.4.3.3", // ecdsa-with-SHA384 + "1.2.840.10045.4.3.4", // ecdsa-with-SHA512 + "1.2.840.113549.1.1.12", // sha384WithRSAEncryption + "1.2.840.113549.1.1.13" // sha512WithRSAEncryption + ) + + private val ALLOWED_EC_FIELD_SIZES: Set = setOf(384, 521) + private const val MIN_RSA_KEY_BITS = 3072 + + /** + * Verifies [stapledResponse] for the leaf certificate (`chain[0]`) with no network access. + * + * @throws CertificateException whose cause is a [CertPathValidatorException] on any failure. + */ + fun verify( + chain: Array, + stapledResponse: ByteArray, + acceptedIssuers: Array = emptyArray() + ) { + if (chain.isEmpty()) { + val cpve = CertPathValidatorException( + "Certificate chain is empty", + null, + null, + -1, + BasicReason.UNDETERMINED_REVOCATION_STATUS + ) + throw CertificateException(cpve.message, cpve) + } + + val leaf = chain[0] + val (pathCerts, anchor, issuerCert) = resolvePathAndAnchor(chain, acceptedIssuers) + + val cf = CertificateFactory.getInstance("X.509") + val certPath = try { + cf.generateCertPath(pathCerts) + } catch (e: GeneralSecurityException) { + val cpve = CertPathValidatorException( + "Failed to build CertPath for OCSP verification: ${e.message}", + e, + null, + -1, + BasicReason.UNDETERMINED_REVOCATION_STATUS + ) + throw CertificateException(cpve.message, cpve) + } + + try { + val cpv = CertPathValidator.getInstance("PKIX") + val revChecker = cpv.revocationChecker as PKIXRevocationChecker + revChecker.options = EnumSet.of( + PKIXRevocationChecker.Option.ONLY_END_ENTITY, + PKIXRevocationChecker.Option.NO_FALLBACK + ) + revChecker.ocspResponses = mapOf(leaf to stapledResponse) + + val params = PKIXParameters(setOf(anchor)).apply { + isRevocationEnabled = false + addCertPathChecker(revChecker) + } + cpv.validate(certPath, params) + } catch (e: CertPathValidatorException) { + throw CertificateException( + "Stapled OCSP verification failed (${e.reason}): ${e.message}", + e + ) + } catch (e: GeneralSecurityException) { + val cpve = CertPathValidatorException( + "Stapled OCSP verification failed: ${e.message}", + e, + certPath, + 0, + BasicReason.UNDETERMINED_REVOCATION_STATUS + ) + throw CertificateException(cpve.message, cpve) + } + + enforceOcspSignaturePolicy(stapledResponse, issuerCert, certPath) + } + + private data class ResolvedChain( + val pathCerts: List, + val anchor: TrustAnchor, + val issuerCert: X509Certificate + ) + + private fun resolvePathAndAnchor( + chain: Array, + acceptedIssuers: Array + ): ResolvedChain { + val topCert = chain.last() + val isTopSelfSigned = topCert.subjectX500Principal == topCert.issuerX500Principal + + if (isTopSelfSigned && chain.size >= 2) { + return ResolvedChain( + pathCerts = chain.dropLast(1), + anchor = TrustAnchor(topCert, null), + issuerCert = chain[1] + ) + } + + // Server omitted the root CA from the TLS chain โ€” locate the anchor in acceptedIssuers. + val anchorCert = findIssuerCert(topCert, acceptedIssuers) + ?: if (isTopSelfSigned) topCert else null + + if (anchorCert == null) { + val cpve = CertPathValidatorException( + "Unable to locate trust anchor for OCSP verification (issuer=${topCert.issuerX500Principal.name})", + null, + null, + -1, + PKIXReason.NO_TRUST_ANCHOR + ) + throw CertificateException(cpve.message, cpve) + } + + val issuerCert = if (chain.size >= 2) chain[1] else anchorCert + return ResolvedChain( + pathCerts = chain.toList(), + anchor = TrustAnchor(anchorCert, null), + issuerCert = issuerCert + ) + } + + private fun findIssuerCert( + cert: X509Certificate, + candidates: Array + ): X509Certificate? { + val matching = candidates.filter { it.subjectX500Principal == cert.issuerX500Principal } + if (matching.isEmpty()) return null + for (candidate in matching) { + try { + cert.verify(candidate.publicKey) + return candidate + } catch (_: GeneralSecurityException) { + // Try next candidate with the same subject DN + } + } + return matching.first() + } + + private fun enforceOcspSignaturePolicy( + stapledResponse: ByteArray, + issuerCert: X509Certificate, + certPath: java.security.cert.CertPath + ) { + val parsed = try { + parseBasicOcspResponse(stapledResponse) + } catch (e: IllegalArgumentException) { + val cpve = CertPathValidatorException( + "Malformed DER in stapled OCSP response: ${e.message}", + e, + certPath, + 0, + BasicReason.UNDETERMINED_REVOCATION_STATUS + ) + throw CertificateException(cpve.message, cpve) + } + + if (parsed.signatureAlgOid !in ALLOWED_OCSP_SIG_OIDS) { + val cpve = CertPathValidatorException( + "OCSP response signature algorithm OID ${parsed.signatureAlgOid} is not permitted " + + "by FIA_X509_EXT.1.1 (allowed: $ALLOWED_OCSP_SIG_OIDS)", + null, + certPath, + 0, + BasicReason.ALGORITHM_CONSTRAINED + ) + throw CertificateException(cpve.message, cpve) + } + + val signerCert = parsed.embeddedCerts.firstOrNull() ?: issuerCert + val pubKey = signerCert.publicKey + when (pubKey) { + is ECPublicKey -> { + val fieldSize = pubKey.params?.curve?.field?.fieldSize ?: 0 + if (fieldSize !in ALLOWED_EC_FIELD_SIZES) { + val cpve = CertPathValidatorException( + "OCSP signer EC key field size $fieldSize bits is not permitted " + + "by FIA_X509_EXT.1.1 (must be P-384 or P-521)", + null, + certPath, + 0, + BasicReason.ALGORITHM_CONSTRAINED + ) + throw CertificateException(cpve.message, cpve) + } + } + is RSAPublicKey -> { + val bits = pubKey.modulus.bitLength() + if (bits < MIN_RSA_KEY_BITS) { + val cpve = CertPathValidatorException( + "OCSP signer RSA key size $bits bits is less than minimum $MIN_RSA_KEY_BITS bits " + + "required by FIA_X509_EXT.1.1", + null, + certPath, + 0, + BasicReason.ALGORITHM_CONSTRAINED + ) + throw CertificateException(cpve.message, cpve) + } + } + else -> { + val cpve = CertPathValidatorException( + "Unsupported OCSP signer public key algorithm: ${pubKey.algorithm}", + null, + certPath, + 0, + BasicReason.ALGORITHM_CONSTRAINED + ) + throw CertificateException(cpve.message, cpve) + } + } + } + + internal data class ParsedBasicOcsp( + val signatureAlgOid: String, + val embeddedCerts: List + ) + + internal fun parseBasicOcspResponse(der: ByteArray): ParsedBasicOcsp { + val outer = DerReader(der).readTlv(expectedTag = 0x30) + val outerReader = DerReader(outer.value) + + // responseStatus ENUMERATED + val statusTlv = outerReader.readTlv(expectedTag = 0x0A) + val status = if (statusTlv.value.size == 1) statusTlv.value[0].toInt() and 0xFF else -1 + require(status == 0) { "OCSPResponseStatus is not successful (status=$status)" } + + // responseBytes [0] EXPLICIT ResponseBytes + require(outerReader.hasRemaining()) { "Missing responseBytes in OCSPResponse" } + val respBytesTag = outerReader.readTlv(expectedTag = 0xA0) + val respBytesSeq = DerReader(respBytesTag.value).readTlv(expectedTag = 0x30) + val respBytesReader = DerReader(respBytesSeq.value) + + val responseTypeOid = decodeOid(respBytesReader.readTlv(expectedTag = 0x06).value) + require(responseTypeOid == OID_ID_PKIX_OCSP_BASIC) { + "Unsupported OCSP responseType OID: $responseTypeOid" + } + val responseOctets = respBytesReader.readTlv(expectedTag = 0x04).value + + // BasicOCSPResponse ::= SEQUENCE { tbsResponseData, signatureAlgorithm, signature, certs [0] OPTIONAL } + val basicSeq = DerReader(responseOctets).readTlv(expectedTag = 0x30) + val basicReader = DerReader(basicSeq.value) + + // 1. tbsResponseData SEQUENCE + basicReader.readTlv(expectedTag = 0x30) + + // 2. signatureAlgorithm AlgorithmIdentifier ::= SEQUENCE { algorithm OID, parameters ANY OPTIONAL } + val sigAlgSeq = basicReader.readTlv(expectedTag = 0x30) + val sigAlgOid = decodeOid(DerReader(sigAlgSeq.value).readTlv(expectedTag = 0x06).value) + + // 3. signature BIT STRING + basicReader.readTlv(expectedTag = 0x03) + + // 4. certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL + val certs = mutableListOf() + if (basicReader.hasRemaining()) { + val certsWrapper = basicReader.readTlv(expectedTag = 0xA0) + val certsSeq = DerReader(certsWrapper.value).readTlv(expectedTag = 0x30) + val certsReader = DerReader(certsSeq.value) + val cf = CertificateFactory.getInstance("X.509") + while (certsReader.hasRemaining()) { + val certTlv = certsReader.readTlv(expectedTag = 0x30) + val cert = cf.generateCertificate(ByteArrayInputStream(certTlv.fullEncoded)) as X509Certificate + certs.add(cert) + } + } + + return ParsedBasicOcsp(sigAlgOid, certs) + } + + private data class DerTlv( + val tag: Int, + val value: ByteArray, + val fullEncoded: ByteArray + ) + + private class DerReader(private val data: ByteArray) { + private var pos = 0 + + fun hasRemaining(): Boolean = pos < data.size + + fun readTlv(expectedTag: Int? = null): DerTlv { + val start = pos + require(pos < data.size) { "Unexpected end of DER input" } + val tag = data[pos++].toInt() and 0xFF + if (expectedTag != null) { + require(tag == expectedTag) { + "Expected DER tag 0x${expectedTag.toString(16)}, got 0x${tag.toString(16)}" + } + } + require(pos < data.size) { "Truncated DER length" } + val firstLen = data[pos++].toInt() and 0xFF + val len = if ((firstLen and 0x80) == 0) { + firstLen + } else { + val numBytes = firstLen and 0x7F + require(numBytes in 1..4) { "Unsupported DER length encoding ($numBytes bytes)" } + require(pos + numBytes <= data.size) { "Truncated DER multi-byte length" } + var acc = 0 + for (i in 0 until numBytes) { + acc = (acc shl 8) or (data[pos++].toInt() and 0xFF) + } + acc + } + require(len >= 0 && pos + len <= data.size) { "DER value exceeds input bounds" } + val value = data.copyOfRange(pos, pos + len) + pos += len + val fullEncoded = data.copyOfRange(start, pos) + return DerTlv(tag, value, fullEncoded) + } + } + + private fun decodeOid(bytes: ByteArray): String { + require(bytes.isNotEmpty()) { "Empty OID" } + val first = bytes[0].toInt() and 0xFF + val arc0 = minOf(first / 40, 2) + val arc1 = first - arc0 * 40 + val sb = StringBuilder().append(arc0).append('.').append(arc1) + var i = 1 + while (i < bytes.size) { + var value = BigInteger.ZERO + var b: Int + do { + require(i < bytes.size) { "Truncated OID subidentifier" } + b = bytes[i++].toInt() and 0xFF + value = value.shiftLeft(7).or(BigInteger.valueOf((b and 0x7F).toLong())) + } while ((b and 0x80) != 0) + sb.append('.').append(value) + } + return sb.toString() + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/VerifiableSSLSocketFactory.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/VerifiableSSLSocketFactory.kt new file mode 100644 index 0000000..cdcd288 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/kotlin/com/android/niap/cert/validator/VerifiableSSLSocketFactory.kt @@ -0,0 +1,639 @@ +/* + * Copyright 2026 Google LLC + * + * 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. + */ + +package com.android.niap.cert.validator + +import android.util.Log +import java.io.ByteArrayOutputStream +import java.io.FilterInputStream +import java.io.FilterOutputStream +import java.io.InputStream +import java.io.OutputStream +import java.net.InetAddress +import java.net.Socket +import java.net.SocketAddress +import java.nio.channels.SocketChannel +import java.util.Collections +import java.util.WeakHashMap +import javax.net.ssl.SSLHandshakeException +import javax.net.ssl.SSLSocket +import javax.net.ssl.SSLSocketFactory + +/** + * Holds TLS 1.2 wire-captured OCSP staple state for a single [SSLSocket] handshake. + */ +internal class WireOcspCapture { + @Volatile var ocspResponse: ByteArray? = null + @Volatile var negotiatedTls13: Boolean = false +} + +/** + * Synchronized weak-key registry correlating each [SSLSocket] created by + * [VerifiableSSLSocketFactory] with its underlying [WireOcspCapture]. + */ +internal object WireOcspRegistry { + private val captures = Collections.synchronizedMap(WeakHashMap()) + + fun register(socket: SSLSocket, capture: WireOcspCapture) { + captures[socket] = capture + } + + fun lookup(socket: SSLSocket?): WireOcspCapture? = + if (socket == null) null else captures[socket] +} + +/** + * [SSLSocketFactory] wrapper that enforces protocol versions, cipher suite allowlists + * (for both TLS 1.2 and TLS 1.3), mandatory TLS handshake extensions such as + * Extended Master Secret (EMS, RFC 7627 / FCS_TLSC_EXT.1), and TLS 1.2 wire-level + * `CertificateStatus` (OCSP staple) capture on the underlying socket stream while + * keeping platform Conscrypt [SSLSocket] instances intact. + */ +class VerifiableSSLSocketFactory( + private val delegate: SSLSocketFactory, + private val allowedCipherSuites: Array? = NiapTlsPolicy.DEFAULT_SUITE_NAMES, + private val requireExtendedMasterSecret: Boolean = true, + private val enabledProtocols: Array = NiapTlsPolicy.allowedProtocols(enforceTls12 = false) +) : SSLSocketFactory() { + + private val allowTls13: Boolean = enabledProtocols.any { it == "TLSv1.3" } + + private val allowedCipherCodePoints: Set? = + allowedCipherSuites?.let { NiapTlsPolicy.codePointsForNames(it, allowTls13) } + + private val needsInterposition: Boolean = + requireExtendedMasterSecret || allowedCipherCodePoints != null || !NiapTlsPolicy.isPublicStapleApiAvailable + + override fun getDefaultCipherSuites(): Array = + allowedCipherSuites ?: delegate.defaultCipherSuites + + override fun getSupportedCipherSuites(): Array = + allowedCipherSuites ?: delegate.supportedCipherSuites + + override fun createSocket(s: Socket?, host: String?, port: Int, autoClose: Boolean): Socket { + requireNotNull(s) { "Underlying socket must not be null" } + val raw = if (needsInterposition && s !is VerifiableRawSocket) { + VerifiableRawSocket(s, requireExtendedMasterSecret, allowedCipherCodePoints) + } else { + s + } + val sslSocket = (delegate.createSocket(raw, host, port, autoClose) as SSLSocket) + .also(::applySocketPolicy) + if (raw is VerifiableRawSocket) { + WireOcspRegistry.register(sslSocket, raw.ocspCapture) + } + return sslSocket + } + + override fun createSocket(host: String?, port: Int): Socket = + createFromRawSocket({ Socket(host, port) }, host, port) { delegate.createSocket(host, port) } + + override fun createSocket(host: String?, port: Int, localHost: InetAddress?, localPort: Int): Socket = + createFromRawSocket({ Socket(host, port, localHost, localPort) }, host, port) { + delegate.createSocket(host, port, localHost, localPort) + } + + override fun createSocket(host: InetAddress?, port: Int): Socket = + createFromRawSocket({ Socket(host, port) }, host?.hostAddress, port) { + delegate.createSocket(host, port) + } + + override fun createSocket(address: InetAddress?, port: Int, localAddress: InetAddress?, localPort: Int): Socket = + createFromRawSocket({ Socket(address, port, localAddress, localPort) }, address?.hostAddress, port) { + delegate.createSocket(address, port, localAddress, localPort) + } + + private inline fun createFromRawSocket( + rawFactory: () -> Socket, + host: String?, + port: Int, + fallback: () -> Socket + ): Socket { + if (!needsInterposition) { + return (fallback() as SSLSocket).also(::applySocketPolicy) + } + val raw = rawFactory() + return try { + createSocket(raw, host, port, true) + } catch (t: Throwable) { + runCatching { raw.close() } + throw t + } + } + + private fun applySocketPolicy(sslSocket: SSLSocket) { + val supportedProtos = sslSocket.supportedProtocols.toSet() + val targetProtos = enabledProtocols.filter { it in supportedProtos }.toTypedArray() + if (targetProtos.isNotEmpty()) { + sslSocket.enabledProtocols = targetProtos + } + if (allowedCipherSuites != null) { + val supportedCiphers = sslSocket.supportedCipherSuites.toSet() + val targetCiphers = allowedCipherSuites.filter { it in supportedCiphers }.toTypedArray() + if (targetCiphers.isNotEmpty()) { + sslSocket.enabledCipherSuites = targetCiphers + } + } + } +} + +internal object ServerHelloValidator { + internal const val MAX_PRE_HELLO_BYTES = 32768 + private const val MAX_RECORD_LEN = 18432 + private const val EXT_EMS = 0x0017 + private const val EXT_SUPPORTED_VERSIONS = 0x002B + private const val TLS_1_3 = 0x0304 + + // RFC 8446 SHA-256("HelloRetryRequest") + private val HRR_RANDOM = byteArrayOf( + 0xCF.toByte(), 0x21, 0xAD.toByte(), 0x74, 0xE5.toByte(), 0x9A.toByte(), 0x61, 0x11, + 0xBE.toByte(), 0x1D, 0x8C.toByte(), 0x02, 0x1E, 0x65, 0xB8.toByte(), 0x91.toByte(), + 0xC2.toByte(), 0xA2.toByte(), 0x11, 0x16, 0x7A, 0xBB.toByte(), 0x8C.toByte(), 0x5E, + 0x07, 0x9E.toByte(), 0x09, 0xE2.toByte(), 0xC8.toByte(), 0xA8.toByte(), 0x33, 0x9C.toByte() + ) + + sealed interface Result { + data object NeedMoreBytes : Result + data class HelloRetryRequest(val consumedBytes: Int) : Result + data class PassThrough(val isTls13: Boolean = false) : Result + data class Reject(val reason: String) : Result + } + + fun inspect( + wire: ByteArray, + allowCcs: Boolean = false, + requireEms: Boolean = true, + allowedCipherSuites: Set? = null + ): Result { + if (wire.size > MAX_PRE_HELLO_BYTES) { + return Result.Reject("Pre-ServerHello data exceeded $MAX_PRE_HELLO_BYTES bytes") + } + val hsBuf = ByteArrayOutputStream() + var off = 0 + while (off + 5 <= wire.size) { + val type = wire[off].toInt() and 0xFF + val len = u16(wire, off + 3) + if (len !in 1..MAX_RECORD_LEN) return Result.Reject("Invalid TLS record length: $len") + val avail = minOf(len, wire.size - (off + 5)) + when (type) { + 0x16 -> { // Handshake + if (avail > 0) hsBuf.write(wire, off + 5, avail) + if (hasCompleteFirstMessage(hsBuf) || avail < len) { + if (avail == len) off += 5 + len + break + } + } + 0x15 -> { // Alert + if (avail < 2) return Result.NeedMoreBytes + if ((wire[off + 5].toInt() and 0xFF) == 2) return Result.PassThrough(isTls13 = false) + if (avail < len) return Result.NeedMoreBytes + } + 0x14 -> { // ChangeCipherSpec (allowed after TLS 1.3 HRR) + if (!allowCcs || len != 1) return Result.Reject("Unexpected ChangeCipherSpec") + if (avail < 1) return Result.NeedMoreBytes + } + else -> return Result.Reject("Unexpected TLS record type 0x${type.toString(16)}") + } + off += 5 + len + } + + val hs = hsBuf.toByteArray() + if (hs.size < 4) return Result.NeedMoreBytes + val hsType = hs[0].toInt() and 0xFF + val hsLen = ((hs[1].toInt() and 0xFF) shl 16) or u16(hs, 2) + if (hsType != 0x02) return Result.Reject("Expected ServerHello (0x02), got 0x${hsType.toString(16)}") + if (hsLen > MAX_PRE_HELLO_BYTES) return Result.Reject("Excessive ServerHello length: $hsLen") + if (hs.size < 4 + hsLen) return Result.NeedMoreBytes + + return checkServerHello( + body = hs.copyOfRange(4, 4 + hsLen), + consumedBytes = off, + requireEms = requireEms, + allowedCipherSuites = allowedCipherSuites + ) + } + + private fun checkServerHello( + body: ByteArray, + consumedBytes: Int, + requireEms: Boolean, + allowedCipherSuites: Set? + ): Result { + if (body.size < 38) return Result.Reject("Malformed ServerHello: length=${body.size}") + val legacyVer = u16(body, 0) + val isHrr = body.copyOfRange(2, 34).contentEquals(HRR_RANDOM) + val sidLen = body[34].toInt() and 0xFF + val cipherOff = 35 + sidLen + var pos = cipherOff + 3 + if (sidLen > 32 || pos > body.size) return Result.Reject("Malformed ServerHello session_id") + + val cipherSuite = u16(body, cipherOff) + + var hasEms = false + var supportedVer: Int? = null + if (pos < body.size) { + if (pos + 2 > body.size) return Result.Reject("Truncated ServerHello extensions length") + val extTotal = u16(body, pos) + pos += 2 + if (pos + extTotal != body.size) return Result.Reject("ServerHello extensions length mismatch") + val seen = HashSet() + while (pos < body.size) { + if (pos + 4 > body.size) return Result.Reject("Truncated ServerHello extension header") + val extType = u16(body, pos) + val extLen = u16(body, pos + 2) + pos += 4 + if (pos + extLen > body.size || !seen.add(extType)) { + return Result.Reject("Invalid or duplicate extension 0x${extType.toString(16)}") + } + when (extType) { + EXT_EMS -> { + if (extLen != 0) return Result.Reject("Non-empty EMS extension") + hasEms = true + } + EXT_SUPPORTED_VERSIONS -> { + if (extLen != 2) return Result.Reject("Invalid supported_versions length") + supportedVer = u16(body, pos) + } + } + pos += extLen + } + } + + if (allowedCipherSuites != null && cipherSuite !in allowedCipherSuites) { + return Result.Reject( + "Server selected cipher suite ${NiapTlsPolicy.describeCipherSuite(cipherSuite)}, " + + "which is not in the NIAP allowlist" + ) + } + + val negotiatedVer = supportedVer ?: legacyVer + if (negotiatedVer >= TLS_1_3) { + return if (isHrr) Result.HelloRetryRequest(consumedBytes) else Result.PassThrough(isTls13 = true) + } + return if (!requireEms || hasEms) { + Result.PassThrough(isTls13 = false) + } else { + Result.Reject( + "TLS ServerHello (0x${negotiatedVer.toString(16)}) omitted mandatory extended_master_secret (EMS) extension" + ) + } + } + + private fun hasCompleteFirstMessage(buf: ByteArrayOutputStream): Boolean { + if (buf.size() < 4) return false + val b = buf.toByteArray() + val len = ((b[1].toInt() and 0xFF) shl 16) or u16(b, 2) + return b.size >= 4 + len + } + + private fun u16(b: ByteArray, off: Int): Int = + ((b[off].toInt() and 0xFF) shl 8) or (b[off + 1].toInt() and 0xFF) +} + +internal class Tls12HandshakeTap( + private val capture: WireOcspCapture +) { + companion object { + private const val MAX_RECORD_LEN = 18432 + internal const val MAX_CERT_STATUS_BYTES = 65536 + private const val RECORD_HANDSHAKE = 0x16 + private const val HS_CERTIFICATE_STATUS = 0x16 // 22 + private const val HS_SERVER_HELLO_DONE = 0x0E // 14 + private const val STATUS_TYPE_OCSP = 0x01 + } + + private val recHeader = ByteArray(5) + private var recHeaderPos = 0 + private var recBytesRemaining = 0 + + private val hsHeader = ByteArray(4) + private var hsHeaderPos = 0 + private var hsType = 0 + private var hsBytesRemaining = 0 + private var certStatusBuf: ByteArrayOutputStream? = null + + var done: Boolean = false + private set + + fun isIncompleteCertificateStatus(): Boolean = certStatusBuf != null + + /** + * Inspects incoming TLS wire bytes without modifying them. + * Stops automatically at `ServerHelloDone` or any non-handshake record (such as `ChangeCipherSpec`). + * + * @return null on success, or an error message if a `CertificateStatus` message or record is malformed. + */ + fun feed(data: ByteArray, off: Int, len: Int): String? { + var i = off + val end = off + len + while (i < end && !done) { + if (recBytesRemaining == 0) { + val take = minOf(5 - recHeaderPos, end - i) + System.arraycopy(data, i, recHeader, recHeaderPos, take) + recHeaderPos += take + i += take + if (recHeaderPos == 5) { + recHeaderPos = 0 + val recType = recHeader[0].toInt() and 0xFF + val recLen = ((recHeader[3].toInt() and 0xFF) shl 8) or (recHeader[4].toInt() and 0xFF) + if (recType != RECORD_HANDSHAKE) { + if (certStatusBuf != null) { + return "Truncated TLS CertificateStatus message before non-handshake record 0x${recType.toString(16)}" + } + done = true + return null + } + if (recLen !in 1..MAX_RECORD_LEN) { + return "Invalid TLS handshake record length: $recLen" + } + recBytesRemaining = recLen + } + } else { + val chunkLen = minOf(recBytesRemaining, end - i) + val err = feedHandshakeBytes(data, i, chunkLen) + if (err != null) return err + i += chunkLen + recBytesRemaining -= chunkLen + } + } + return null + } + + private fun feedHandshakeBytes(data: ByteArray, off: Int, len: Int): String? { + var i = off + val end = off + len + while (i < end && !done) { + if (hsBytesRemaining == 0 && hsHeaderPos < 4) { + val take = minOf(4 - hsHeaderPos, end - i) + System.arraycopy(data, i, hsHeader, hsHeaderPos, take) + hsHeaderPos += take + i += take + if (hsHeaderPos == 4) { + hsType = hsHeader[0].toInt() and 0xFF + val hsLen = ((hsHeader[1].toInt() and 0xFF) shl 16) or + ((hsHeader[2].toInt() and 0xFF) shl 8) or + (hsHeader[3].toInt() and 0xFF) + hsHeaderPos = 0 + hsBytesRemaining = hsLen + + if (hsType == HS_CERTIFICATE_STATUS) { + if (hsLen == 0) { + return "Malformed TLS CertificateStatus message: empty body" + } + if (hsLen > MAX_CERT_STATUS_BYTES) { + return "TLS CertificateStatus message exceeded maximum size ($hsLen > $MAX_CERT_STATUS_BYTES bytes)" + } + certStatusBuf = ByteArrayOutputStream(minOf(hsLen, 4096)) + } else if (hsType == HS_SERVER_HELLO_DONE && hsLen == 0) { + done = true + return null + } + } + } else { + val take = minOf(hsBytesRemaining, end - i) + certStatusBuf?.write(data, i, take) + i += take + hsBytesRemaining -= take + if (hsBytesRemaining == 0) { + val buf = certStatusBuf + if (buf != null) { + certStatusBuf = null + val err = parseCertificateStatusBody(buf.toByteArray()) + if (err != null) return err + } else if (hsType == HS_SERVER_HELLO_DONE) { + done = true + return null + } + } + } + } + return null + } + + private fun parseCertificateStatusBody(body: ByteArray): String? { + if (body.size < 4) { + return "Malformed TLS CertificateStatus message: body too short (${body.size} bytes)" + } + val statusType = body[0].toInt() and 0xFF + if (statusType != STATUS_TYPE_OCSP) { + return "Unsupported TLS CertificateStatus status_type: $statusType (only status_type=1 ocsp is supported)" + } + val respLen = ((body[1].toInt() and 0xFF) shl 16) or + ((body[2].toInt() and 0xFF) shl 8) or + (body[3].toInt() and 0xFF) + if (respLen == 0) { + return "Malformed TLS CertificateStatus message: empty OCSPResponse" + } + if (4 + respLen != body.size) { + return "Malformed TLS CertificateStatus message: OCSPResponse length $respLen does not match body size ${body.size - 4}" + } + capture.ocspResponse = body.copyOfRange(4, 4 + respLen) + return null + } +} + +internal class VerifiableRawSocket( + private val delegate: Socket, + private val requireExtendedMasterSecret: Boolean = true, + private val allowedCipherCodePoints: Set? = null +) : Socket() { + @Volatile private var rejected = false + internal val ocspCapture = WireOcspCapture() + + private val verifiedIn: InputStream by lazy { + EmsVerifyingInputStream( + delegateIn = delegate.getInputStream(), + requireEms = requireExtendedMasterSecret, + allowedCipherSuites = allowedCipherCodePoints, + ocspCapture = ocspCapture, + onReject = ::sendFatalAlertAndAbort + ) + } + private val guardedOut: OutputStream by lazy { + object : FilterOutputStream(delegate.getOutputStream()) { + override fun write(b: Int) { if (!rejected) out.write(b) } + override fun write(b: ByteArray, off: Int, len: Int) { if (!rejected) out.write(b, off, len) } + override fun flush() { if (!rejected) out.flush() } + } + } + + private fun sendFatalAlertAndAbort() { + if (rejected) return + rejected = true + runCatching { + delegate.getOutputStream().apply { + write(byteArrayOf(0x15, 0x03, 0x03, 0x00, 0x02, 0x02, 0x28)) // fatal handshake_failure + flush() + } + } + runCatching { delegate.shutdownOutput() } + } + + override fun getInputStream(): InputStream = verifiedIn + override fun getOutputStream(): OutputStream = guardedOut + override fun getChannel(): SocketChannel? = null + + override fun connect(endpoint: SocketAddress?) = delegate.connect(endpoint) + override fun connect(endpoint: SocketAddress?, timeout: Int) = delegate.connect(endpoint, timeout) + override fun bind(bindpoint: SocketAddress?) = delegate.bind(bindpoint) + override fun getInetAddress(): InetAddress? = delegate.inetAddress + override fun getLocalAddress(): InetAddress = delegate.localAddress + override fun getPort(): Int = delegate.port + override fun getLocalPort(): Int = delegate.localPort + override fun getRemoteSocketAddress(): SocketAddress? = delegate.remoteSocketAddress + override fun getLocalSocketAddress(): SocketAddress? = delegate.localSocketAddress + override fun setTcpNoDelay(on: Boolean) { delegate.tcpNoDelay = on } + override fun getTcpNoDelay(): Boolean = delegate.tcpNoDelay + override fun setSoLinger(on: Boolean, linger: Int) = delegate.setSoLinger(on, linger) + override fun getSoLinger(): Int = delegate.soLinger + override fun sendUrgentData(data: Int) = delegate.sendUrgentData(data) + override fun setOOBInline(on: Boolean) { delegate.oobInline = on } + override fun getOOBInline(): Boolean = delegate.oobInline + override fun setSoTimeout(timeout: Int) { delegate.soTimeout = timeout } + override fun getSoTimeout(): Int = delegate.soTimeout + override fun setSendBufferSize(size: Int) { delegate.sendBufferSize = size } + override fun getSendBufferSize(): Int = delegate.sendBufferSize + override fun setReceiveBufferSize(size: Int) { delegate.receiveBufferSize = size } + override fun getReceiveBufferSize(): Int = delegate.receiveBufferSize + override fun setKeepAlive(on: Boolean) { delegate.keepAlive = on } + override fun getKeepAlive(): Boolean = delegate.keepAlive + override fun setTrafficClass(tc: Int) { delegate.trafficClass = tc } + override fun getTrafficClass(): Int = delegate.trafficClass + override fun setReuseAddress(on: Boolean) { delegate.reuseAddress = on } + override fun getReuseAddress(): Boolean = delegate.reuseAddress + @Synchronized override fun close() = delegate.close() + override fun shutdownInput() = delegate.shutdownInput() + override fun shutdownOutput() = delegate.shutdownOutput() + override fun isConnected(): Boolean = delegate.isConnected + override fun isBound(): Boolean = delegate.isBound + override fun isClosed(): Boolean = delegate.isClosed + override fun isInputShutdown(): Boolean = delegate.isInputShutdown + override fun isOutputShutdown(): Boolean = delegate.isOutputShutdown + override fun setPerformancePreferences(c: Int, l: Int, b: Int) = delegate.setPerformancePreferences(c, l, b) +} + +internal class EmsVerifyingInputStream( + delegateIn: InputStream, + private val requireEms: Boolean = true, + private val allowedCipherSuites: Set? = null, + private val ocspCapture: WireOcspCapture? = null, + private val onReject: () -> Unit +) : FilterInputStream(delegateIn) { + private val pending = ByteArrayOutputStream() + private var replay: ByteArray? = null + private var replayPos = 0 + private var verified = false + private var seenHrr = false + private var tls12Tap: Tls12HandshakeTap? = null + private var failure: String? = null + + override fun read(): Int { + val one = ByteArray(1) + return if (read(one, 0, 1) == -1) -1 else (one[0].toInt() and 0xFF) + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (off < 0 || len < 0 || len > b.size - off) throw IndexOutOfBoundsException() + if (len == 0) return 0 + failure?.let { throw SSLHandshakeException(it) } + + replay?.let { buf -> + val n = minOf(len, buf.size - replayPos) + System.arraycopy(buf, replayPos, b, off, n) + replayPos += n + if (replayPos >= buf.size) { replay = null; replayPos = 0 } + return n + } + if (verified) { + val n = `in`.read(b, off, len) + val tap = tls12Tap + if (tap != null) { + if (n == -1) { + if (tap.isIncompleteCertificateStatus()) { + failHandshake("TLS connection closed before CertificateStatus completed") + } + tls12Tap = null + return -1 + } + val err = tap.feed(b, off, n) + if (err != null) failHandshake(err) + if (tap.done) tls12Tap = null + } + return n + } + + val chunk = ByteArray(4096) + while (true) { + if (pending.size() > 0) { + val wire = pending.toByteArray() + val res = ServerHelloValidator.inspect( + wire = wire, + allowCcs = seenHrr, + requireEms = requireEms, + allowedCipherSuites = allowedCipherSuites + ) + when (res) { + is ServerHelloValidator.Result.PassThrough -> { + verified = true + pending.reset() + if (res.isTls13) { + ocspCapture?.negotiatedTls13 = true + } else if (ocspCapture != null) { + val tap = Tls12HandshakeTap(ocspCapture) + val err = tap.feed(wire, 0, wire.size) + if (err != null) failHandshake(err) + if (!tap.done) { + tls12Tap = tap + } + } + replay = wire + return read(b, off, len) + } + is ServerHelloValidator.Result.HelloRetryRequest -> { + seenHrr = true + pending.reset() + val consumed = minOf(res.consumedBytes, wire.size) + replay = wire.copyOfRange(0, consumed) + if (consumed < wire.size) { + pending.write(wire, consumed, wire.size - consumed) + } + return read(b, off, len) + } + is ServerHelloValidator.Result.Reject -> failHandshake(res.reason) + ServerHelloValidator.Result.NeedMoreBytes -> Unit + } + } + val n = `in`.read(chunk) + if (n == -1) { + if (pending.size() == 0) { verified = true; return -1 } + failHandshake("TLS connection closed before ServerHello completed") + } + if (pending.size() + n > ServerHelloValidator.MAX_PRE_HELLO_BYTES) { + failHandshake("TLS pre-ServerHello buffer limit exceeded") + } + pending.write(chunk, 0, n) + } + } + + override fun available(): Int = (replay?.let { it.size - replayPos } ?: 0) + `in`.available() + + private fun failHandshake(reason: String): Nothing { + runCatching { Log.e("VerifiableSSLSocket", reason) } + failure = reason + onReject() + throw SSLHandshakeException(reason) + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/main/res/xml/niap_security_config.xml b/niap-cc/niap-android-cert-ext/cert-lib/src/main/res/xml/niap_security_config.xml new file mode 100644 index 0000000..aa5739c --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/main/res/xml/niap_security_config.xml @@ -0,0 +1,64 @@ + + + + + true + + + + *.COM + *.NET + *.ORG + *.GOV + *.EDU + + + + + TLS_AES_128_GCM_SHA256 + TLS_AES_256_GCM_SHA384 + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + + + + BOTH_CA + + + + + false + + + true + + + true + + + true + + + serverAuth + + + true + diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapCertHelperCacheTest.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapCertHelperCacheTest.kt new file mode 100644 index 0000000..6ebd6ef --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapCertHelperCacheTest.kt @@ -0,0 +1,90 @@ +/* + * Copyright 2026 Google LLC + * + * 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. + */ + +package com.android.niap.cert.validator + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertSame +import org.junit.Test +import java.net.Socket +import java.net.URL +import java.security.Principal +import java.security.PrivateKey +import java.security.cert.X509Certificate +import javax.net.ssl.X509KeyManager + +class NiapCertHelperCacheTest { + + private class DummyKeyManager : X509KeyManager { + override fun getClientAliases(keyType: String?, issuers: Array?): Array? = null + override fun chooseClientAlias(keyType: Array?, issuers: Array?, socket: Socket?): String? = null + override fun getServerAliases(keyType: String?, issuers: Array?): Array? = null + override fun chooseServerAlias(keyType: String?, issuers: Array?, socket: Socket?): String? = null + override fun getCertificateChain(alias: String?): Array? = null + override fun getPrivateKey(alias: String?): PrivateKey? = null + } + + @Test + fun openConnectionAndCreateSocketFactory_reuseSameCachedStack() { + val helper = NiapCertHelper.createForTesting( + trustAnchorPolicy = NiapCertHelper.TrustAnchorOptions.SYSTEM_CA_ONLY + ) + val factory1 = helper.createSSLSocketFactory() + val factory2 = helper.createSSLSocketFactory() + val conn1 = helper.openConnection(URL("https://example.com")) + val conn2 = helper.openConnection(URL("https://example.com")) + + assertSame(factory1, factory2) + assertSame(factory1, conn1.sslSocketFactory) + assertSame(factory1, conn2.sslSocketFactory) + assertEquals(1, helper.cacheSizeForTesting()) + } + + @Test + fun keyManagerIdentity_partitionsCacheEntries() { + val helper = NiapCertHelper.createForTesting( + trustAnchorPolicy = NiapCertHelper.TrustAnchorOptions.SYSTEM_CA_ONLY + ) + val km1 = DummyKeyManager() + val km2 = DummyKeyManager() + + val fNoKm = helper.createSSLSocketFactory() + val fKm1a = helper.createSSLSocketFactory(km1) + val fKm1b = helper.createSSLSocketFactory(km1) + val fKm2 = helper.createSSLSocketFactory(km2) + + assertSame(fKm1a, fKm1b) + assertNotSame(fNoKm, fKm1a) + assertNotSame(fKm1a, fKm2) + assertEquals(3, helper.cacheSizeForTesting()) + } + + @Test + fun clearCache_evictsCachedFactories() { + val helper = NiapCertHelper.createForTesting( + trustAnchorPolicy = NiapCertHelper.TrustAnchorOptions.SYSTEM_CA_ONLY + ) + val before = helper.createSSLSocketFactory() + assertEquals(1, helper.cacheSizeForTesting()) + + helper.clearCache() + assertEquals(0, helper.cacheSizeForTesting()) + + val after = helper.createSSLSocketFactory() + assertNotSame(before, after) + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapCertValidatorTest.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapCertValidatorTest.kt new file mode 100644 index 0000000..f38cc9b --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapCertValidatorTest.kt @@ -0,0 +1,82 @@ +/* + * Copyright 2026 Google LLC + * + * 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. + */ + +package com.android.niap.cert.validator + +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.math.BigInteger +import java.security.Principal +import java.security.PublicKey +import java.security.cert.CertificateException +import java.security.cert.X509Certificate +import java.util.Date + +class NiapCertValidatorTest { + + private class FakeUnsupportedKeyCert(private val keyAlgorithm: String) : X509Certificate() { + override fun getSigAlgName(): String = "SHA384withDSA" + override fun getPublicKey(): PublicKey = object : PublicKey { + override fun getAlgorithm(): String = keyAlgorithm + override fun getFormat(): String = "X.509" + override fun getEncoded(): ByteArray = ByteArray(0) + } + override fun hasUnsupportedCriticalExtension(): Boolean = false + override fun getCriticalExtensionOIDs(): MutableSet = mutableSetOf() + override fun getNonCriticalExtensionOIDs(): MutableSet = mutableSetOf() + override fun getExtensionValue(oid: String?): ByteArray? = null + override fun getEncoded(): ByteArray = ByteArray(0) + override fun verify(key: PublicKey?) = Unit + override fun verify(key: PublicKey?, sigProvider: String?) = Unit + override fun toString(): String = "FakeUnsupportedKeyCert($keyAlgorithm)" + override fun checkValidity() = Unit + override fun checkValidity(date: Date?) = Unit + override fun getVersion(): Int = 3 + override fun getSerialNumber(): BigInteger = BigInteger.ONE + override fun getIssuerDN(): Principal = Principal { "CN=TestCA" } + override fun getSubjectDN(): Principal = Principal { "CN=TestLeaf" } + override fun getNotBefore(): Date = Date(0) + override fun getNotAfter(): Date = Date(Long.MAX_VALUE) + override fun getTBSCertificate(): ByteArray = ByteArray(0) + override fun getSignature(): ByteArray = ByteArray(0) + override fun getSigAlgOID(): String = "2.16.840.1.101.3.4.3.3" + override fun getSigAlgParams(): ByteArray? = null + override fun getIssuerUniqueID(): BooleanArray? = null + override fun getSubjectUniqueID(): BooleanArray? = null + override fun getKeyUsage(): BooleanArray? = null + override fun getBasicConstraints(): Int = -1 + } + + @Test + fun checkAlgorithmConstraints_rejectsUnsupportedPublicKeyTypes() { + val validator = NiapCertValidator( + strictSigAlg = true, + enforceMandatoryExtensions = false, + enforceEku = false, + enforceCaConstraints = false + ) + try { + validator.validateCertificate(arrayOf(FakeUnsupportedKeyCert("Ed25519"))) + fail("Expected CertificateException for unsupported public key type") + } catch (e: CertificateException) { + assertTrue( + "Unexpected message: ${e.message}", + e.message!!.contains("Unsupported public key type: Ed25519") + ) + } + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapTlsPolicyTest.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapTlsPolicyTest.kt new file mode 100644 index 0000000..b1f68ec --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapTlsPolicyTest.kt @@ -0,0 +1,113 @@ +/* + * Copyright 2026 Google LLC + * + * 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. + */ + +package com.android.niap.cert.validator + +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +class NiapTlsPolicyTest { + + @After + fun tearDown() { + NiapTlsPolicy.resetCapabilityStateForTesting() + } + + @Test + fun whenPublicStapleApiUnavailable_pinsToTls12OnlyRegardlessOfConfig() { + NiapTlsPolicy.overridePublicStapleApiAvailable = false + + assertTrue(NiapTlsPolicy.effectiveEnforceTls12(enforceTls12 = false)) + assertTrue(NiapTlsPolicy.effectiveEnforceTls12(enforceTls12 = true)) + assertArrayEquals(arrayOf("TLSv1.2"), NiapTlsPolicy.allowedProtocols(enforceTls12 = false)) + assertArrayEquals(arrayOf("TLSv1.2"), NiapTlsPolicy.allowedProtocols(enforceTls12 = true)) + + val suites = NiapTlsPolicy.suiteNamesForPolicy(NiapTlsPolicy.APPROVED_SUITES, enforceTls12 = false) + assertTrue(suites.isNotEmpty()) + assertTrue(suites.none { it.startsWith("TLS_AES_") }) + } + + @Test + fun whenPublicStapleApiAvailable_respectsEnforceTls12Config() { + NiapTlsPolicy.overridePublicStapleApiAvailable = true + + assertFalse(NiapTlsPolicy.effectiveEnforceTls12(enforceTls12 = false)) + assertTrue(NiapTlsPolicy.effectiveEnforceTls12(enforceTls12 = true)) + assertArrayEquals( + arrayOf("TLSv1.3", "TLSv1.2"), + NiapTlsPolicy.allowedProtocols(enforceTls12 = false) + ) + assertArrayEquals( + arrayOf("TLSv1.2"), + NiapTlsPolicy.allowedProtocols(enforceTls12 = true) + ) + + val bothSuites = NiapTlsPolicy.suiteNamesForPolicy(NiapTlsPolicy.APPROVED_SUITES, enforceTls12 = false) + assertTrue(bothSuites.any { it == "TLS_AES_128_GCM_SHA256" }) + assertTrue(bothSuites.any { it == "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" }) + + val tls12Suites = NiapTlsPolicy.suiteNamesForPolicy(NiapTlsPolicy.APPROVED_SUITES, enforceTls12 = true) + assertTrue(tls12Suites.none { it.startsWith("TLS_AES_") }) + } + + @Test + fun jvmRuntime_detectsPublicStapleApiAvailable() { + NiapTlsPolicy.resetCapabilityStateForTesting() + // Desktop JDK 9+ provides ExtendedSSLSession.getStatusResponses() + assertTrue(NiapTlsPolicy.isPublicStapleApiAvailable) + } + + @Test + fun forceTls12WireCapture_refusedWhenNotDebuggable() { + NiapTlsPolicy.overridePublicStapleApiAvailable = true + try { + NiapTlsPolicy.setForceTls12WireCaptureForTesting(isDebuggable = false, enabled = true) + fail("Expected IllegalStateException when app is not debuggable") + } catch (e: IllegalStateException) { + assertTrue( + "Expected FLAG_DEBUGGABLE message, got: ${e.message}", + e.message!!.contains("debuggable") + ) + } + assertFalse(NiapTlsPolicy.isForceTls12WireCaptureEnabled) + assertTrue(NiapTlsPolicy.isPublicStapleApiAvailable) + } + + @Test + fun forceTls12WireCapture_whenDebuggableForcesApi36PathAndRestoresOnDisable() { + NiapTlsPolicy.overridePublicStapleApiAvailable = true + assertTrue(NiapTlsPolicy.isPublicStapleApiAvailable) + assertArrayEquals(arrayOf("TLSv1.3", "TLSv1.2"), NiapTlsPolicy.allowedProtocols(enforceTls12 = false)) + + NiapTlsPolicy.setForceTls12WireCaptureForTesting(isDebuggable = true, enabled = true) + assertTrue(NiapTlsPolicy.isForceTls12WireCaptureEnabled) + assertFalse(NiapTlsPolicy.isPublicStapleApiAvailable) + assertTrue(NiapTlsPolicy.effectiveEnforceTls12(enforceTls12 = false)) + assertArrayEquals(arrayOf("TLSv1.2"), NiapTlsPolicy.allowedProtocols(enforceTls12 = false)) + val forcedSuites = NiapTlsPolicy.suiteNamesForPolicy(NiapTlsPolicy.APPROVED_SUITES, enforceTls12 = false) + assertTrue(forcedSuites.isNotEmpty()) + assertTrue(forcedSuites.none { it.startsWith("TLS_AES_") }) + + NiapTlsPolicy.setForceTls12WireCaptureForTesting(isDebuggable = true, enabled = false) + assertFalse(NiapTlsPolicy.isForceTls12WireCaptureEnabled) + assertTrue(NiapTlsPolicy.isPublicStapleApiAvailable) + assertArrayEquals(arrayOf("TLSv1.3", "TLSv1.2"), NiapTlsPolicy.allowedProtocols(enforceTls12 = false)) + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapX509TrustManagerTest.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapX509TrustManagerTest.kt new file mode 100644 index 0000000..58b4b46 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/NiapX509TrustManagerTest.kt @@ -0,0 +1,342 @@ +/* + * Copyright 2026 Google LLC + * + * 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. + */ + +package com.android.niap.cert.validator + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.net.Socket +import java.security.cert.CertPathBuilderException +import java.security.cert.CertPathValidatorException +import java.security.cert.CertificateException +import java.security.cert.CertificateExpiredException +import java.security.cert.CertificateNotYetValidException +import java.security.cert.PKIXReason +import java.security.cert.X509Certificate +import javax.net.ssl.SSLContext +import javax.net.ssl.SSLEngine +import javax.net.ssl.X509ExtendedTrustManager +import javax.net.ssl.X509TrustManager + +class NiapX509TrustManagerTest { + + private class RecordingExtendedTrustManager( + private val onServer: () -> Unit = {}, + private val onClient: () -> Unit = {} + ) : X509ExtendedTrustManager() { + val calls = mutableListOf() + var lastSocket: Socket? = null + var lastEngine: SSLEngine? = null + + override fun checkClientTrusted(chain: Array?, authType: String?) { + calls.add("client-2arg") + onClient() + } + + override fun checkClientTrusted( + chain: Array?, + authType: String?, + socket: Socket? + ) { + calls.add("client-socket") + lastSocket = socket + onClient() + } + + override fun checkClientTrusted( + chain: Array?, + authType: String?, + engine: SSLEngine? + ) { + calls.add("client-engine") + lastEngine = engine + onClient() + } + + override fun checkServerTrusted(chain: Array?, authType: String?) { + calls.add("server-2arg") + onServer() + } + + override fun checkServerTrusted( + chain: Array?, + authType: String?, + socket: Socket? + ) { + calls.add("server-socket") + lastSocket = socket + onServer() + } + + override fun checkServerTrusted( + chain: Array?, + authType: String?, + engine: SSLEngine? + ) { + calls.add("server-engine") + lastEngine = engine + onServer() + } + + override fun getAcceptedIssuers(): Array = emptyArray() + } + + private class RecordingPlainTrustManager : X509TrustManager { + val calls = mutableListOf() + + override fun checkClientTrusted(chain: Array?, authType: String?) { + calls.add("client-2arg") + } + + override fun checkServerTrusted(chain: Array?, authType: String?) { + calls.add("server-2arg") + } + + override fun getAcceptedIssuers(): Array = emptyArray() + } + + @Test + fun niapTrustManager_delegatesToExtendedSocketAndEngineVariants() { + val delegate = RecordingExtendedTrustManager() + val tm = NiapX509TrustManager(delegate, NiapCertValidator()) + val socket = Socket() + val engine = SSLContext.getDefault().createSSLEngine() + + tm.checkServerTrusted(null, "ECDHE_ECDSA", socket) + tm.checkServerTrusted(null, "ECDHE_ECDSA", engine) + tm.checkClientTrusted(null, "ECDHE_ECDSA", socket) + tm.checkClientTrusted(null, "ECDHE_ECDSA", engine) + + assertEquals( + listOf("server-socket", "server-engine", "client-socket", "client-engine"), + delegate.calls + ) + assertSame(socket, delegate.lastSocket) + assertSame(engine, delegate.lastEngine) + } + + @Test + fun niapTrustManager_fallsBackToTwoArgWhenDelegateIsPlainTrustManager() { + val delegate = RecordingPlainTrustManager() + val tm = NiapX509TrustManager(delegate, NiapCertValidator()) + val socket = Socket() + val engine = SSLContext.getDefault().createSSLEngine() + + tm.checkServerTrusted(null, "ECDHE_ECDSA", socket) + tm.checkServerTrusted(null, "ECDHE_ECDSA", engine) + tm.checkClientTrusted(null, "ECDHE_ECDSA", socket) + tm.checkClientTrusted(null, "ECDHE_ECDSA", engine) + + assertEquals( + listOf("server-2arg", "server-2arg", "client-2arg", "client-2arg"), + delegate.calls + ) + } + + @Test + fun niapTrustManager_twoArgCheckServerTrustedFailsClosed() { + val delegate = RecordingExtendedTrustManager() + val tm = NiapX509TrustManager(delegate, NiapCertValidator()) + + try { + tm.checkServerTrusted(null, "ECDHE_ECDSA") + fail("Expected session-less checkServerTrusted to fail closed") + } catch (e: CertificateException) { + assertEquals( + "Revocation status unavailable: no TLS session available to verify the stapled OCSP response " + + "(use a session-aware X509ExtendedTrustManager call)", + e.message + ) + } + assertEquals(listOf("server-2arg"), delegate.calls) + } + + @Test + fun niapTrustManager_twoArgCheckServerTrustedPropagatesDelegateFailure() { + val expected = CertificateExpiredException("Certificate expired") + val delegate = RecordingExtendedTrustManager(onServer = { throw expected }) + val tm = NiapX509TrustManager(delegate, NiapCertValidator()) + + try { + tm.checkServerTrusted(null, "ECDHE_ECDSA") + fail("Expected delegate failure to propagate") + } catch (e: CertificateException) { + assertSame(expected, e) + } + assertEquals(listOf("server-2arg"), delegate.calls) + } + + @Test + fun combinedTrustManager_fallsBackToSystemOnConscryptTrustAnchorNotFound() { + val custom = RecordingExtendedTrustManager( + onServer = { + throw CertificateException( + CertPathValidatorException("Trust anchor for certification path not found.") + ) + } + ) + val system = RecordingExtendedTrustManager() + val combined = NiapCertHelper.CombinedTrustManager(system, custom) + val socket = Socket() + + combined.checkServerTrusted(null, "ECDHE_ECDSA", socket) + + assertEquals(listOf("server-socket"), custom.calls) + assertEquals(listOf("server-socket"), system.calls) + assertSame(socket, custom.lastSocket) + assertSame(socket, system.lastSocket) + } + + @Test + fun combinedTrustManager_fallsBackToSystemOnCertPathBuilderException() { + val custom = RecordingExtendedTrustManager( + onServer = { + throw CertificateException( + "PKIX path building failed", + CertPathBuilderException("unable to find valid certification path to requested target") + ) + } + ) + val system = RecordingExtendedTrustManager() + val combined = NiapCertHelper.CombinedTrustManager(system, custom) + val engine = SSLContext.getDefault().createSSLEngine() + + combined.checkServerTrusted(null, "ECDHE_ECDSA", engine) + + assertEquals(listOf("server-engine"), custom.calls) + assertEquals(listOf("server-engine"), system.calls) + assertSame(engine, system.lastEngine) + } + + @Test + fun combinedTrustManager_fallsBackToSystemOnPkixNoTrustAnchorReason() { + val custom = RecordingExtendedTrustManager( + onServer = { + throw CertificateException( + CertPathValidatorException("no anchor", null, null, -1, PKIXReason.NO_TRUST_ANCHOR) + ) + } + ) + val system = RecordingExtendedTrustManager() + val combined = NiapCertHelper.CombinedTrustManager(system, custom) + + combined.checkServerTrusted(null, "ECDHE_ECDSA") + + assertEquals(listOf("server-2arg"), custom.calls) + assertEquals(listOf("server-2arg"), system.calls) + } + + @Test + fun combinedTrustManager_doesNotFallBackOnRevocationFailure() { + val expected = CertificateException( + CertPathValidatorException( + "Certificate has been revoked", + null, + null, + -1, + CertPathValidatorException.BasicReason.REVOKED + ) + ) + val custom = RecordingExtendedTrustManager(onServer = { throw expected }) + val system = RecordingExtendedTrustManager() + val combined = NiapCertHelper.CombinedTrustManager(system, custom) + + try { + combined.checkServerTrusted(null, "ECDHE_ECDSA", Socket()) + fail("Expected revocation failure to be rethrown without falling back") + } catch (e: CertificateException) { + assertSame(expected, e) + } + assertTrue(system.calls.isEmpty()) + } + + @Test + fun combinedTrustManager_doesNotFallBackOnExpiredCertificate() { + val expected = CertificateExpiredException("Certificate expired") + val custom = RecordingExtendedTrustManager(onServer = { throw expected }) + val system = RecordingExtendedTrustManager() + val combined = NiapCertHelper.CombinedTrustManager(system, custom) + + try { + combined.checkServerTrusted(null, "ECDHE_ECDSA", Socket()) + fail("Expected expiry failure to be rethrown without falling back") + } catch (e: CertificateException) { + assertSame(expected, e) + } + assertTrue(system.calls.isEmpty()) + } + + @Test + fun combinedTrustManager_doesNotFallBackOnNotYetValidCertificate() { + val expected = CertificateNotYetValidException("Certificate not yet valid") + val custom = RecordingExtendedTrustManager(onServer = { throw expected }) + val system = RecordingExtendedTrustManager() + val combined = NiapCertHelper.CombinedTrustManager(system, custom) + + try { + combined.checkServerTrusted(null, "ECDHE_ECDSA") + fail("Expected not-yet-valid failure to be rethrown without falling back") + } catch (e: CertificateException) { + assertSame(expected, e) + } + assertTrue(system.calls.isEmpty()) + } + + @Test + fun combinedTrustManager_doesNotFallBackOnConstraintViolation() { + val expected = CertificateException( + CertPathValidatorException( + "Not a CA certificate", + null, + null, + -1, + PKIXReason.NOT_CA_CERT + ) + ) + val custom = RecordingExtendedTrustManager(onServer = { throw expected }) + val system = RecordingExtendedTrustManager() + val combined = NiapCertHelper.CombinedTrustManager(system, custom) + + try { + combined.checkServerTrusted(null, "ECDHE_ECDSA") + fail("Expected constraint failure to be rethrown without falling back") + } catch (e: CertificateException) { + assertSame(expected, e) + } + assertTrue(system.calls.isEmpty()) + } + + @Test + fun combinedTrustManager_doesNotFallBackOnUnknownCertificateException() { + val expected = CertificateException("Invalid signature") + val custom = RecordingExtendedTrustManager(onServer = { throw expected }) + val system = RecordingExtendedTrustManager() + val combined = NiapCertHelper.CombinedTrustManager(system, custom) + + try { + combined.checkServerTrusted(null, "ECDHE_ECDSA") + fail("Expected generic certificate failure to be rethrown without falling back") + } catch (e: CertificateException) { + assertSame(expected, e) + } + assertTrue(system.calls.isEmpty()) + assertFalse(NiapCertHelper.CombinedTrustManager.isTrustAnchorNotFound(expected)) + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/OcspStapleValidatorTest.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/OcspStapleValidatorTest.kt new file mode 100644 index 0000000..bf7a903 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/OcspStapleValidatorTest.kt @@ -0,0 +1,486 @@ +/* + * Copyright 2026 Google LLC + * + * 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. + */ + +package com.android.niap.cert.validator + +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.security.Principal +import java.security.cert.CertPathValidatorException +import java.security.cert.Certificate +import java.security.cert.CertificateException +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import javax.net.ssl.ExtendedSSLSession +import javax.net.ssl.HandshakeCompletedListener +import javax.net.ssl.SSLEngine +import javax.net.ssl.SSLEngineResult +import javax.net.ssl.SSLSession +import javax.net.ssl.SSLSessionContext +import javax.net.ssl.SSLSocket +import javax.net.ssl.X509TrustManager +import java.nio.ByteBuffer + +class OcspStapleValidatorTest { + + private fun loadResource(name: String): ByteArray { + val stream = javaClass.classLoader!!.getResourceAsStream("ocsp/$name") + ?: throw IllegalStateException("Missing test fixture: ocsp/$name") + return stream.use { it.readBytes() } + } + + private fun loadCert(name: String): X509Certificate { + val cf = CertificateFactory.getInstance("X.509") + return cf.generateCertificate(loadResource(name).inputStream()) as X509Certificate + } + + private val caCert by lazy { loadCert("ca.crt") } + private val leafCert by lazy { loadCert("server.crt") } + + private fun fakeTrustManager(anchors: Array = arrayOf(caCert)): X509TrustManager = + object : X509TrustManager { + override fun checkClientTrusted(chain: Array?, authType: String?) = Unit + override fun checkServerTrusted(chain: Array?, authType: String?) = Unit + override fun getAcceptedIssuers(): Array = anchors + } + + class FakeExtendedSession(private val responses: List) : ExtendedSSLSession() { + override fun getLocalSupportedSignatureAlgorithms(): Array = emptyArray() + override fun getPeerSupportedSignatureAlgorithms(): Array = emptyArray() + fun getStatusResponses(): List = responses + override fun getId(): ByteArray = ByteArray(0) + override fun getSessionContext(): SSLSessionContext? = null + override fun getCreationTime(): Long = 0L + override fun getLastAccessedTime(): Long = 0L + override fun invalidate() = Unit + override fun isValid(): Boolean = true + override fun putValue(name: String?, value: Any?) = Unit + override fun getValue(name: String?): Any? = null + override fun removeValue(name: String?) = Unit + override fun getValueNames(): Array = emptyArray() + override fun getPeerCertificates(): Array = emptyArray() + override fun getLocalCertificates(): Array? = null + @Deprecated("Deprecated in Java") + override fun getPeerCertificateChain(): Array = emptyArray() + override fun getPeerPrincipal(): Principal? = null + override fun getLocalPrincipal(): Principal? = null + override fun getCipherSuite(): String = "TLS_AES_256_GCM_SHA384" + override fun getProtocol(): String = "TLSv1.3" + override fun getPeerHost(): String = "localhost" + override fun getPeerPort(): Int = 443 + override fun getPacketBufferSize(): Int = 16384 + override fun getApplicationBufferSize(): Int = 16384 + } + + private fun fakeExtendedSession(responses: List): ExtendedSSLSession = + FakeExtendedSession(responses) + + private fun fakeSslSocket(handshakeSession: SSLSession?): SSLSocket = + object : SSLSocket() { + override fun getHandshakeSession(): SSLSession? = handshakeSession + override fun getSupportedCipherSuites(): Array = emptyArray() + override fun getEnabledCipherSuites(): Array = emptyArray() + override fun setEnabledCipherSuites(suites: Array?) = Unit + override fun getSupportedProtocols(): Array = emptyArray() + override fun getEnabledProtocols(): Array = emptyArray() + override fun setEnabledProtocols(protocols: Array?) = Unit + override fun getSession(): SSLSession? = handshakeSession + override fun addHandshakeCompletedListener(listener: HandshakeCompletedListener?) = Unit + override fun removeHandshakeCompletedListener(listener: HandshakeCompletedListener?) = Unit + override fun startHandshake() = Unit + override fun setUseClientMode(mode: Boolean) = Unit + override fun getUseClientMode(): Boolean = true + override fun setNeedClientAuth(need: Boolean) = Unit + override fun getNeedClientAuth(): Boolean = false + override fun setWantClientAuth(want: Boolean) = Unit + override fun getWantClientAuth(): Boolean = false + override fun setEnableSessionCreation(flag: Boolean) = Unit + override fun getEnableSessionCreation(): Boolean = true + } + + private fun fakeSslEngine(handshakeSession: SSLSession?): SSLEngine = + object : SSLEngine() { + override fun getHandshakeSession(): SSLSession? = handshakeSession + override fun wrap(srcs: Array?, offset: Int, length: Int, dst: ByteBuffer?): SSLEngineResult = + throw UnsupportedOperationException() + override fun unwrap(src: ByteBuffer?, dsts: Array?, offset: Int, length: Int): SSLEngineResult = + throw UnsupportedOperationException() + override fun getDelegatedTask(): Runnable? = null + override fun closeInbound() = Unit + override fun isInboundDone(): Boolean = false + override fun closeOutbound() = Unit + override fun isOutboundDone(): Boolean = false + override fun getSupportedCipherSuites(): Array = emptyArray() + override fun getEnabledCipherSuites(): Array = emptyArray() + override fun setEnabledCipherSuites(suites: Array?) = Unit + override fun getSupportedProtocols(): Array = emptyArray() + override fun getEnabledProtocols(): Array = emptyArray() + override fun setEnabledProtocols(protocols: Array?) = Unit + override fun getSession(): SSLSession? = handshakeSession + override fun beginHandshake() = Unit + override fun getHandshakeStatus(): SSLEngineResult.HandshakeStatus = SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING + override fun setUseClientMode(mode: Boolean) = Unit + override fun getUseClientMode(): Boolean = true + override fun setNeedClientAuth(need: Boolean) = Unit + override fun getNeedClientAuth(): Boolean = false + override fun setWantClientAuth(want: Boolean) = Unit + override fun getWantClientAuth(): Boolean = false + override fun setEnableSessionCreation(flag: Boolean) = Unit + override fun getEnableSessionCreation(): Boolean = true + } + + @Test + fun goodStaple_isAcceptedViaSocketAndEngine() { + val good = loadResource("good.der") + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + val session = fakeExtendedSession(listOf(good)) + + // Full chain [leaf, ca] via socket + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(session)) + // Leaf-only chain [leaf] (root resolved from acceptedIssuers) via engine + tm.checkServerTrusted(arrayOf(leafCert), "ECDHE_ECDSA", fakeSslEngine(session)) + } + + @Test + fun goodStapleWithoutEmbeddedCerts_isAcceptedUsingIssuerKey() { + val goodNoCerts = loadResource("good-nocerts.der") + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + val session = fakeExtendedSession(listOf(goodNoCerts)) + + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(session)) + } + + @Test + fun missingStaple_isRejectedWithClearMessage() { + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + val emptySession = fakeExtendedSession(emptyList()) + + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(emptySession)) + fail("Expected CertificateException when no OCSP staple is present") + } catch (e: CertificateException) { + assertEquals( + "Revocation status unavailable: server did not staple an OCSP response (OCSP stapling is required)", + e.message + ) + } + } + + @Test + fun revokedStaple_isRejectedWithRevokedReason() { + val revoked = loadResource("revoked.der") + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + val session = fakeExtendedSession(listOf(revoked)) + + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(session)) + fail("Expected CertificateException for revoked OCSP staple") + } catch (e: CertificateException) { + val cause = e.cause + assertTrue("Expected CertPathValidatorException cause, got $cause", cause is CertPathValidatorException) + assertEquals( + CertPathValidatorException.BasicReason.REVOKED, + (cause as CertPathValidatorException).reason + ) + } + } + + @Test + fun badSignerStaple_isRejectedWithCertPathValidatorExceptionCause() { + val badSigner = loadResource("badsigner.der") + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + val session = fakeExtendedSession(listOf(badSigner)) + + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(session)) + fail("Expected CertificateException for unauthorized OCSP signer") + } catch (e: CertificateException) { + assertTrue( + "Expected CertPathValidatorException cause, got ${e.cause}", + e.cause is CertPathValidatorException + ) + } + } + + @Test + fun corruptStaple_isRejectedWithCertPathValidatorExceptionCause() { + val corrupt = loadResource("corrupt.der") + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + val session = fakeExtendedSession(listOf(corrupt)) + + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(session)) + fail("Expected CertificateException for corrupt OCSP staple") + } catch (e: CertificateException) { + assertTrue( + "Expected CertPathValidatorException cause, got ${e.cause}", + e.cause is CertPathValidatorException + ) + } + } + + @Test + fun sha256SignedStaple_isRejectedByFiaX509AlgorithmConstraints() { + val sha256 = loadResource("good-sha256.der") + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + val session = fakeExtendedSession(listOf(sha256)) + + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(session)) + fail("Expected CertificateException for SHA-256 signed OCSP staple") + } catch (e: CertificateException) { + val cause = e.cause + assertTrue("Expected CertPathValidatorException cause, got $cause", cause is CertPathValidatorException) + assertEquals( + CertPathValidatorException.BasicReason.ALGORITHM_CONSTRAINED, + (cause as CertPathValidatorException).reason + ) + assertTrue( + "Expected OID 1.2.840.10045.4.3.2 in message: ${cause.message}", + cause.message!!.contains("1.2.840.10045.4.3.2") + ) + } + } + + class FakeNonExtendedSession(private val responses: List) : SSLSession { + @Suppress("unused") + fun getStatusResponses(): List = responses + override fun getId(): ByteArray = ByteArray(0) + override fun getSessionContext(): SSLSessionContext? = null + override fun getCreationTime(): Long = 0L + override fun getLastAccessedTime(): Long = 0L + override fun invalidate() = Unit + override fun isValid(): Boolean = true + override fun putValue(name: String?, value: Any?) = Unit + override fun getValue(name: String?): Any? = null + override fun removeValue(name: String?) = Unit + override fun getValueNames(): Array = emptyArray() + override fun getPeerCertificates(): Array = emptyArray() + override fun getLocalCertificates(): Array? = null + @Deprecated("Deprecated in Java") + override fun getPeerCertificateChain(): Array = emptyArray() + override fun getPeerPrincipal(): Principal? = null + override fun getLocalPrincipal(): Principal? = null + override fun getCipherSuite(): String = "TLS_AES_256_GCM_SHA384" + override fun getProtocol(): String = "TLSv1.3" + override fun getPeerHost(): String = "localhost" + override fun getPeerPort(): Int = 443 + override fun getPacketBufferSize(): Int = 16384 + override fun getApplicationBufferSize(): Int = 16384 + } + + class ThrowingExtendedSession(private val error: Throwable) : ExtendedSSLSession() { + override fun getLocalSupportedSignatureAlgorithms(): Array = emptyArray() + override fun getPeerSupportedSignatureAlgorithms(): Array = emptyArray() + fun getStatusResponses(): List = throw error + override fun getId(): ByteArray = ByteArray(0) + override fun getSessionContext(): SSLSessionContext? = null + override fun getCreationTime(): Long = 0L + override fun getLastAccessedTime(): Long = 0L + override fun invalidate() = Unit + override fun isValid(): Boolean = true + override fun putValue(name: String?, value: Any?) = Unit + override fun getValue(name: String?): Any? = null + override fun removeValue(name: String?) = Unit + override fun getValueNames(): Array = emptyArray() + override fun getPeerCertificates(): Array = emptyArray() + override fun getLocalCertificates(): Array? = null + @Deprecated("Deprecated in Java") + override fun getPeerCertificateChain(): Array = emptyArray() + override fun getPeerPrincipal(): Principal? = null + override fun getLocalPrincipal(): Principal? = null + override fun getCipherSuite(): String = "TLS_AES_256_GCM_SHA384" + override fun getProtocol(): String = "TLSv1.3" + override fun getPeerHost(): String = "localhost" + override fun getPeerPort(): Int = 443 + override fun getPacketBufferSize(): Int = 16384 + override fun getApplicationBufferSize(): Int = 16384 + } + + @Test + fun nonExtendedSessionWithConcreteMethod_isNotReflectedAndFailsWithApiUnavailable() { + val good = loadResource("good.der") + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + val concreteOnlySession = FakeNonExtendedSession(listOf(good)) + + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(concreteOnlySession)) + fail("Expected CertificateException when session is not an ExtendedSSLSession") + } catch (e: CertificateException) { + assertTrue( + "Expected platform API unavailable message, got: ${e.message}", + e.message!!.contains("platform API unavailable") + ) + assertTrue( + "Must not report misleading 'server did not staple' message: ${e.message}", + !e.message!!.contains("server did not staple") + ) + } + } + + @Test + fun extendedSessionThrowingError_failsWithApiUnavailableAndPreservesCause() { + val rootCause = UnsupportedOperationException("statusResponses not supported") + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + val session = ThrowingExtendedSession(rootCause) + + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(session)) + fail("Expected CertificateException when getStatusResponses() throws") + } catch (e: CertificateException) { + assertTrue( + "Expected platform API unavailable message, got: ${e.message}", + e.message!!.contains("platform API unavailable") + ) + assertEquals(rootCause, e.cause) + } + } + + @Test + fun nullHandshakeSession_failsWithApiUnavailable() { + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslSocket(null)) + fail("Expected CertificateException when handshakeSession is null") + } catch (e: CertificateException) { + assertTrue( + "Expected platform API unavailable message, got: ${e.message}", + e.message!!.contains("platform API unavailable") + ) + } + } + + @After + fun resetPolicyState() { + NiapTlsPolicy.resetCapabilityStateForTesting() + } + + private fun fakeTls12Session(): SSLSession = object : SSLSession { + override fun getId(): ByteArray = ByteArray(0) + override fun getSessionContext(): SSLSessionContext? = null + override fun getCreationTime(): Long = 0L + override fun getLastAccessedTime(): Long = 0L + override fun invalidate() = Unit + override fun isValid(): Boolean = true + override fun putValue(name: String?, value: Any?) = Unit + override fun getValue(name: String?): Any? = null + override fun removeValue(name: String?) = Unit + override fun getValueNames(): Array = emptyArray() + override fun getPeerCertificates(): Array = emptyArray() + override fun getLocalCertificates(): Array? = null + @Deprecated("Deprecated in Java") + override fun getPeerCertificateChain(): Array = emptyArray() + override fun getPeerPrincipal(): Principal? = null + override fun getLocalPrincipal(): Principal? = null + override fun getCipherSuite(): String = "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" + override fun getProtocol(): String = "TLSv1.2" + override fun getPeerHost(): String = "localhost" + override fun getPeerPort(): Int = 443 + override fun getPacketBufferSize(): Int = 16384 + override fun getApplicationBufferSize(): Int = 16384 + } + + @Test + fun withoutPublicApi_usesWireCapturedGoodAndRevokedStaples() { + NiapTlsPolicy.overridePublicStapleApiAvailable = false + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + + val goodSocket = fakeSslSocket(fakeTls12Session()) + WireOcspRegistry.register(goodSocket, WireOcspCapture().apply { ocspResponse = loadResource("good.der") }) + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", goodSocket) + + val revokedSocket = fakeSslSocket(fakeTls12Session()) + WireOcspRegistry.register(revokedSocket, WireOcspCapture().apply { ocspResponse = loadResource("revoked.der") }) + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", revokedSocket) + fail("Expected CertificateException for wire-captured revoked staple") + } catch (e: CertificateException) { + val cause = e.cause + assertTrue("Expected CertPathValidatorException cause, got $cause", cause is CertPathValidatorException) + assertEquals(CertPathValidatorException.BasicReason.REVOKED, (cause as CertPathValidatorException).reason) + } + } + + @Test + fun withoutPublicApi_missingWireStapleReportsServerDidNotStaple() { + NiapTlsPolicy.overridePublicStapleApiAvailable = false + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + + val socket = fakeSslSocket(fakeTls12Session()) + WireOcspRegistry.register(socket, WireOcspCapture()) // no CertificateStatus received + + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", socket) + fail("Expected CertificateException when wire capture has no staple") + } catch (e: CertificateException) { + assertEquals( + "Revocation status unavailable: server did not staple an OCSP response (OCSP stapling is required)", + e.message + ) + } + } + + @Test + fun withoutPublicApi_sslEngineAndTls13FailWithInaccessibleMessage() { + NiapTlsPolicy.overridePublicStapleApiAvailable = false + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + + // SSLEngine handshake + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", fakeSslEngine(fakeTls12Session())) + fail("Expected CertificateException for SSLEngine without public API") + } catch (e: CertificateException) { + assertTrue( + "Expected inaccessible message, got: ${e.message}", + e.message!!.contains("not accessible on this platform version") && e.message!!.contains("SSLEngine") + ) + } + + // TLS 1.3 negotiated on SSLSocket without public API + val tls13Socket = fakeSslSocket(fakeExtendedSession(emptyList())) + WireOcspRegistry.register(tls13Socket, WireOcspCapture().apply { negotiatedTls13 = true }) + try { + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", tls13Socket) + fail("Expected CertificateException for TLS 1.3 without public API") + } catch (e: CertificateException) { + assertTrue( + "Expected inaccessible TLSv1.3 message, got: ${e.message}", + e.message!!.contains("not accessible on this platform version") && e.message!!.contains("TLSv1.3") + ) + } + } + + @Test + fun forcedTls12WireCapture_overridesPublicApiAndUsesWireCapture() { + // On JVM, public ExtendedSSLSession.getStatusResponses() is available, but enabling the + // test hook must ignore the session's getStatusResponses() and read from WireOcspRegistry. + NiapTlsPolicy.setForceTls12WireCaptureForTesting(isDebuggable = true, enabled = true) + val tm = NiapX509TrustManager(fakeTrustManager(), NiapCertValidator()) + + // Session has empty statusResponses, while WireOcspRegistry has a valid good staple -> MUST PASS! + val sessionWithNoApiStaple = fakeExtendedSession(emptyList()).let { + fakeTls12Session() + } + val socket = fakeSslSocket(sessionWithNoApiStaple) + WireOcspRegistry.register(socket, WireOcspCapture().apply { ocspResponse = loadResource("good.der") }) + + tm.checkServerTrusted(arrayOf(leafCert, caCert), "ECDHE_ECDSA", socket) + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/VerifiableSSLSocketFactoryTest.kt b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/VerifiableSSLSocketFactoryTest.kt new file mode 100644 index 0000000..78db7ab --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/test/kotlin/com/android/niap/cert/validator/VerifiableSSLSocketFactoryTest.kt @@ -0,0 +1,602 @@ +/* + * Copyright 2026 Google LLC + * + * 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. + */ + +package com.android.niap.cert.validator + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.InputStream +import javax.net.ssl.SSLHandshakeException + +class VerifiableSSLSocketFactoryTest { + + private fun buildServerHelloBody( + legacyVersion: Int = 0x0303, + random: ByteArray = ByteArray(32) { (it + 1).toByte() }, + sessionId: ByteArray = ByteArray(32) { 0xAA.toByte() }, + cipherSuite: Int = 0xC02C, + extensions: List>? = emptyList() + ): ByteArray { + val out = ByteArrayOutputStream() + out.write((legacyVersion ushr 8) and 0xFF) + out.write(legacyVersion and 0xFF) + out.write(random) + out.write(sessionId.size) + out.write(sessionId) + out.write((cipherSuite ushr 8) and 0xFF) + out.write(cipherSuite and 0xFF) + out.write(0x00) + + if (extensions != null) { + val extBuf = ByteArrayOutputStream() + for ((extType, extData) in extensions) { + extBuf.write((extType ushr 8) and 0xFF) + extBuf.write(extType and 0xFF) + extBuf.write((extData.size ushr 8) and 0xFF) + extBuf.write(extData.size and 0xFF) + extBuf.write(extData) + } + val extBytes = extBuf.toByteArray() + out.write((extBytes.size ushr 8) and 0xFF) + out.write(extBytes.size and 0xFF) + out.write(extBytes) + } + return out.toByteArray() + } + + private fun wrapHandshake(hsType: Int, body: ByteArray): ByteArray = + ByteArrayOutputStream().apply { + write(hsType and 0xFF) + write((body.size ushr 16) and 0xFF) + write((body.size ushr 8) and 0xFF) + write(body.size and 0xFF) + write(body) + }.toByteArray() + + private fun wrapRecord(contentType: Int, payload: ByteArray): ByteArray = + ByteArrayOutputStream().apply { + write(contentType and 0xFF) + write(0x03); write(0x03) + write((payload.size ushr 8) and 0xFF) + write(payload.size and 0xFF) + write(payload) + }.toByteArray() + + @Test + fun tls12WithEms_isAcceptedAndReplayedIntact() { + val sh = buildServerHelloBody( + extensions = listOf(0xFF01 to byteArrayOf(0x00), 0x0017 to ByteArray(0)) + ) + val wire = wrapRecord(0x16, wrapHandshake(0x02, sh)) + + byteArrayOf(0x17, 0x03, 0x03, 0x00, 0x02, 0x11, 0x22) + + var rejected = false + val readBack = EmsVerifyingInputStream(ByteArrayInputStream(wire)) { rejected = true }.readBytes() + + assertFalse(rejected) + assertArrayEquals(wire, readBack) + } + + @Test + fun tls12OmittingEms_isRejectedWithSSLHandshakeException() { + val sh = buildServerHelloBody( + extensions = listOf(0xFF01 to byteArrayOf(0x00), 0x000B to byteArrayOf(0x01, 0x00)) + ) + val wire = wrapRecord(0x16, wrapHandshake(0x02, sh)) + + var rejectedCount = 0 + val stream = EmsVerifyingInputStream(ByteArrayInputStream(wire)) { rejectedCount++ } + + try { + stream.read(ByteArray(256)) + fail("Expected SSLHandshakeException when TLS 1.2 ServerHello omits EMS") + } catch (e: SSLHandshakeException) { + assertTrue(e.message!!.contains("extended_master_secret")) + } + assertEquals(1, rejectedCount) + } + + @Test + fun tls12WithNoExtensionsBlock_isRejected() { + val wire = wrapRecord(0x16, wrapHandshake(0x02, buildServerHelloBody(extensions = null))) + assertTrue(ServerHelloValidator.inspect(wire) is ServerHelloValidator.Result.Reject) + } + + @Test + fun tls12WithNonEmptyEms_isRejected() { + val sh = buildServerHelloBody(extensions = listOf(0x0017 to byteArrayOf(0x01))) + val wire = wrapRecord(0x16, wrapHandshake(0x02, sh)) + assertTrue(ServerHelloValidator.inspect(wire) is ServerHelloValidator.Result.Reject) + } + + @Test + fun tls13WithoutEms_isAccepted() { + val sh = buildServerHelloBody( + cipherSuite = 0x1302, + extensions = listOf(0x002B to byteArrayOf(0x03, 0x04)) + ) + val wire = wrapRecord(0x16, wrapHandshake(0x02, sh)) + assertEquals(ServerHelloValidator.Result.PassThrough(isTls13 = true), ServerHelloValidator.inspect(wire)) + } + + @Test + fun fragmentedRecords_reassemblesAndEnforcesEms() { + val hs = wrapHandshake(0x02, buildServerHelloBody(extensions = listOf(0x0017 to ByteArray(0)))) + val fullWire = wrapRecord(0x16, hs.copyOfRange(0, 20)) + wrapRecord(0x16, hs.copyOfRange(20, hs.size)) + + val drip = object : InputStream() { + var pos = 0 + override fun read(): Int = if (pos < fullWire.size) fullWire[pos++].toInt() and 0xFF else -1 + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (pos >= fullWire.size) return -1 + val n = minOf(3, len, fullWire.size - pos) + System.arraycopy(fullWire, pos, b, off, n) + pos += n + return n + } + } + + val out = EmsVerifyingInputStream(drip) { fail("Unexpected rejection") }.readBytes() + assertArrayEquals(fullWire, out) + } + + private val defaultAllowedCodePoints = NiapTlsPolicy.codePointsForNames(NiapTlsPolicy.DEFAULT_SUITE_NAMES) + + private val hrrRandom = byteArrayOf( + 0xCF.toByte(), 0x21, 0xAD.toByte(), 0x74, 0xE5.toByte(), 0x9A.toByte(), 0x61, 0x11, + 0xBE.toByte(), 0x1D, 0x8C.toByte(), 0x02, 0x1E, 0x65, 0xB8.toByte(), 0x91.toByte(), + 0xC2.toByte(), 0xA2.toByte(), 0x11, 0x16, 0x7A, 0xBB.toByte(), 0x8C.toByte(), 0x5E, + 0x07, 0x9E.toByte(), 0x09, 0xE2.toByte(), 0xC8.toByte(), 0xA8.toByte(), 0x33, 0x9C.toByte() + ) + + @Test + fun tls13ChaCha20_isRejectedWithSuiteNameAndFatalAlert() { + val sh = buildServerHelloBody( + cipherSuite = 0x1303, + extensions = listOf(0x002B to byteArrayOf(0x03, 0x04)) + ) + val wire = wrapRecord(0x16, wrapHandshake(0x02, sh)) + + var rejectedCount = 0 + val stream = EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(wire), + onReject = { rejectedCount++ }, + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints + ) + + try { + stream.read(ByteArray(256)) + fail("Expected SSLHandshakeException for TLS 1.3 ChaCha20 (0x1303)") + } catch (e: SSLHandshakeException) { + assertTrue( + "Unexpected message: ${e.message}", + e.message!!.contains("0x1303 (TLS_CHACHA20_POLY1305_SHA256)") + ) + assertTrue(e.message!!.contains("NIAP allowlist")) + } + assertEquals(1, rejectedCount) + } + + @Test + fun tls12ChaCha20_isRejectedEvenWithEms() { + val sh = buildServerHelloBody( + cipherSuite = 0xCCA9, + extensions = listOf(0x0017 to ByteArray(0)) + ) + val wire = wrapRecord(0x16, wrapHandshake(0x02, sh)) + + val res = ServerHelloValidator.inspect( + wire = wire, + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints + ) + assertTrue(res is ServerHelloValidator.Result.Reject) + val reason = (res as ServerHelloValidator.Result.Reject).reason + assertTrue( + "Unexpected reason: $reason", + reason.contains("0xCCA9 (TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256)") + ) + } + + @Test + fun tls13Aes128Gcm_andTls12Aes256Gcm_areAccepted() { + val tls13Wire = wrapRecord( + 0x16, + wrapHandshake( + 0x02, + buildServerHelloBody( + cipherSuite = 0x1301, + extensions = listOf(0x002B to byteArrayOf(0x03, 0x04)) + ) + ) + ) + assertEquals( + ServerHelloValidator.Result.PassThrough(isTls13 = true), + ServerHelloValidator.inspect( + wire = tls13Wire, + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints + ) + ) + + val tls12Wire = wrapRecord( + 0x16, + wrapHandshake( + 0x02, + buildServerHelloBody( + cipherSuite = 0xC02C, + extensions = listOf(0x0017 to ByteArray(0)) + ) + ) + ) + assertEquals( + ServerHelloValidator.Result.PassThrough(isTls13 = false), + ServerHelloValidator.inspect( + wire = tls12Wire, + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints + ) + ) + } + + @Test + fun hrrWithDisallowedCipherSuite_isRejectedImmediately() { + val hrr = buildServerHelloBody( + random = hrrRandom, + cipherSuite = 0x1303, + extensions = listOf(0x002B to byteArrayOf(0x03, 0x04)) + ) + val wire = wrapRecord(0x16, wrapHandshake(0x02, hrr)) + + val res = ServerHelloValidator.inspect( + wire = wire, + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints + ) + assertTrue(res is ServerHelloValidator.Result.Reject) + assertTrue((res as ServerHelloValidator.Result.Reject).reason.contains("0x1303")) + } + + @Test + fun hrrWithAllowedCipherSuite_followedByCcsAndAllowedServerHello_isAccepted() { + val hrrWire = wrapRecord( + 0x16, + wrapHandshake( + 0x02, + buildServerHelloBody( + random = hrrRandom, + cipherSuite = 0x1301, + extensions = listOf(0x002B to byteArrayOf(0x03, 0x04)) + ) + ) + ) + val ccsWire = wrapRecord(0x14, byteArrayOf(0x01)) + val shWire = wrapRecord( + 0x16, + wrapHandshake( + 0x02, + buildServerHelloBody( + cipherSuite = 0x1301, + extensions = listOf(0x002B to byteArrayOf(0x03, 0x04)) + ) + ) + ) + val fullWire = hrrWire + ccsWire + shWire + + val readBack = EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(fullWire), + onReject = { fail("Unexpected rejection") }, + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints + ).readBytes() + + assertArrayEquals(fullWire, readBack) + } + + @Test + fun hrrWithAllowedCipherSuite_followedByDisallowedServerHello_isRejected() { + val hrrWire = wrapRecord( + 0x16, + wrapHandshake( + 0x02, + buildServerHelloBody( + random = hrrRandom, + cipherSuite = 0x1301, + extensions = listOf(0x002B to byteArrayOf(0x03, 0x04)) + ) + ) + ) + val ccsWire = wrapRecord(0x14, byteArrayOf(0x01)) + val badShWire = wrapRecord( + 0x16, + wrapHandshake( + 0x02, + buildServerHelloBody( + cipherSuite = 0x1303, + extensions = listOf(0x002B to byteArrayOf(0x03, 0x04)) + ) + ) + ) + val fullWire = hrrWire + ccsWire + badShWire + + var rejectedCount = 0 + val stream = EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(fullWire), + onReject = { rejectedCount++ }, + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints + ) + + try { + stream.readBytes() + fail("Expected SSLHandshakeException when post-HRR ServerHello selects 0x1303") + } catch (e: SSLHandshakeException) { + assertTrue(e.message!!.contains("0x1303")) + } + assertEquals(1, rejectedCount) + } + + @Test + fun xmlCipherSuiteResolution_emptyReturnsBuiltinAndNarrowingWorks() { + assertEquals(NiapTlsPolicy.APPROVED_SUITES, NiapTlsPolicy.resolveAllowedCipherSuites(null)) + assertEquals(NiapTlsPolicy.APPROVED_SUITES, NiapTlsPolicy.resolveAllowedCipherSuites(emptyList())) + + val narrowed = NiapTlsPolicy.resolveAllowedCipherSuites( + listOf("TLS_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384") + ) + assertEquals(2, narrowed.size) + assertEquals(listOf(0x1302, 0xC02C), narrowed.map { it.codePoint }) + } + + @Test + fun xmlCipherSuiteResolution_rejectsNonApprovedOrUnknownSuites() { + try { + NiapTlsPolicy.resolveAllowedCipherSuites(listOf("TLS_CHACHA20_POLY1305_SHA256")) + fail("Expected IllegalArgumentException for non-approved suite") + } catch (e: IllegalArgumentException) { + assertTrue(e.message!!.contains("TLS_CHACHA20_POLY1305_SHA256")) + } + + try { + NiapTlsPolicy.resolveAllowedCipherSuites(listOf("TLS_NON_EXISTENT_SUITE")) + fail("Expected IllegalArgumentException for unknown suite") + } catch (e: IllegalArgumentException) { + assertTrue(e.message!!.contains("TLS_NON_EXISTENT_SUITE")) + } + } + + private fun buildCertificateStatusBody( + ocspDer: ByteArray, + statusType: Int = 0x01, + declaredLength: Int = ocspDer.size + ): ByteArray = ByteArrayOutputStream().apply { + write(statusType and 0xFF) + write((declaredLength ushr 16) and 0xFF) + write((declaredLength ushr 8) and 0xFF) + write(declaredLength and 0xFF) + write(ocspDer) + }.toByteArray() + + @Test + fun wireCapture_tls12SeparateRecords_capturesOcspAndReplaysIntact() { + val fakeOcsp = byteArrayOf(0x30, 0x09, 0x0A, 0x01, 0x00, 0xA0.toByte(), 0x04, 0x01, 0x02, 0x03, 0x04) + val sh = wrapRecord(0x16, wrapHandshake(0x02, buildServerHelloBody(extensions = listOf(0x0017 to ByteArray(0))))) + val cert = wrapRecord(0x16, wrapHandshake(0x0B, ByteArray(128) { 0x42 })) + val status = wrapRecord(0x16, wrapHandshake(0x16, buildCertificateStatusBody(fakeOcsp))) + val done = wrapRecord(0x16, wrapHandshake(0x0E, ByteArray(0))) + val appData = wrapRecord(0x17, byteArrayOf(0x55, 0x66, 0x77)) + val fullWire = sh + cert + status + done + appData + + val capture = WireOcspCapture() + val readBack = EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(fullWire), + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints, + ocspCapture = capture + ) { fail("Unexpected rejection") }.readBytes() + + assertArrayEquals(fullWire, readBack) + assertFalse(capture.negotiatedTls13) + assertArrayEquals(fakeOcsp, capture.ocspResponse) + } + + @Test + fun wireCapture_tls12MultipleMessagesInSingleRecord_capturesOcspAndReplaysIntact() { + val fakeOcsp = ByteArray(64) { (it * 3 + 7).toByte() } + val combinedHandshake = + wrapHandshake(0x02, buildServerHelloBody(extensions = listOf(0x0017 to ByteArray(0)))) + + wrapHandshake(0x0B, ByteArray(40) { 0x11 }) + + wrapHandshake(0x16, buildCertificateStatusBody(fakeOcsp)) + + wrapHandshake(0x0C, ByteArray(32) { 0x22 }) + + wrapHandshake(0x0E, ByteArray(0)) + val fullWire = wrapRecord(0x16, combinedHandshake) + + val capture = WireOcspCapture() + val readBack = EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(fullWire), + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints, + ocspCapture = capture + ) { fail("Unexpected rejection") }.readBytes() + + assertArrayEquals(fullWire, readBack) + assertArrayEquals(fakeOcsp, capture.ocspResponse) + } + + @Test + fun wireCapture_tls12FragmentedAcrossRecordsAndSmallReads_capturesOcsp() { + val fakeOcsp = ByteArray(90) { (it + 0x10).toByte() } + val sh = wrapRecord(0x16, wrapHandshake(0x02, buildServerHelloBody(extensions = listOf(0x0017 to ByteArray(0))))) + val statusMsg = wrapHandshake(0x16, buildCertificateStatusBody(fakeOcsp)) + val statusFrag1 = wrapRecord(0x16, statusMsg.copyOfRange(0, 17)) + val statusFrag2 = wrapRecord(0x16, statusMsg.copyOfRange(17, 51)) + val statusFrag3 = wrapRecord(0x16, statusMsg.copyOfRange(51, statusMsg.size)) + val done = wrapRecord(0x16, wrapHandshake(0x0E, ByteArray(0))) + val fullWire = sh + statusFrag1 + statusFrag2 + statusFrag3 + done + + val drip = object : InputStream() { + var pos = 0 + override fun read(): Int = if (pos < fullWire.size) fullWire[pos++].toInt() and 0xFF else -1 + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (pos >= fullWire.size) return -1 + val n = minOf(3, len, fullWire.size - pos) + System.arraycopy(fullWire, pos, b, off, n) + pos += n + return n + } + } + + val capture = WireOcspCapture() + val readBack = EmsVerifyingInputStream( + delegateIn = drip, + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints, + ocspCapture = capture + ) { fail("Unexpected rejection") }.readBytes() + + assertArrayEquals(fullWire, readBack) + assertArrayEquals(fakeOcsp, capture.ocspResponse) + } + + @Test + fun wireCapture_nonOcspStatusType_isRejected() { + val sh = wrapRecord(0x16, wrapHandshake(0x02, buildServerHelloBody(extensions = listOf(0x0017 to ByteArray(0))))) + val badStatus = wrapRecord(0x16, wrapHandshake(0x16, buildCertificateStatusBody(byteArrayOf(1, 2, 3), statusType = 2))) + val fullWire = sh + badStatus + + var rejectedCount = 0 + val stream = EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(fullWire), + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints, + ocspCapture = WireOcspCapture() + ) { rejectedCount++ } + + try { + stream.readBytes() + fail("Expected SSLHandshakeException for non-OCSP status_type") + } catch (e: SSLHandshakeException) { + assertTrue("Unexpected message: ${e.message}", e.message!!.contains("status_type")) + } + assertEquals(1, rejectedCount) + } + + @Test + fun wireCapture_malformedAndTruncatedCertificateStatus_isRejected() { + val sh = wrapRecord(0x16, wrapHandshake(0x02, buildServerHelloBody(extensions = listOf(0x0017 to ByteArray(0))))) + + // Length mismatch inside CertificateStatus body + val mismatchStatus = wrapRecord( + 0x16, + wrapHandshake(0x16, buildCertificateStatusBody(byteArrayOf(1, 2, 3, 4), declaredLength = 10)) + ) + var rejected1 = 0 + try { + EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(sh + mismatchStatus), + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints, + ocspCapture = WireOcspCapture() + ) { rejected1++ }.readBytes() + fail("Expected SSLHandshakeException for length mismatch") + } catch (e: SSLHandshakeException) { + assertTrue("Unexpected message: ${e.message}", e.message!!.contains("CertificateStatus")) + } + assertEquals(1, rejected1) + + // Truncated EOF mid-CertificateStatus + val statusMsg = wrapHandshake(0x16, buildCertificateStatusBody(ByteArray(40) { 0x33 })) + val truncatedRecord = wrapRecord(0x16, statusMsg.copyOfRange(0, 20)) + var rejected2 = 0 + try { + EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(sh + truncatedRecord), + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints, + ocspCapture = WireOcspCapture() + ) { rejected2++ }.readBytes() + fail("Expected SSLHandshakeException for truncated CertificateStatus") + } catch (e: SSLHandshakeException) { + assertTrue("Unexpected message: ${e.message}", e.message!!.contains("CertificateStatus")) + } + assertEquals(1, rejected2) + } + + @Test + fun wireCapture_resumedTls12CcsAndTls13_stopTappingCleanly() { + // Resumed TLS 1.2: ServerHello followed by ChangeCipherSpec + encrypted Finished + val sh12 = wrapRecord(0x16, wrapHandshake(0x02, buildServerHelloBody(extensions = listOf(0x0017 to ByteArray(0))))) + val ccs = wrapRecord(0x14, byteArrayOf(0x01)) + val encFin = wrapRecord(0x16, ByteArray(48) { 0x7E }) // encrypted bytes, not plaintext handshake + val resumedWire = sh12 + ccs + encFin + + val capture12 = WireOcspCapture() + val read12 = EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(resumedWire), + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints, + ocspCapture = capture12 + ) { fail("Unexpected rejection on resumed TLS 1.2") }.readBytes() + assertArrayEquals(resumedWire, read12) + assertFalse(capture12.negotiatedTls13) + assertEquals(null, capture12.ocspResponse) + + // TLS 1.3: ServerHello followed by encrypted ApplicationData + val sh13 = wrapRecord( + 0x16, + wrapHandshake( + 0x02, + buildServerHelloBody( + cipherSuite = 0x1301, + extensions = listOf(0x002B to byteArrayOf(0x03, 0x04)) + ) + ) + ) + val app13 = wrapRecord(0x17, ByteArray(64) { 0x5A }) + val tls13Wire = sh13 + app13 + + val capture13 = WireOcspCapture() + val read13 = EmsVerifyingInputStream( + delegateIn = ByteArrayInputStream(tls13Wire), + requireEms = true, + allowedCipherSuites = defaultAllowedCodePoints, + ocspCapture = capture13 + ) { fail("Unexpected rejection on TLS 1.3") }.readBytes() + assertArrayEquals(tls13Wire, read13) + assertTrue(capture13.negotiatedTls13) + assertEquals(null, capture13.ocspResponse) + } + + @Test + fun wireOcspRegistry_correlatesRegisteredSocket() { + val sslSocket = javax.net.ssl.SSLContext.getDefault().socketFactory.createSocket() as javax.net.ssl.SSLSocket + val capture = WireOcspCapture().apply { ocspResponse = byteArrayOf(0x30, 0x03, 0x0A, 0x01, 0x00) } + WireOcspRegistry.register(sslSocket, capture) + + val lookedUp = WireOcspRegistry.lookup(sslSocket) + assertEquals(capture, lookedUp) + assertArrayEquals(capture.ocspResponse, lookedUp?.ocspResponse) + assertEquals(null, WireOcspRegistry.lookup(null)) + sslSocket.close() + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/badsigner.der b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/badsigner.der new file mode 100644 index 0000000..8fab4c3 Binary files /dev/null and b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/badsigner.der differ diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/ca.crt b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/ca.crt new file mode 100644 index 0000000..0a0dde3 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/ca.crt @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIBuDCCAT+gAwIBAgIUNyDnO/VH7KRKZedTsOQif9YHQAQwCgYIKoZIzj0EAwMw +HDEaMBgGA1UEAwwRTklBUCBUZXN0IFJvb3QgQ0EwHhcNMjYxMjAzMTgyODU3WhcN +MzYxMTMwMTgyODU3WjAcMRowGAYDVQQDDBFOSUFQIFRlc3QgUm9vdCBDQTB2MBAG +ByqGSM49AgEGBSuBBAAiA2IABC3/FASwXyLzC2A4Kri3XSh+6XBJC4IDobeztOyv +xQjlhJC1CxGOQ5+/p188tYZj6MgbM/whtRrs8s9r1AIHo0ujRpOj4R3LM+T7ZWxN +Plr08a+FOTIfBHwmYFtabnoDuqNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B +Af8EBAMCAQYwHQYDVR0OBBYEFAvW1EKNMHra7HpQagHLMJbdgtY7MAoGCCqGSM49 +BAMDA2cAMGQCMBR3wx5ONBkOhXvI9B4xpA1NeZaCFCW62OPphk60lw+bSGB3ELYO +xq/hm7N1Tkzj5AIwDFlBwMTElm3i/J5G+eZluvFS8fJFRSWGY7LgmJ1fs+QcTaIf +KZzdyjWwVzaoLTZj +-----END CERTIFICATE----- diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/corrupt.der b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/corrupt.der new file mode 100644 index 0000000..9701ec8 Binary files /dev/null and b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/corrupt.der differ diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/gen_ocsp_fixtures.sh b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/gen_ocsp_fixtures.sh new file mode 100755 index 0000000..0183224 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/gen_ocsp_fixtures.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# Generates long-validity (10-year) NIAP-profile-compliant PKI (EC P-384 / SHA-384) +# and stapled OCSP response fixtures for JVM unit tests in cert-lib. +set -euo pipefail + +O="${OPENSSL_BIN:-/opt/homebrew/bin/openssl}" +OUT_DIR="$(cd "$(dirname "$0")" && pwd)" +TMP_DIR="$(mktemp -d)" +trap 'rm -rf "$TMP_DIR"' EXIT + +cd "$TMP_DIR" + +# --- Root CA (EC P-384, ecdsa-with-SHA384) --- +"$O" ecparam -name secp384r1 -genkey -noout -out ca.key +"$O" req -x509 -new -key ca.key -sha384 -days 3650 -subj "/CN=NIAP Test Root CA" \ + -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" \ + -addext "subjectKeyIdentifier=hash" \ + -out ca.crt + +# --- Server leaf (EC P-384, ecdsa-with-SHA384, satisfies NiapCertValidator) --- +"$O" ecparam -name secp384r1 -genkey -noout -out server.key +"$O" req -new -key server.key -subj "/CN=localhost" -out server.csr +cat > server.ext < index-good.txt +printf "R\t391231235959Z\t%s\t%s\tunknown\t/CN=localhost\n" "$(date -u +%y%m%d%H%M%SZ)" "$SERIAL" > index-revoked.txt + +# --- OCSP responses (-ndays 3650 for long-lived unit test fixtures) --- +"$O" ocsp -issuer ca.crt -cert server.crt -no_nonce -reqout req.der + +# good: CA-signed with ecdsa-with-SHA384 +"$O" ocsp -reqin req.der -index index-good.txt -CA ca.crt -rsigner ca.crt -rkey ca.key -rmd sha384 -ndays 3650 -respout good.der + +# good-nocerts: CA-signed with ecdsa-with-SHA384, no embedded responder cert +"$O" ocsp -reqin req.der -index index-good.txt -CA ca.crt -rsigner ca.crt -rkey ca.key -rmd sha384 -ndays 3650 -resp_no_certs -respout good-nocerts.der + +# revoked: CA-signed with ecdsa-with-SHA384, status=revoked +"$O" ocsp -reqin req.der -index index-revoked.txt -CA ca.crt -rsigner ca.crt -rkey ca.key -rmd sha384 -ndays 3650 -respout revoked.der + +# badsigner: signed by an unauthorized rogue key +"$O" ocsp -reqin req.der -index index-good.txt -CA ca.crt -rsigner rogue.crt -rkey rogue.key -rmd sha384 -ndays 3650 -respout badsigner.der + +# good-sha256: CA-signed good response using ecdsa-with-SHA256 (outside FIA_X509_EXT.1.1) +"$O" ocsp -reqin req.der -index index-good.txt -CA ca.crt -rsigner ca.crt -rkey ca.key -rmd sha256 -ndays 3650 -respout good-sha256.der + +# corrupt: good-nocerts.der with a flipped signature byte +python3 - <<'EOF' +b = bytearray(open('good-nocerts.der', 'rb').read()) +b[-1] ^= 0x01 +open('corrupt.der', 'wb').write(bytes(b)) +EOF + +cp ca.crt server.crt good.der good-nocerts.der revoked.der badsigner.der good-sha256.der corrupt.der "$OUT_DIR/" +echo "Generated OCSP test fixtures in $OUT_DIR" diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/good-nocerts.der b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/good-nocerts.der new file mode 100644 index 0000000..c5e6dca Binary files /dev/null and b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/good-nocerts.der differ diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/good-sha256.der b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/good-sha256.der new file mode 100644 index 0000000..878154a Binary files /dev/null and b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/good-sha256.der differ diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/good.der b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/good.der new file mode 100644 index 0000000..432412e Binary files /dev/null and b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/good.der differ diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/revoked.der b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/revoked.der new file mode 100644 index 0000000..a208c64 Binary files /dev/null and b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/revoked.der differ diff --git a/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/server.crt b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/server.crt new file mode 100644 index 0000000..26c48ad --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-lib/src/test/resources/ocsp/server.crt @@ -0,0 +1,14 @@ +-----BEGIN CERTIFICATE----- +MIICNTCCAbugAwIBAgIUB6yDQBbLO2P7GNJFLtsnBw2vkrQwCgYIKoZIzj0EAwMw +HDEaMBgGA1UEAwwRTklBUCBUZXN0IFJvb3QgQ0EwHhcNMjYxMjAzMTgyODU3WhcN +MzYxMTMwMTgyODU3WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwdjAQBgcqhkjOPQIB +BgUrgQQAIgNiAAStm6dsJ7p1vAcXRbk2YvlJ7vBAOnCrbxWElE3WoiHs0fH4pmRr +1di/LmftsF4Yb6vc79qpLgj+T4ITgtWIUcyT5Zq3wdoP45jJh7YiHSKTmrdycTSw +uD+DN+0qmL9SeVyjgcUwgcIwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCB4Aw +EwYDVR0lBAwwCgYIKwYBBQUHAwEwHQYDVR0OBBYEFGyp61Ws6wfPfL+sY1y9X6fP +TlKbMB8GA1UdIwQYMBaAFAvW1EKNMHra7HpQagHLMJbdgtY7MBoGA1UdEQQTMBGC +CWxvY2FsaG9zdIcEfwAAATAxBggrBgEFBQcBAQQlMCMwIQYIKwYBBQUHMAGGFWh0 +dHA6Ly8xMjcuMC4wLjE6ODg4ODAKBggqhkjOPQQDAwNoADBlAjA5CL8oTieJhLmk +o9O2XDcMfHvbSHErUkmoNjOxPj+4J1HQdDFJwBu5/35cQubafZcCMQCrc1uzjDqx +1EaWNJZLGssq3aTACM/6Fae47uWBKwua8kTz6EtNcO2KQc9yvVFFPBg= +-----END CERTIFICATE----- diff --git a/niap-cc/niap-android-cert-ext/cert-manager/build.gradle.kts b/niap-cc/niap-android-cert-ext/cert-manager/build.gradle.kts new file mode 100644 index 0000000..f615981 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/build.gradle.kts @@ -0,0 +1,118 @@ +/* + * Copyright 2026 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. + */ + +import java.io.File + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") + id("org.jetbrains.kotlin.plugin.compose") version "2.2.0" +} + +android { + namespace = "com.example.niap.cert.ext.manager" + compileSdk = 34 + + defaultConfig { + applicationId = "com.example.niap.cert.ext.manager" + minSdk = 32 + targetSdk = 34 + versionCode = 1 + versionName = "1.0" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = "1.8" + } + buildFeatures { + compose = true + } + lint { + error += setOf( + "PrivateApi", + "DiscouragedPrivateApi", + "SoonBlockedPrivateApi", + "BlockedPrivateApi" + ) + abortOnError = true + } +} + +dependencies { + implementation("androidx.core:core-ktx:1.12.0") + implementation("androidx.appcompat:appcompat:1.6.1") + implementation("com.google.android.material:material:1.11.0") + + // Bouncy Castle for CSR generation + implementation("org.bouncycastle:bcpkix-jdk18on:1.77") + + // OkHttp for EST communication + implementation("com.squareup.okhttp3:okhttp:4.12.0") + + // NIAP Validator Core Library + implementation(project(":cert-lib")) + + // Jetpack Compose UI + val composeBom = platform("androidx.compose:compose-bom:2024.02.00") + implementation(composeBom) + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.material3:material3") + implementation("androidx.activity:activity-compose:1.8.2") + implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0") +} + +// --- Auto-Copy APK to TestBed Core Resources --- +val testbedRoot = gradle.extra["testbedRoot"] as File +val skipTestbedCopy = providers.gradleProperty("skipTestbedCopy") + .map { it.isEmpty() || it.equals("true", ignoreCase = true) } + .getOrElse(false) + +tasks.register("copyApkToCore") { + description = "Copies the generated APK to the TestBed Core resources directory." + enabled = !skipTestbedCopy + onlyIf { !skipTestbedCopy } + + // Source: The output of the assembleDebug task + from(layout.buildDirectory.dir("outputs/apk/debug")) + include("*-debug.apk") + + // Destination: /testbed-core/composeApp/resources/ + val coreResourcesDir = File(testbedRoot, "testbed-core/composeApp/resources") + into(coreResourcesDir) + + rename { "cert-manager-debug.apk" } + + doFirst { + coreResourcesDir.mkdirs() + } + doLast { + println("โœ… APK copied to: ${coreResourcesDir.absolutePath}") + } +} + +if (!skipTestbedCopy) { + tasks.configureEach { + if (name == "assemble" || name == "assembleDebug") { + finalizedBy("copyApkToCore") + } + } +} + + diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/AndroidManifest.xml b/niap-cc/niap-android-cert-ext/cert-manager/src/main/AndroidManifest.xml new file mode 100644 index 0000000..ebf2eae --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/AndroidManifest.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/ManagerActivity.kt b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/ManagerActivity.kt new file mode 100644 index 0000000..33f1df3 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/ManagerActivity.kt @@ -0,0 +1,135 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.service + +import android.content.Intent +import android.os.Bundle +import android.util.Log +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.android.niap.cert.manager.EnrollmentRequest +import com.android.niap.cert.manager.NiapCertManager +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import androidx.lifecycle.lifecycleScope + +class ManagerActivity : ComponentActivity() { + private lateinit var certManager: NiapCertManager + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + certManager = NiapCertManager(applicationContext) + handleIntent(intent) + setContent { + MaterialTheme { + Surface( + modifier = Modifier.fillMaxSize(), + color = MaterialTheme.colorScheme.background + ) { + ManagerAppScreen(certManager) + } + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + handleIntent(intent) + } + + private fun handleIntent(intent: Intent) { + when (intent.getStringExtra("action")) { + "verifyMtls" -> { + val alias = intent.getStringExtra("alias") ?: "test_client_cert" + val protectedUrl = intent.getStringExtra("protectedUrl") ?: "https://localhost:8443/protected/" + val caPemUrl = intent.getStringExtra("caPemUrl") ?: "http://localhost:8080/cacert.pem" + lifecycleScope.launch(Dispatchers.IO) { + val caPem = try { + java.net.URL(caPemUrl).readText() + } catch (e: Exception) { + Log.w("ManagerActivity", "Could not download CA PEM: ${e.message}") + "" + } + Log.d("ManagerActivity", "Auto-verifyMtls: alias=$alias url=$protectedUrl") + val result = certManager.verifyMtls(alias, protectedUrl, caPem) + Log.d("ManagerActivity", "MTLS_RESULT: $result") + } + } + "enroll" -> { + val alias = intent.getStringExtra("alias") ?: "test_client_cert" + val estUrl = intent.getStringExtra("estUrl") ?: "https://localhost:8443/.well-known/est/" + val authToken = intent.getStringExtra("authToken") ?: "estuser:estpwd" + val subjectDn = intent.getStringExtra("subjectDn") ?: "CN=TestUser" + + lifecycleScope.launch(Dispatchers.IO) { + val caPemUrl = intent.getStringExtra("caPemUrl") ?: "http://localhost:8080/cacert.pem" + val caPem = try { + java.net.URL(caPemUrl).readText().also { + Log.d("ManagerActivity", "Downloaded CA PEM from $caPemUrl (${it.length} bytes)") + } + } catch (e: Exception) { + Log.w("ManagerActivity", "Could not download CA PEM from $caPemUrl: ${e.message}") + "" + } + + Log.d("ManagerActivity", "Auto-enroll: alias=$alias url=$estUrl subject=$subjectDn") + val request = EnrollmentRequest(alias, estUrl, authToken, subjectDn, trustedCaPem = caPem) + try { + certManager.enroll(request).get(30, java.util.concurrent.TimeUnit.SECONDS) + Log.d("ManagerActivity", "Enrollment succeeded: READY") + } catch (e: java.util.concurrent.ExecutionException) { + Log.e("ManagerActivity", "Enrollment failed: ${e.cause?.message ?: e.message}") + } catch (e: Exception) { + Log.e("ManagerActivity", "Enrollment failed: ${e.message}") + } + } + } + } + } + + override fun onDestroy() { + super.onDestroy() + certManager.close() + } +} + +@Composable +fun ManagerAppScreen(certManager: NiapCertManager) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(16.dp) + ) { + Text("NIAP Cert Manager Service", style = MaterialTheme.typography.headlineMedium) + Spacer(modifier = Modifier.height(16.dp)) + Text( + "ใ“ใฎใ‚ขใƒ—ใƒชใฏ Intent ็ตŒ็”ฑใงๅˆถๅพกใ—ใพใ™ใ€‚", + style = MaterialTheme.typography.bodyMedium + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + "enroll: action=enroll, alias, estUrl, authToken, subjectDn, caPemUrl\n" + + "verify: action=verifyMtls, alias, protectedUrl, caPemUrl", + style = MaterialTheme.typography.bodySmall + ) + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/NiapCertOrchestrator.kt b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/NiapCertOrchestrator.kt new file mode 100644 index 0000000..0664159 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/NiapCertOrchestrator.kt @@ -0,0 +1,72 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.service + +import android.content.Context +import android.util.Log +import com.android.niap.cert.manager.EnrollmentRequest +import com.android.niap.cert.service.engine.CsrEngine +import com.android.niap.cert.service.engine.EstClient +import com.android.niap.cert.service.engine.KeyStoreEngine +import com.android.niap.cert.service.engine.CertValidator +class NiapCertOrchestrator(private val context: Context) { + private val csrEngine = CsrEngine() + private val estClient = EstClient(context) + private val validator = CertValidator() + private val keyStoreEngine = KeyStoreEngine() + + data class WorkflowResult( + val certificateData: ByteArray?, + val errorMessage: String? + ) + + suspend fun executeWorkflow(request: EnrollmentRequest): WorkflowResult { + val alias = request.alias + Log.d("NiapCertOrchestrator", "Generating CSR for $alias") + val csr = csrEngine.generateCsr(alias, request.subjectDn, request.sans, request.csrSpec) + + Log.d("NiapCertOrchestrator", "Acquiring certificate via EST from ${request.estServerUrl}") + val certResponse = estClient.acquireCertificate(csr, request.estServerUrl, request.authToken, request.trustedCaPem) + + if (certResponse.isEmpty()) { + val errMsg = estClient.lastError ?: "Connection refused or unreachable" + Log.e("NiapCertOrchestrator", "Network error during EST certificate acquisition: $errMsg") + return WorkflowResult(null, errMsg) + } + + Log.d("NiapCertOrchestrator", "Validating received certificate") + val isValid = validator.validate(certResponse, request.validatorConfig) + + return if (isValid) { + Log.d("NiapCertOrchestrator", "Storing certificate in KeyStore") + keyStoreEngine.storeCertificate(alias, certResponse) + WorkflowResult(keyStoreEngine.getCertificateData(alias), null) + } else { + val errMsg = validator.lastError ?: "Certificate validation failed" + WorkflowResult(null, errMsg) + } + } + + fun hasEnrollment(alias: String): Boolean = keyStoreEngine.getCertificateData(alias).isNotEmpty() + + fun getCertificateData(alias: String): ByteArray = keyStoreEngine.getCertificateData(alias) + + suspend fun revoke(alias: String) { + estClient.revokeCertificate(alias) + keyStoreEngine.deleteCertificate(alias) + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/NiapCertService.kt b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/NiapCertService.kt new file mode 100644 index 0000000..7fecc4c --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/NiapCertService.kt @@ -0,0 +1,180 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.service + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.Service +import android.content.Context +import android.content.Intent +import android.os.IBinder +import android.util.Log +import com.android.niap.cert.manager.EnrollmentRequest +import com.android.niap.cert.manager.IEnrollmentCallback +import com.android.niap.cert.manager.INiapCertManager +import com.android.niap.cert.manager.IRevocationCallback +import com.android.niap.cert.service.engine.KeyStoreEngine +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch + +class NiapCertService : Service() { + + private val orchestrator by lazy { NiapCertOrchestrator(this) } + private val keyStoreEngine by lazy { KeyStoreEngine() } + private val serviceScope = CoroutineScope(Dispatchers.Default) + + inner class CertBinder : INiapCertManager.Stub() { + override fun enroll( + alias: String?, estServerUrl: String?, authToken: String?, subjectDn: String?, + sans: List?, keyTypeStr: String?, sigAlgStr: String?, + trustedCaPem: String?, validatorConfig: android.os.Bundle?, + callback: IEnrollmentCallback? + ) { + if (callback == null) { + Log.e("NiapCertService", "enroll: callback must not be null") + return + } + if (alias == null || estServerUrl == null || authToken == null || subjectDn == null) { + Log.e("NiapCertService", "enroll: missing required parameters") + safeOnError(callback, "Missing required enrollment parameters") + return + } + Log.d("NiapCertService", "Enroll request for alias: $alias") + val keyType = try { com.android.niap.cert.manager.KeyType.valueOf(keyTypeStr ?: "EC_P384") } catch (e: Exception) { com.android.niap.cert.manager.KeyType.EC_P384 } + val sigAlg = try { com.android.niap.cert.manager.SigAlg.valueOf(sigAlgStr ?: "SHA384_ECDSA") } catch (e: Exception) { com.android.niap.cert.manager.SigAlg.SHA384_ECDSA } + val config = if (validatorConfig != null) { + com.android.niap.cert.manager.ValidatorConfig( + strictSigAlg = validatorConfig.getBoolean("strictSigAlg", true), + enforceCaConstraints = validatorConfig.getBoolean("enforceCaConstraints", true), + enforceMandatoryExtensions = validatorConfig.getBoolean("enforceMandatoryExtensions", true), + enforceEku = validatorConfig.getBoolean("enforceEku", true) + ) + } else com.android.niap.cert.manager.ValidatorConfig() + + val request = EnrollmentRequest( + alias = alias, estServerUrl = estServerUrl, authToken = authToken, + subjectDn = subjectDn, sans = sans ?: emptyList(), + csrSpec = com.android.niap.cert.manager.CsrSpec(keyType, sigAlg), + trustedCaPem = trustedCaPem ?: "", validatorConfig = config + ) + + serviceScope.launch { + try { + val result = orchestrator.executeWorkflow(request) + if (result.certificateData != null) { + safeOnSuccess(callback, result.certificateData) + } else { + safeOnError(callback, result.errorMessage ?: "Unknown enrollment error") + } + } catch (e: Exception) { + Log.e("NiapCertService", "Enrollment threw exception: ${e.message}", e) + safeOnError(callback, e.message ?: e.javaClass.simpleName) + } + } + } + + override fun revoke(alias: String?, callback: IRevocationCallback?) { + if (callback == null) { + Log.e("NiapCertService", "revoke: callback must not be null") + return + } + if (alias.isNullOrEmpty()) { + safeRevokeError(callback, "Missing alias") + return + } + Log.d("NiapCertService", "Revoke request for alias: $alias") + serviceScope.launch { + try { + orchestrator.revoke(alias) + safeRevokeSuccess(callback) + } catch (e: Exception) { + Log.e("NiapCertService", "Revocation threw exception: ${e.message}", e) + safeRevokeError(callback, e.message ?: e.javaClass.simpleName) + } + } + } + + override fun hasEnrollment(alias: String?): Boolean = + !alias.isNullOrEmpty() && orchestrator.hasEnrollment(alias) + + override fun getCertificateData(alias: String?): ByteArray = + orchestrator.getCertificateData(alias ?: "") + + /** + * Signing oracle: signs [digestBytes] with the AndroidKeyStore key bound to [alias]. + * NONEwithECDSA โ€” Conscrypt has already computed the digest. + */ + override fun sign(alias: String?, digestBytes: ByteArray?): ByteArray { + requireNotNull(alias) { "alias must not be null" } + requireNotNull(digestBytes) { "digestBytes must not be null" } + return keyStoreEngine.sign(alias, digestBytes) + } + } + + private val binder = CertBinder() + + override fun onCreate() { + super.onCreate() + Log.d("NiapCertService", "Service created") + createNotificationChannel() + startForeground(1, createNotification(), android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) + } + + override fun onBind(intent: Intent?): IBinder { + Log.d("NiapCertService", "Service bound") + return binder + } + + private fun createNotificationChannel() { + val channel = NotificationChannel("niap_cert_channel", "NIAP Certificate Manager", NotificationManager.IMPORTANCE_LOW) + (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel) + } + + private fun createNotification() = Notification.Builder(this, "niap_cert_channel") + .setContentTitle("NIAP Cert Manager") + .setContentText("Managing certificates securely") + .setSmallIcon(android.R.drawable.ic_dialog_info) + .build() + + // --- callback invocation helpers (swallow RemoteException; caller already gone) --- + + private fun safeOnSuccess(cb: IEnrollmentCallback, data: ByteArray) { + try { cb.onSuccess(data) } catch (e: android.os.RemoteException) { + Log.w("NiapCertService", "Enrollment callback unreachable: ${e.message}") + } + } + + private fun safeOnError(cb: IEnrollmentCallback, msg: String) { + try { cb.onError(msg) } catch (e: android.os.RemoteException) { + Log.w("NiapCertService", "Enrollment error callback unreachable: ${e.message}") + } + } + + private fun safeRevokeSuccess(cb: IRevocationCallback) { + try { cb.onSuccess() } catch (e: android.os.RemoteException) { + Log.w("NiapCertService", "Revocation callback unreachable: ${e.message}") + } + } + + private fun safeRevokeError(cb: IRevocationCallback, msg: String) { + try { cb.onError(msg) } catch (e: android.os.RemoteException) { + Log.w("NiapCertService", "Revocation error callback unreachable: ${e.message}") + } + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/CertValidator.kt b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/CertValidator.kt new file mode 100644 index 0000000..e6f1119 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/CertValidator.kt @@ -0,0 +1,70 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.service.engine + +import android.util.Log +import com.android.niap.cert.validator.NiapCertValidator +import java.io.ByteArrayInputStream +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate + +import com.android.niap.cert.manager.ValidatorConfig + +class CertValidator { + + var lastError: String? = null + + fun validate(certData: ByteArray, config: ValidatorConfig): Boolean { + lastError = null + try { + Log.d("CertValidator", "Validating received certificate data (${certData.size} bytes)") + val factory = CertificateFactory.getInstance("X.509") + + // Try to Base64 decode the response if it is Base64 encoded, otherwise use raw bytes. + val decodedData = try { + android.util.Base64.decode(certData, android.util.Base64.DEFAULT) + } catch (e: Exception) { + certData + } + + // PKCS#7 responses contain multiple certificates in a CMS signed data block. + // We must parse all certs in the chain using generateCertificates. + val certificates = factory.generateCertificates(ByteArrayInputStream(decodedData)) + val certsChain = certificates.filterIsInstance().toTypedArray() + + if (certsChain.isEmpty()) { + throw java.security.cert.CertificateException("No certificates found in PKCS#7 response") + } + + Log.d("CertValidator", "Parsed chain of ${certsChain.size} certificates, initiating validation") + val validator = NiapCertValidator( + strictSigAlg = config.strictSigAlg, + enforceCaConstraints = config.enforceCaConstraints, + enforceMandatoryExtensions = config.enforceMandatoryExtensions, + enforceEku = config.enforceEku, + requiredEkus = listOf("clientAuth") + ) + validator.validateCertificate(certsChain) + Log.d("CertValidator", "Certificate validation passed successfully") + return true + } catch (e: Exception) { + lastError = e.message ?: e.javaClass.simpleName + Log.e("CertValidator", "Certificate validation failed: ${e.message}") + return false + } + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/CsrEngine.kt b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/CsrEngine.kt new file mode 100644 index 0000000..b6ce598 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/CsrEngine.kt @@ -0,0 +1,112 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.service.engine + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import com.android.niap.cert.manager.CsrSpec +import com.android.niap.cert.manager.KeyType +import com.android.niap.cert.manager.SigAlg +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers +import org.bouncycastle.asn1.x500.X500Name +import org.bouncycastle.asn1.x509.Extension +import org.bouncycastle.asn1.x509.ExtensionsGenerator +import org.bouncycastle.asn1.x509.GeneralName +import org.bouncycastle.asn1.x509.GeneralNames +import org.bouncycastle.pkcs.PKCS10CertificationRequest +import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder +import java.security.KeyPairGenerator +import java.security.KeyStore +import java.security.spec.ECGenParameterSpec + +class CsrEngine : INiapCsrEngine { + + override fun generateCsr(alias: String, subjectDn: String, sans: List, spec: CsrSpec): ByteArray { + // 1. Generate KeyPair in Android KeyStore based on CsrSpec + val keyPair = generateKeyPairInKeyStore(alias, spec.keyType) + + // 2. Build Subject DN + val subject = X500Name(subjectDn) + + // 3. Initialize CSR Builder with Public Key + val csrBuilder = JcaPKCS10CertificationRequestBuilder(subject, keyPair.public) + + // 4. Add SAN (Subject Alternative Name) Extensions if present + if (sans.isNotEmpty()) { + val extensionsGenerator = ExtensionsGenerator() + val generalNames = sans.map { san -> + if (android.util.Patterns.IP_ADDRESS.matcher(san).matches()) { + GeneralName(GeneralName.iPAddress, san) + } else { + GeneralName(GeneralName.dNSName, san) + } + }.toTypedArray() + + val sanSeq = GeneralNames(generalNames) + extensionsGenerator.addExtension( + Extension.subjectAlternativeName, + false, + sanSeq.toASN1Primitive() + ) + csrBuilder.addAttribute( + PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, + extensionsGenerator.generate() + ) + } + + // 5. Sign CSR using Private Key from Android KeyStore based on CsrSpec + val signer = JcaContentSignerBuilder(spec.sigAlg.algorithmName) + .setProvider("AndroidKeyStoreBCWorkaround") + .build(keyPair.private) + val csr: PKCS10CertificationRequest = csrBuilder.build(signer) + + // 6. Return DER encoded CSR + return csr.encoded + } + + private fun generateKeyPairInKeyStore(alias: String, keyType: KeyType): java.security.KeyPair { + val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + if (keyStore.containsAlias(alias)) { + keyStore.deleteEntry(alias) + } + + val keyPairGenerator = KeyPairGenerator.getInstance(keyType.keyAlgorithm, "AndroidKeyStore") + val builder = KeyGenParameterSpec.Builder( + alias, + KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY + ) + + val paramSpecName = keyType.parameterSpecName + val size = keyType.keySize + if (paramSpecName != null) { + builder.setAlgorithmParameterSpec(ECGenParameterSpec(paramSpecName)) + } else if (size != null) { + builder.setKeySize(size) + } + + builder.setDigests( + KeyProperties.DIGEST_NONE, // Required: Conscrypt uses NONEwithECDSA for TLS CertificateVerify + KeyProperties.DIGEST_SHA256, + KeyProperties.DIGEST_SHA384, + KeyProperties.DIGEST_SHA512 + ) + + keyPairGenerator.initialize(builder.build()) + return keyPairGenerator.generateKeyPair() + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/EstClient.kt b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/EstClient.kt new file mode 100644 index 0000000..9fd6a97 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/EstClient.kt @@ -0,0 +1,171 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.service.engine + +import android.content.Context +import android.util.Base64 +import android.util.Log +import com.android.niap.cert.validator.NiapCertHelper +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import java.io.IOException + +import java.security.KeyStore +import java.security.cert.CertificateFactory +import javax.net.ssl.SSLContext +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509TrustManager +import javax.net.ssl.SSLSocketFactory + +class EstClient(private val context: Context) { + + private val client: OkHttpClient by lazy { + val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { + init(null as KeyStore?) + } + val systemTm = tmf.trustManagers.first { it is X509TrustManager } as X509TrustManager + val sslContext = SSLContext.getInstance("TLS").apply { + init(null, arrayOf(systemTm), null) + } + val emsSocketFactory = com.android.niap.cert.validator.VerifiableSSLSocketFactory( + delegate = sslContext.socketFactory, + requireExtendedMasterSecret = true + ) + OkHttpClient.Builder() + .sslSocketFactory(emsSocketFactory, systemTm) + .build() + } + + var lastError: String? = null + + /** + * Acquires a certificate from an EST server (RFC 7030) using /simpleenroll endpoint. + */ + fun acquireCertificate(csr: ByteArray, serverUrl: String, authToken: String, trustedCaPem: String): ByteArray { + lastError = null + val base64Csr = Base64.encodeToString(csr, Base64.DEFAULT) + val requestBody = base64Csr.toRequestBody("application/pkcs10".toMediaType()) + + // Ensure URL ends correctly without duplicate paths + val endpoint = if (serverUrl.endsWith("/simpleenroll")) { + serverUrl + } else if (serverUrl.contains("/est/")) { + // If user explicitly specified an est path (like /est/simpleenroll) + val base = serverUrl.removeSuffix("/") + if (base.endsWith("simpleenroll")) base else "$base/simpleenroll" + } else if (serverUrl.contains("/.well-known/est")) { + val base = serverUrl.removeSuffix("/").removeSuffix("/.well-known/est") + "$base/.well-known/est/simpleenroll" + } else { + "${serverUrl.removeSuffix("/")}/.well-known/est/simpleenroll" + } + + Log.d("EstClient", "POSTing CSR to EST endpoint: $endpoint") + + val requestBuilder = Request.Builder() + .url(endpoint) + .post(requestBody) + .header("Content-Type", "application/pkcs10") + + if (authToken.isNotEmpty()) { + val authHeader = if (authToken.startsWith("Basic ") || authToken.startsWith("Bearer ")) { + authToken + } else if (authToken.contains(":")) { + val encoded = Base64.encodeToString(authToken.toByteArray(), Base64.NO_WRAP) + "Basic $encoded" + } else { + "Basic $authToken" + } + requestBuilder.header("Authorization", authHeader) + Log.d("EstClient", "Configured Authorization header style: ${if (authHeader.startsWith("Basic")) "Basic [Base64]" else "Custom"}") + } + + val request = requestBuilder.build() + + val activeClient = if (trustedCaPem.isNotEmpty()) { + try { + Log.d("EstClient", "Configuring custom TLS trust anchor from PEM data") + val (sslSocketFactory, trustManager) = createSslSocketFactory(trustedCaPem) + client.newBuilder() + .sslSocketFactory(sslSocketFactory, trustManager) + .build() + } catch (e: Exception) { + val msg = "Failed to configure custom TLS trust anchor: ${e.message ?: e.javaClass.simpleName}" + lastError = msg + Log.e("EstClient", msg, e) + return ByteArray(0) + } + } else { + client + } + + try { + activeClient.newCall(request).execute().use { response -> + if (!response.isSuccessful) { + val msg = "HTTP ${response.code}: ${response.message}" + lastError = msg + Log.e("EstClient", "EST enrollment failed with $msg") + throw IOException(msg) + } + + val responseBody = response.body?.bytes() ?: throw IOException("Empty response body from EST server") + Log.d("EstClient", "EST enrollment successful. Received ${responseBody.size} bytes") + Log.d("EstClient", "Response body string:\n" + String(responseBody)) + return responseBody + } + } catch (e: Exception) { + lastError = lastError ?: e.message ?: e.javaClass.simpleName + Log.e("EstClient", "Exception during EST acquisition: ${e.message}", e) + return ByteArray(0) + } + } + + private fun createSslSocketFactory(caPem: String): Pair { + val cf = CertificateFactory.getInstance("X.509") + val cert = cf.generateCertificate(caPem.byteInputStream()) + + val keyStore = KeyStore.getInstance(KeyStore.getDefaultType()).apply { + load(null, null) + setCertificateEntry("ca", cert) + } + + val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { + init(keyStore) + } + + val trustManagers = tmf.trustManagers + val x509TrustManager = trustManagers[0] as X509TrustManager + + val sslContext = SSLContext.getInstance("TLS").apply { + init(null, arrayOf(x509TrustManager), null) + } + + val emsSocketFactory = com.android.niap.cert.validator.VerifiableSSLSocketFactory( + delegate = sslContext.socketFactory, + requireExtendedMasterSecret = true + ) + + return Pair(emsSocketFactory, x509TrustManager) + } + + fun revokeCertificate(alias: String): Boolean { + Log.d("EstClient", "Revoking certificate for $alias") + return true + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/INiapCsrEngine.kt b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/INiapCsrEngine.kt new file mode 100644 index 0000000..dd59b90 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/INiapCsrEngine.kt @@ -0,0 +1,23 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.service.engine + +import com.android.niap.cert.manager.CsrSpec + +interface INiapCsrEngine { + fun generateCsr(alias: String, subjectDn: String, sans: List, spec: CsrSpec = CsrSpec()): ByteArray +} diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/KeyStoreEngine.kt b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/KeyStoreEngine.kt new file mode 100644 index 0000000..2a58b9a --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/kotlin/com/android/niap/cert/service/engine/KeyStoreEngine.kt @@ -0,0 +1,113 @@ +/* + * Copyright 2026 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. + */ + +package com.android.niap.cert.service.engine + +import android.util.Log +import java.io.ByteArrayInputStream +import java.security.KeyStore +import java.security.PrivateKey +import java.security.Signature +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate + +class KeyStoreEngine { + + private val keyStore: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + + fun storeCertificate(alias: String, certData: ByteArray): Boolean { + try { + Log.d("KeyStoreEngine", "Storing certificate chain for alias: $alias") + val factory = CertificateFactory.getInstance("X.509") + + // Try to Base64 decode the response if it is Base64 encoded, otherwise use raw bytes. + val decodedData = try { + android.util.Base64.decode(certData, android.util.Base64.DEFAULT) + } catch (e: Exception) { + certData + } + + // Parse all certs in the chain from the PKCS#7 container + val certificates = factory.generateCertificates(ByteArrayInputStream(decodedData)) + val certsChain = certificates.filterIsInstance().toTypedArray() + + if (certsChain.isEmpty()) { + throw java.security.cert.CertificateException("No certificates found in PKCS#7 response to store") + } + + if (keyStore.containsAlias(alias)) { + val entry = keyStore.getEntry(alias, null) + if (entry is KeyStore.PrivateKeyEntry) { + // Update the hardware-backed key entry with the complete X.509 chain + val privateKey: PrivateKey = entry.privateKey + keyStore.setKeyEntry(alias, privateKey, null, certsChain) + Log.d("KeyStoreEngine", "Successfully updated hardware key chain with ${certsChain.size} certificates for $alias") + return true + } + } + + // Fallback: store the leaf certificate + keyStore.setCertificateEntry(alias, certsChain[0]) + Log.d("KeyStoreEngine", "Successfully stored certificate entry for $alias") + return true + } catch (e: Exception) { + Log.e("KeyStoreEngine", "Failed to store certificate in Android KeyStore", e) + return false + } + } + + fun deleteCertificate(alias: String): Boolean { + try { + if (keyStore.containsAlias(alias)) { + keyStore.deleteEntry(alias) + Log.d("KeyStoreEngine", "Deleted KeyStore entry for $alias") + } + return true + } catch (e: Exception) { + Log.e("KeyStoreEngine", "Failed to delete KeyStore entry", e) + return false + } + } + + fun getCertificateData(alias: String): ByteArray { + try { + if (keyStore.containsAlias(alias)) { + val cert = keyStore.getCertificate(alias) + if (cert != null) { + return cert.encoded + } + } + } catch (e: Exception) { + Log.e("KeyStoreEngine", "Failed to get certificate data from KeyStore", e) + } + return ByteArray(0) + } + + /** + * Signs [digestBytes] with the AndroidKeyStore key bound to [alias] using NONEwithECDSA. + * Conscrypt passes a pre-computed digest for TLS CertificateVerify; the key must have + * DIGEST_NONE in its permitted digests (see CsrEngine). + */ + fun sign(alias: String, digestBytes: ByteArray): ByteArray { + val key = keyStore.getKey(alias, null) as? PrivateKey + ?: throw IllegalStateException("No private key found for alias '$alias'") + return Signature.getInstance("NONEwithECDSA").run { + initSign(key) + update(digestBytes) + sign() + } + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-manager/src/main/res/xml/network_security_config.xml b/niap-cc/niap-android-cert-ext/cert-manager/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..c781f91 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-manager/src/main/res/xml/network_security_config.xml @@ -0,0 +1,22 @@ + + + + + testrfc7030.com + localhost + + diff --git a/niap-cc/niap-android-cert-ext/cert-test-app/build.gradle.kts b/niap-cc/niap-android-cert-ext/cert-test-app/build.gradle.kts new file mode 100644 index 0000000..8ff7672 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-test-app/build.gradle.kts @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2026 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. + */ + +import java.io.File + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") + id("org.jetbrains.kotlin.plugin.compose") version "2.2.0" +} + +android { + namespace = "com.example.niap.cert.ext.testapp.cert" + compileSdk = 34 + + defaultConfig { + applicationId = "com.example.niap.cert.ext.testapp.cert" + minSdk = 32 + targetSdk = 34 + versionCode = 1 + versionName = "1.0" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = "1.8" + } + buildFeatures { + compose = true + } + lint { + error += setOf( + "PrivateApi", + "DiscouragedPrivateApi", + "SoonBlockedPrivateApi", + "BlockedPrivateApi" + ) + abortOnError = true + } +} + +dependencies { + implementation(project(":cert-lib")) + implementation("androidx.core:core-ktx:1.12.0") + implementation("androidx.appcompat:appcompat:1.6.1") + implementation("androidx.work:work-runtime-ktx:2.9.0") + implementation("com.squareup.okhttp3:okhttp:4.12.0") + + // Jetpack Compose UI + val composeBom = platform("androidx.compose:compose-bom:2024.02.00") + implementation(composeBom) + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.material3:material3") + implementation("androidx.activity:activity-compose:1.8.2") + implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0") +} + +val testbedRoot = gradle.extra["testbedRoot"] as File +val skipTestbedCopy = providers.gradleProperty("skipTestbedCopy") + .map { it.isEmpty() || it.equals("true", ignoreCase = true) } + .getOrElse(false) + +tasks.register("copyApkToCore") { + description = "Copies the generated APK to the TestBed Core resources directory." + enabled = !skipTestbedCopy + onlyIf { !skipTestbedCopy } + + from(layout.buildDirectory.dir("outputs/apk/debug")) + include("*-debug.apk") + val coreResourcesDir = File(testbedRoot, "testbed-core/composeApp/resources") + into(coreResourcesDir) + rename { "cert-test-app-debug.apk" } + doFirst { + coreResourcesDir.mkdirs() + } + doLast { + println("โœ… APK copied to: ${coreResourcesDir.absolutePath}") + } +} + +if (!skipTestbedCopy) { + tasks.named("assemble") { + finalizedBy("copyApkToCore") + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-test-app/src/main/AndroidManifest.xml b/niap-cc/niap-android-cert-ext/cert-test-app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..363ed50 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-test-app/src/main/AndroidManifest.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/niap-cc/niap-android-cert-ext/cert-test-app/src/main/kotlin/com/example/niap/cert/ext/testapp/cert/CertTestActivity.kt b/niap-cc/niap-android-cert-ext/cert-test-app/src/main/kotlin/com/example/niap/cert/ext/testapp/cert/CertTestActivity.kt new file mode 100644 index 0000000..6a24cb5 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-test-app/src/main/kotlin/com/example/niap/cert/ext/testapp/cert/CertTestActivity.kt @@ -0,0 +1,309 @@ +/* + * Copyright 2026 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. + */ + +package com.example.niap.cert.ext.testapp.cert + +import android.content.Context +import android.os.Bundle +import android.util.Log +import android.webkit.WebView +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import com.android.niap.cert.manager.EnrollmentRequest +import com.android.niap.cert.manager.NiapCertManager +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import okhttp3.OkHttpClient +import okhttp3.Request +import java.io.ByteArrayInputStream +import java.security.KeyStore +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509TrustManager + +class CertTestActivity : ComponentActivity() { + + private lateinit var certManager: NiapCertManager + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + certManager = NiapCertManager(applicationContext) + + setContent { + MaterialTheme { + Surface( + modifier = Modifier.fillMaxSize(), + color = MaterialTheme.colorScheme.background + ) { + CertAppScreen(certManager) + } + } + } + } + + override fun onDestroy() { + super.onDestroy() + certManager.close() + } +} + +@Composable +fun CertAppScreen(certManager: NiapCertManager) { + val context = LocalContext.current + val coroutineScope = rememberCoroutineScope() + + val prefs = remember { context.getSharedPreferences("cert_test_prefs", Context.MODE_PRIVATE) } + + var alias by remember { mutableStateOf(prefs.getString("alias", "test_client_cert")!!) } + var estUrl by remember { mutableStateOf(prefs.getString("estUrl", "https://localhost:8443/.well-known/est/")!!) } + var authToken by remember { mutableStateOf(prefs.getString("authToken", "estuser:estpwd")!!) } + var subjectDn by remember { mutableStateOf(prefs.getString("subjectDn", "CN=TestUser")!!) } + var caPemUrl by remember { mutableStateOf(prefs.getString("caPemUrl", "http://localhost:8080/cacert.pem")!!) } + var mtlsEndpoint by remember { mutableStateOf(prefs.getString("mtlsEndpoint", "https://localhost:8081/protected/")!!) } + + fun savePrefs() { + prefs.edit() + .putString("alias", alias) + .putString("estUrl", estUrl) + .putString("authToken", authToken) + .putString("subjectDn", subjectDn) + .putString("caPemUrl", caPemUrl) + .putString("mtlsEndpoint", mtlsEndpoint) + .apply() + } + + // Load CA PEM: download from URL if set, otherwise fall back to raw resource + suspend fun loadCaPem(): String { + if (caPemUrl.isNotBlank()) { + return try { + java.net.URL(caPemUrl).readText().also { + Log.d("CertTestApp", "Downloaded CA PEM from $caPemUrl (${it.length} bytes)") + } + } catch (e: Exception) { + Log.w("CertTestApp", "Failed to download CA PEM: ${e.message}") + "" + } + } + val resId = context.resources.getIdentifier("est_validation_ca", "raw", context.packageName) + return if (resId != 0) { + context.resources.openRawResource(resId).bufferedReader().use { it.readText() }.also { + Log.d("CertTestApp", "Loaded CA PEM from raw resource (${it.length} bytes)") + } + } else { + Log.w("CertTestApp", "No CA PEM available (URL not set, raw resource not found)") + "" + } + } + + var status by remember { mutableStateOf("IDLE") } + var certSummary by remember { mutableStateOf(null) } + var errorMessage by remember { mutableStateOf(null) } + var logMessages by remember { mutableStateOf(listOf()) } + + // Dialog: (httpCode, responseBody) โ€” null means closed + var responseDialog by remember { mutableStateOf?>(null) } + + fun appendLog(msg: String) { + Log.d("CertTestApp", msg) + logMessages = logMessages + msg + } + + // Response dialog with WebView + responseDialog?.let { (code, body) -> + AlertDialog( + onDismissRequest = { responseDialog = null }, + title = { Text("HTTP $code") }, + text = { + AndroidView( + factory = { ctx -> + WebView(ctx).apply { + val html = "
${body.replace("&", "&").replace("<", "<")}
" + loadDataWithBaseURL(null, html, "text/html", "UTF-8", null) + } + }, + modifier = Modifier + .fillMaxWidth() + .height(320.dp) + ) + }, + confirmButton = { + TextButton(onClick = { responseDialog = null }) { Text("Close") } + } + ) + } + + Column( + modifier = Modifier + .fillMaxSize() + .padding(16.dp) + .verticalScroll(rememberScrollState()) + ) { + Text("NIAP EST Enrollment Client", style = MaterialTheme.typography.headlineMedium) + Spacer(modifier = Modifier.height(16.dp)) + + OutlinedTextField(value = alias, onValueChange = { alias = it; savePrefs() }, label = { Text("Key Alias") }, modifier = Modifier.fillMaxWidth()) + Spacer(modifier = Modifier.height(8.dp)) + OutlinedTextField(value = estUrl, onValueChange = { estUrl = it; savePrefs() }, label = { Text("EST Server URL") }, modifier = Modifier.fillMaxWidth()) + Spacer(modifier = Modifier.height(8.dp)) + OutlinedTextField(value = authToken, onValueChange = { authToken = it; savePrefs() }, label = { Text("Auth Token (user:pass)") }, modifier = Modifier.fillMaxWidth()) + Spacer(modifier = Modifier.height(8.dp)) + OutlinedTextField(value = subjectDn, onValueChange = { subjectDn = it; savePrefs() }, label = { Text("Subject DN") }, modifier = Modifier.fillMaxWidth()) + Spacer(modifier = Modifier.height(8.dp)) + OutlinedTextField(value = caPemUrl, onValueChange = { caPemUrl = it; savePrefs() }, label = { Text("CA PEM URL (blank = raw resource)") }, modifier = Modifier.fillMaxWidth()) + Spacer(modifier = Modifier.height(8.dp)) + OutlinedTextField(value = mtlsEndpoint, onValueChange = { mtlsEndpoint = it; savePrefs() }, label = { Text("mTLS Endpoint URL") }, modifier = Modifier.fillMaxWidth()) + Spacer(modifier = Modifier.height(16.dp)) + + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) { + Button(onClick = { + coroutineScope.launch(Dispatchers.IO) { + logMessages = emptyList() + certSummary = null + errorMessage = null + status = "ENROLLING" + val caPem = loadCaPem() + appendLog("CA PEM: ${caPem.length} bytes") + // Use custom CA as TLS trust anchor only for self-signed servers (localhost / private IP). + // Public endpoints (Cloud Run etc.) use the system trust store. + val isPrivate = estUrl.contains("localhost") || estUrl.contains("10.0.2.2") || estUrl.contains("192.168.") + val trustAnchor = if (isPrivate) caPem else "" + if (!isPrivate) appendLog("Public EST URL โ€” using system trust store") + val req = EnrollmentRequest(alias, estUrl, authToken, subjectDn, trustedCaPem = trustAnchor) + try { + val certBytes = certManager.enroll(req).get(30, java.util.concurrent.TimeUnit.SECONDS) + status = "READY" + val cert = CertificateFactory.getInstance("X.509") + .generateCertificate(ByteArrayInputStream(certBytes)) as X509Certificate + certSummary = "Subject: ${cert.subjectDN}\nIssuer: ${cert.issuerDN}\nSerial: ${cert.serialNumber}\nAlg: ${cert.sigAlgName}\nValid: ${cert.notBefore} โ€“ ${cert.notAfter}" + appendLog("Enrollment succeeded") + } catch (e: java.util.concurrent.ExecutionException) { + status = "FAILED" + val detail = e.cause?.message ?: e.message ?: "Unknown error" + appendLog("Enrollment failed: $detail") + errorMessage = detail + } catch (e: Exception) { + status = "FAILED" + appendLog("Enrollment error: ${e.message}") + errorMessage = e.message + } + } + }) { Text("Enroll (EST)") } + + Button( + onClick = { + coroutineScope.launch(Dispatchers.IO) { + appendLog("Revoking alias: $alias") + try { + certManager.revoke(alias).get(15, java.util.concurrent.TimeUnit.SECONDS) + status = "REVOKED" + certSummary = null + errorMessage = null + } catch (e: Exception) { + appendLog("Revoke failed: ${e.message}") + } + } + }, + colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error) + ) { Text("Revoke") } + + Button( + onClick = { + coroutineScope.launch(Dispatchers.IO) { + appendLog("Opening mTLS endpoint: $mtlsEndpoint") + try { + val caPem = loadCaPem() + val helper = com.android.niap.cert.validator.NiapCertHelper.getInstance(context) + val km = certManager.getKeyManager(alias) + val (options, anchors) = if (caPem.isNotBlank()) { + com.android.niap.cert.validator.NiapCertHelper.TrustAnchorOptions.USER_CA_ONLY to + mapOf("ca" to caPem.byteInputStream()) + } else { + com.android.niap.cert.validator.NiapCertHelper.TrustAnchorOptions.SYSTEM_CA_ONLY to null + } + val client = helper.configureOkHttp( + builder = OkHttpClient.Builder(), + trustAnchors = anchors, + options = options, + keyManager = km + ).build() + val response = client.newCall(Request.Builder().url(mtlsEndpoint).get().build()).execute() + val code = response.code + val body = response.body?.string() ?: "" + appendLog("Response: HTTP $code") + responseDialog = code to body + } catch (e: Exception) { + appendLog("Error: ${e.message}") + responseDialog = 0 to (e.message ?: e.javaClass.simpleName) + } + } + }, + enabled = mtlsEndpoint.isNotBlank() + ) { Text("mTLS") } + } + + Spacer(modifier = Modifier.height(16.dp)) + Text("Status: $status", style = MaterialTheme.typography.titleMedium) + + errorMessage?.let { + Spacer(modifier = Modifier.height(8.dp)) + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text("Enrollment Failed", style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.onErrorContainer) + Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onErrorContainer) + } + } + } + + certSummary?.let { + Spacer(modifier = Modifier.height(8.dp)) + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text("Certificate", style = MaterialTheme.typography.titleSmall) + Text(it, style = MaterialTheme.typography.bodySmall) + } + } + } + + // โ”€โ”€ Logs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + Spacer(modifier = Modifier.height(16.dp)) + Text("Logs:", style = MaterialTheme.typography.titleSmall) + Spacer(modifier = Modifier.height(4.dp)) + Card( + modifier = Modifier.fillMaxWidth().height(180.dp), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant) + ) { + Column(modifier = Modifier.padding(8.dp).verticalScroll(rememberScrollState())) { + logMessages.forEach { Text(it, style = MaterialTheme.typography.bodySmall) } + } + } + } +} diff --git a/niap-cc/niap-android-cert-ext/cert-test-app/src/main/res/raw/est_validation_ca.pem b/niap-cc/niap-android-cert-ext/cert-test-app/src/main/res/raw/est_validation_ca.pem new file mode 100644 index 0000000..b42a508 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-test-app/src/main/res/raw/est_validation_ca.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICUjCCAdegAwIBAgIUI93ak0Af/PpdrSMXYNNYXsqZV4swCgYIKoZIzj0EAwMw +VjELMAkGA1UEBhMCSlAxDjAMBgNVBAgMBVRva3lvMRYwFAYDVQQKDA1OSUFQIFRl +c3QgTGFiMR8wHQYDVQQDDBZFU1QgVmFsaWRhdGlvbiBSb290IENBMB4XDTI2MDUy +MTA3MDUxMloXDTM2MDUxODA3MDUxMlowVjELMAkGA1UEBhMCSlAxDjAMBgNVBAgM +BVRva3lvMRYwFAYDVQQKDA1OSUFQIFRlc3QgTGFiMR8wHQYDVQQDDBZFU1QgVmFs +aWRhdGlvbiBSb290IENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE912sIneXUhfC +pKCOlPeoJFLVR0CP1s0Z01+IQIuNEGgoHOKJHFbptRdQJX56q5OfQx9JT/ngevEN +XLuKgAZQNlP/ClVpSs2ShgavWjgcBFq5UJ2gwvH/9P8aV/v1Qi38o2YwZDASBgNV +HRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBRPsVVyFfv7Kf9nn7pr6siFah5PuzAf +BgNVHSMEGDAWgBRPsVVyFfv7Kf9nn7pr6siFah5PuzAOBgNVHQ8BAf8EBAMCAQYw +CgYIKoZIzj0EAwMDaQAwZgIxAO8ZMUvtTSUqyCfzpbTxWEuOilNUm2n8UB0lNqHY +mGltrZFFMakwcsl/I4r/V7tYRQIxAIhVhY25gRoVz33MyHCSIkhw3DwuensR4NpB +RM+4/9m5aN5jODgfEW8bjBK3QlZPJg== +-----END CERTIFICATE----- diff --git a/niap-cc/niap-android-cert-ext/cert-test-app/src/main/res/xml/network_security_config.xml b/niap-cc/niap-android-cert-ext/cert-test-app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..e6a7e2f --- /dev/null +++ b/niap-cc/niap-android-cert-ext/cert-test-app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,21 @@ + + + + + localhost + + diff --git a/niap-cc/niap-android-cert-ext/docs/AGD-TLS-guidance.md b/niap-cc/niap-android-cert-ext/docs/AGD-TLS-guidance.md new file mode 100644 index 0000000..99334b4 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/docs/AGD-TLS-guidance.md @@ -0,0 +1,259 @@ +# Administrator and Developer Guidance (AGD): NIAP TLS & X.509 Enforcement (`cert-lib`) + +This document provides operational and integration guidance for configuring, integrating, and verifying the `cert-lib` Android TLS/X.509 library in its **NIAP-evaluated configuration**. It is intended for application developers integrating `cert-lib` and for administrators or evaluation laboratories verifying compliance against NIAP TLS client (`FCS_TLSC_EXT.1`) and X.509 (`FIA_X509_EXT.1`) requirements. + +--- + +## 1. Evaluated Configuration Requirements + +### 1.1 Required `res/xml/niap_security_config.xml` Settings + +Applications integrating `cert-lib` load their policy from `res/xml/niap_security_config.xml` via `NiapCertHelper.getInstance(context)` (if the application does not provide its own XML resource, the library default in `cert-lib/src/main/res/xml/niap_security_config.xml` is loaded). + +In the evaluated configuration, the following settings are **required**: + +| XML Element | Required Value (Evaluated) | Purpose | +|---|---|---| +| `` | `true` | Enforces SHA-384/SHA-512 signatures and EC P-384/P-521 or RSA โ‰ฅ 3072-bit keys on peer certificates. | +| `` | Built-in list or a strict subset of `NiapTlsPolicy.APPROVED_SUITES` | Restricts negotiated cipher suites to NIAP-approved suites (see Section 2). Omitting or leaving empty uses the full built-in allowlist. | +| `` | `false` (default) or `true` (TLS 1.2 only) | On **API 37+**, enables TLS 1.3 and TLS 1.2 when `false`, or pins to TLS 1.2 only when `true`. On **API โ‰ค 36**, `cert-lib` always runs TLS 1.2 only regardless of this flag (see Section 2.1). | +| `` | `true` | Mandates RFC 7627 Extended Master Secret (EMS) on all TLS 1.2 handshakes (`FCS_TLSC_EXT.1`). | +| `` | `true` | Requires mandatory X.509 extensions (AKID, SKID, KeyUsage) per `FIA_X509_EXT.1.2`. | +| `` | `true` | Requires leaf certificate Extended Key Usage validation. | +| `` | `serverAuth` (or appropriate OID/alias) | Specifies required leaf EKU for TLS server authentication. | +| `` | `true` | Rejects end-entity certificates with `BasicConstraints CA=true`. | +| `` | At least `*.COM`, `*.NET`, `*.ORG`, `*.GOV`, `*.EDU` | Blocks overly broad top-level domain wildcard SANs. | +| `` | `SYSTEM_CA_ONLY`, `USER_CA_ONLY`, or `BOTH_CA` | Controls which trust anchors are accepted. Use `USER_CA_ONLY` when pinning to a private/enterprise CA; avoid trusting untrusted user CAs in production. | + +### 1.2 What the Developer MUST Do +1. **Route all TLS connections through `NiapCertHelper` or `NiapCertManager.getSslSocketFactory(...)`**: + * Use `NiapCertHelper.getInstance(context).configureOkHttp(...)`, `openConnection(...)`, or `createSSLSocketFactory(...)`. + * For hardware-backed client certificates managed by `cert-manager`, use `NiapCertManager.getSslSocketFactory(alias, trustedCaPem, requireExtendedMasterSecret = true)` or pass `NiapCertManager.getKeyManager(alias)` to `NiapCertHelper`. +2. **Preserve hostname verification**: + * For `OkHttpClient`, rely on OkHttp's default RFC 2818/6125 hostname verifier (do not install a permissive `HostnameVerifier`). + * For `HttpsURLConnection`, use the default verifier or delegate to `NiapCertHelper.checkHostname(hostname, session)`. +3. **Reuse the `NiapCertHelper` singleton**: + * Keep the singleton alive across requests so the cached `SSLContext` and TLS session cache enable session resumption. Only call `NiapCertHelper.resetInstance()` when intentionally discarding cached TLS state or reloading configuration. +4. **Ensure server infrastructure supports stapled OCSP**: + * Every TLS server contacted by the application must staple a valid, fresh OCSP response signed with an approved algorithm and key size (see Section 3). + +### 1.3 What the Developer MUST NOT Do +1. **Do NOT weaken XML policy flags** (`niap-rfc8603-strict-sigalg`, `require-extended-master-secret`, `enforce-mandatory-extensions`, `enforce-eku`, `enforce-ca-constraints`) to `false` in production or evaluated builds. +2. **Do NOT use `NiapCertManager.getSslContext(...)`**: It is `@Deprecated` because a raw `SSLContext` bypasses `VerifiableSSLSocketFactory` and cannot enforce cipher suite allowlists, protocol pinning, or Extended Master Secret. +3. **Do NOT disable hostname verification** (e.g. `hostnameVerifier { _, _ -> true }`). +4. **Do NOT add non-approved cipher suites to ``**: Any cipher suite name outside `NiapTlsPolicy.APPROVED_SUITES` causes `NiapCertHelper.fromConfig()` to throw `IllegalArgumentException` at startup. +5. **Do NOT replace the `SSLSocketFactory` or `X509TrustManager` configured by `NiapCertHelper`** with platform defaults. + +--- + +## 2. Supported TLS Protocols, Cipher Suites & Platform-Version-Dependent Behavior + +### 2.1 Platform-Version-Dependent Behavior (API โ‰ค 36 vs. API 37+) + +Device verification on stock-policy Android 16 (API 36) proved that on **API 36 and below** there is no public SDK API for applications to read stapled OCSP responses from an `SSLSession`: the concrete Conscrypt session method is a blocked hidden API, and `javax.net.ssl.ExtendedSSLSession.getStatusResponses()` does not exist at runtime (it is public API only starting in **API 37** per the Android SDK API-version metadata). + +Because TLS 1.3 encrypts the server `Certificate` and `status_request` extensions, an app-level library cannot read TLS 1.3 staples off the wire without platform API support. In TLS 1.2, by contrast, the server's `CertificateStatus` handshake message is transmitted in plaintext prior to `ChangeCipherSpec`, allowing `cert-lib` to read and validate the stapled OCSP response on `SSLSocket` connections without calling any hidden platform API. + +Accordingly, `cert-lib` selects its protocol behavior dynamically based on whether the public `ExtendedSSLSession.getStatusResponses()` API is available at runtime: + +| Aspect | Android 16 and below (API โ‰ค 36) | Android 17 and above (API 37+)* | +|---|---|---| +| **Protocols offered** | **TLS 1.2 only**, regardless of ``. TLS 1.3 is not offered. | **TLS 1.2 + TLS 1.3** when `false` (default), or **TLS 1.2 only** when `true`. | +| **How the OCSP staple is read** | Extracted from the plaintext TLS 1.2 `CertificateStatus` handshake message on the wire (`SSLSocket`). | Read from the session via the public `javax.net.ssl.ExtendedSSLSession.getStatusResponses()` API. | +| **TLS 1.3-only servers** | **Unreachable** โ€” handshake fails with a `protocol_version` alert because TLS 1.3 is not offered. | **Reachable** (subject to NIAP cipher allowlist and valid stapled OCSP response). | +| **Cipher suite advertisement** | Only allowlisted TLS 1.2 suites are advertised; TLS 1.3 suites (including `TLS_CHACHA20_POLY1305_SHA256`) are not advertised at all. | When TLS 1.3 is enabled, platform Conscrypt always advertises `TLS_AES_128_GCM_SHA256`, `TLS_AES_256_GCM_SHA384`, and `TLS_CHACHA20_POLY1305_SHA256`; `cert-lib` rejects any non-allowlisted suite selected by the server (see Section 2.4). | +| **`SSLEngine`-based connections** | **Fail closed** โ€” cannot access staples without the public platform API. | Supported via `ExtendedSSLSession.getStatusResponses()`. | +| **Revocation enforcement** | OCSP stapling only, hard-fail (no CRL or online OCSP fallback). | OCSP stapling only, hard-fail (no CRL or online OCSP fallback). | + +*\*API 37+ behavior still has to be verified on an Android 17 device.* + +> **Requirement for TLS 1.3 with Mandatory OCSP Stapling on API โ‰ค 36:** +> To enforce mandatory OCSP stapling with **TLS 1.3** on Android 16 (API 36) and below, the **OS-integrated (platform) version** is required, because only platform code has access to the encrypted TLS 1.3 stapled OCSP response inside the TLS stack. + +### 2.2 Supported Protocols +* **API 37+ with `false` (default)**: **TLS 1.3** (`TLSv1.3`) and **TLS 1.2** (`TLSv1.2`) are enabled. TLS 1.1 and earlier are disabled by the Android platform (`minSdk = 32+`). +* **API โ‰ค 36 (automatic) or API 37+ with `true`**: Only **TLS 1.2** (`TLSv1.2`) is enabled; TLS 1.3 is disabled and omitted from `ClientHello`. +* **Extended Master Secret (EMS)**: On every TLS 1.2 handshake (when `true`), `VerifiableSSLSocketFactory` inspects the `ServerHello` and rejects the connection with a fatal `handshake_failure` alert if the `extended_master_secret` extension (`0x0017`) is absent. + +### 2.3 Approved Cipher Suites (`NiapTlsPolicy.APPROVED_SUITES`) + +The built-in allowlist is the **AEAD subset of the NIST SP 800-52 Rev. 2 recommended cipher suites supported by the platform TLS stack**. (AES-CCM suites are also SP 800-52 Rev. 2-approved but are not offered by the platform TLS stack; ChaCha20-Poly1305 is not a FIPS-approved algorithm, which is why the library refuses it.) + +| Protocol | Cipher Suite Name | IANA Code Point | +|---|---|---| +| TLS 1.3 *(API 37+ only)* | `TLS_AES_128_GCM_SHA256` | `0x1301` | +| TLS 1.3 *(API 37+ only)* | `TLS_AES_256_GCM_SHA384` | `0x1302` | +| TLS 1.2 | `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` | `0xC02B` | +| TLS 1.2 | `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256` | `0xC02F` | +| TLS 1.2 | `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` | `0xC02C` | +| TLS 1.2 | `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` | `0xC030` | + +XML `` may only narrow this table further (for example, AES-256-only if an evaluation requires it). + +### 2.4 Platform TLS 1.3 Cipher Suite Advertisement Limitation (API 37+) +On **API 37+** when TLS 1.3 is enabled, the Android platform TLS provider (Conscrypt) hard-codes the set of TLS 1.3 cipher suites advertised in `ClientHello`: it **always** offers `TLS_AES_128_GCM_SHA256` (`0x1301`), `TLS_AES_256_GCM_SHA384` (`0x1302`), and `TLS_CHACHA20_POLY1305_SHA256` (`0x1303`), and ignores application calls to `SSLSocket.setEnabledCipherSuites(...)` for TLS 1.3 suites. + +To guarantee that no unapproved TLS 1.3 suite can be negotiated: +1. For **TLS 1.2**, the allowlist is applied directly to the socket and OkHttp `ConnectionSpec`, so only approved TLS 1.2 suites appear in `ClientHello`. +2. For **TLS 1.3** (API 37+), `VerifiableSSLSocketFactory` (`ServerHelloValidator`) parses the server's `ServerHello` on the underlying socket stream before application data or handshake completion proceeds. If the server selects any cipher suite outside the configured allowlist (for example, `0x1303` / `TLS_CHACHA20_POLY1305_SHA256`), the library immediately transmits a fatal TLS `handshake_failure` alert (`0x02 0x28`), shuts down output, and throws `SSLHandshakeException`. +3. Consequently, on API 37+ when TLS 1.3 is enabled, `TLS_CHACHA20_POLY1305_SHA256` may appear in the `ClientHello` cipher list due to platform Conscrypt behavior, **but it is never negotiated**. +4. On **API โ‰ค 36** (where TLS 1.3 is not offered), or on **API 37+** with `true`, no TLS 1.3 cipher suites appear in `ClientHello` at all. + +--- + +## 3. Certificate Revocation Behavior (OCSP Stapling Only) + +* **Offline Stapled OCSP Only**: `cert-lib` validates revocation exclusively via **TLS OCSP stapling** (RFC 6066 `status_request`). It performs **no CRL downloading or checking**, **no online OCSP HTTP queries**, and **no outbound network access** during revocation checking (`PKIXRevocationChecker` configured with `ONLY_END_ENTITY` and `NO_FALLBACK`). +* **Hard-Fail Enforcement (No Override)**: During every full server handshake, `NiapX509TrustManager` obtains the stapled OCSP response โ€” via the plaintext TLS 1.2 `CertificateStatus` handshake message on **API โ‰ค 36** (`SSLSocket`), or via `ExtendedSSLSession.getStatusResponses()` on **API 37+** โ€” and validates it with `OcspStapleValidator`. (`SSLEngine`-based connections fail closed when the public platform API is unavailable.) Connections are **unconditionally rejected** if the staple is: + * Missing or empty + * Revoked (`REVOKED`) or `UNKNOWN` + * Stale/expired or not yet valid (`thisUpdate` / `nextUpdate`) + * Malformed DER or non-successful `OCSPResponseStatus` + * Signed by an untrusted or unauthorized responder, or failing signature verification + * Signed with a non-compliant algorithm or key size +* **OCSP Cryptographic Constraints (`FIA_X509_EXT.1.1`)**: + * **Allowed signature algorithms**: + * `ecdsa-with-SHA384` (`1.2.840.10045.4.3.3`) + * `ecdsa-with-SHA512` (`1.2.840.10045.4.3.4`) + * `sha384WithRSAEncryption` (`1.2.840.113549.1.1.12`) + * `sha512WithRSAEncryption` (`1.2.840.113549.1.1.13`) + * **Allowed OCSP signer keys** (embedded responder certificate if present, otherwise the issuing CA certificate): + * ECDSA on **P-384** or **P-521** + * RSA with modulus **โ‰ฅ 3072 bits** +* **Resumed Sessions**: On resumed TLS handshakes, the platform TLS stack does not re-invoke `checkServerTrusted`; certificate chain and stapled OCSP checks therefore run on **full handshakes only**. +* **Operational Compatibility Note**: Because stapled OCSP is mandatory with no override, endpoints whose issuing CA does not operate an OCSP responder (for example, Let's Encrypt, which discontinued OCSP service in 2025) or servers that do not staple a compliant OCSP response cannot be used with `cert-lib`. + +--- + +## 4. Mutual TLS (Client Certificate Authentication) Setup + +`cert-lib` supports mutual TLS (mTLS) through two equivalent paths, both of which enforce the full NIAP TLS policy (cipher allowlist, protocol pinning, EMS, X.509 validation, and hard-fail OCSP stapling): + +### 4.1 Application-Provided `X509KeyManager` +Load the client credential (for example from a PKCS#12 keystore or Android KeyStore) into a standard `X509KeyManager` and pass it to `NiapCertHelper`: + +```kotlin +val helper = NiapCertHelper.getInstance(context) + +// OkHttp +val client = helper.configureOkHttp( + builder = OkHttpClient.Builder(), + trustAnchors = customAnchors, // or null to use configured policy + options = NiapCertHelper.TrustAnchorOptions.USER_CA_ONLY, + keyManager = clientKeyManager +).build() + +// HttpsURLConnection +val conn = helper.openConnection( + url = URL("https://mtls.example.gov/"), + trustAnchors = customAnchors, + options = NiapCertHelper.TrustAnchorOptions.USER_CA_ONLY, + keyManager = clientKeyManager +) +``` + +### 4.2 Hardware-Backed Credentials via `cert-manager` +When private keys are enrolled and isolated inside the `cert-manager` service: + +```kotlin +val certManager = NiapCertManager(context) +val socketFactory = certManager.getSslSocketFactory( + alias = "client_alias", + trustedCaPem = serverCaPem, + requireExtendedMasterSecret = true +) +``` + +Alternatively, pass `certManager.getKeyManager("client_alias")` into `NiapCertHelper.configureOkHttp(...)` or `NiapCertHelper.openConnection(...)`. Do **not** use the deprecated `NiapCertManager.getSslContext(...)`. + +--- + +## 5. Session Resumption Behavior + +* **Mechanism**: Session resumption is performed by the Android platform TLS stack โ€” **TLS 1.2 session tickets / session IDs** (all supported API levels) and **TLS 1.3 pre-shared keys (`NewSessionTicket` / `pre_shared_key`)** on API 37+ when TLS 1.3 is enabled. +* **Caching Scope**: `NiapCertHelper` caches one `SSLContext` (and its `NiapX509TrustManager` and `VerifiableSSLSocketFactory`) per unique tuple: + `(TrustAnchorOptions, SHA-256(anchor certificates), keyManager identity, requireExtendedMasterSecret)`. +* **Requirements for Resumption**: + 1. Reuse the same `NiapCertHelper` singleton across connections (do not call `NiapCertHelper.resetInstance()` between requests). + 2. When using mTLS, pass the same `X509KeyManager` object reference so the cache key matches. + 3. The peer server must issue session tickets (TLS 1.2/1.3) or support session ID caching (TLS 1.2). +* **Cache Invalidation**: Calling `NiapCertHelper.resetInstance()` clears all cached `SSLContext` instances and discards the client TLS session cache. +* **Security Note**: As noted in Section 3, resumed handshakes reuse the validated session state and do not re-run `checkServerTrusted` or stapled OCSP verification. + +--- + +## 6. Error Messages and Troubleshooting + +All TLS handshake and certificate/OCSP failures surface to callers as `javax.net.ssl.SSLHandshakeException` (with underlying `CertificateException` / `CertPathValidatorException` causes where applicable). + +| Failure Condition | Representative Exception Message | Remediation | +|---|---|---| +| TLS 1.3-only server contacted from Android 16 or below (API โ‰ค 36) | `javax.net.ssl.SSLHandshakeException: ... TLSV1_ALERT_PROTOCOL_VERSION` | Expected on API โ‰ค 36 because `cert-lib` offers TLS 1.2 only when `ExtendedSSLSession.getStatusResponses()` is unavailable. Enable TLS 1.2 (with an approved cipher suite, EMS, and OCSP stapling) on the server, run on API 37+, or deploy the OS-integrated platform version. | +| Platform OCSP staple API unavailable (e.g., `SSLEngine` on API โ‰ค 36) | `Revocation status unavailable: platform API (ExtendedSSLSession.getStatusResponses) unavailable` | Expected fail-closed rejection when the public API is absent and wire-level TLS 1.2 `CertificateStatus` capture is not available (`SSLEngine`). Use `SSLSocket`-based stacks (`HttpsURLConnection` / `OkHttp` via `NiapCertHelper`), run on API 37+, or deploy the OS-integrated platform version. | +| Server selected unapproved cipher suite (API 37+ TLS 1.3, e.g. ChaCha20) | `javax.net.ssl.SSLHandshakeException: Server selected cipher suite 0x1303 (TLS_CHACHA20_POLY1305_SHA256), which is not in the NIAP allowlist` | Configure server to select an approved suite from `NiapTlsPolicy.APPROVED_SUITES`. | +| TLS 1.2 server omitted Extended Master Secret | `javax.net.ssl.SSLHandshakeException: TLS ServerHello (0x303) omitted mandatory extended_master_secret (EMS) extension` | Enable RFC 7627 Extended Master Secret on the TLS 1.2 server (or negotiate TLS 1.3 on API 37+). | +| Server did not staple an OCSP response | `Revocation status unavailable: server did not staple an OCSP response (OCSP stapling is required)` | Enable OCSP stapling (RFC 6066) on the server using a CA that supports OCSP. | +| Stapled OCSP response reports revoked certificate | `Stapled OCSP verification failed (REVOKED): ...` | Expected rejection for revoked certificates; replace the server certificate. | +| Stapled OCSP response expired, corrupt, or untrusted signer | `Stapled OCSP verification failed (UNDETERMINED_REVOCATION_STATUS): ...` or `Malformed DER in stapled OCSP response: ...` | Refresh the server's OCSP staple and verify responder certificate chain/delegation. | +| OCSP response signed with SHA-256 or weak algorithm | `OCSP response signature algorithm OID 1.2.840.10045.4.3.2 is not permitted by FIA_X509_EXT.1.1 (allowed: [1.2.840.10045.4.3.3, 1.2.840.10045.4.3.4, 1.2.840.113549.1.1.12, 1.2.840.113549.1.1.13])` | Reconfigure OCSP responder to sign responses with SHA-384 or SHA-512. | +| OCSP responder key too weak | `OCSP signer EC key field size 256 bits is not permitted by FIA_X509_EXT.1.1 (must be P-384 or P-521)` or `OCSP signer RSA key size 2048 bits is less than minimum 3072 bits required by FIA_X509_EXT.1.1` | Provision an OCSP responder key using EC P-384/P-521 or RSA โ‰ฅ 3072 bits. | +| Unapproved cipher suite in `niap_security_config.xml` | `IllegalArgumentException: Cipher suite '' is not in the NIAP-approved allowlist. Approved suites: ...` | Remove non-approved suites from ``. | +| Server requires mTLS but client supplied no certificate | `javax.net.ssl.SSLProtocolException: ... TLSV1_ALERT_CERTIFICATE_REQUIRED` | Supply an `X509KeyManager` to `NiapCertHelper` or use `NiapCertManager.getSslSocketFactory(...)`. | + +--- + +## 7. Verification with `validator-test-app` and `tools/tls-lab-repro` + +Evaluators and developers can verify all TLS, OCSP stapling, mutual TLS, and session resumption requirements on a physical Android device using the packaged `validator-test-app-strict-debug.apk` and the host-side OpenSSL harness in `tools/tls-lab-repro/`. + +### 7.1 Prerequisites & Setup +1. Install `validator-test-app-strict-debug.apk` on the Android device and verify its SHA-256 against `SHA256SUMS` (the app also displays and logs its `versionName`, build time, and git SHA at launch). +2. Forward device port `9443` to the host over USB: + ```bash + adb reverse tcp:9443 tcp:9443 + ``` +3. Generate the NIAP-compliant P-384 / `ecdsa-with-SHA384` test PKI, OCSP staples (`good`, `revoked`, `badsigner`, `corrupt`, `good-sha256`), and client PKCS#12 keystore: + ```bash + ./tools/tls-lab-repro/gen_pki.sh + ``` + +### 7.2 Full Automated Matrix +Run all test cases across both `HttpsURLConnection` (`http`) and `OkHttp` (`okhttp3`): +```bash +./tools/tls-lab-repro/run_matrix.sh +``` +The harness queries `adb shell getprop ro.build.version.sdk` on the connected device and automatically selects the matching expected profile: +* **API โ‰ค 36**: `tools/tls-lab-repro/expected_fixed_api36.tsv` (TLS-1.2-only profile; `baseline-good-staple` negotiates TLS 1.2, `tls13-chacha-only` and `tls13-aes128-only` fail with `protocol_version`, `resumption-repeat` resumes TLS 1.2). +* **API 37+**: `tools/tls-lab-repro/expected_fixed.tsv` (TLS 1.2 + TLS 1.3 profile). + +Override the profile explicitly with `EXPECTED=api36`, `EXPECTED=api37`, or `EXPECTED=/path/to/table.tsv` (`EXPECTED_FILE=` is also accepted). The harness records the detected device API level and expected profile used in `tools/tls-lab-repro/out/matrix_report.md`, along with full OpenSSL `-trace` logs and PID-scoped device `logcat` captures under `tools/tls-lab-repro/out/logs/`. + +**Test-Only Wire-Capture Override (`force_tls12_wire`):** For cross-version verification (exercising the API โ‰ค 36 TLS 1.2 wire-capture OCSP path on an API 37+ device), `cert-lib` provides `NiapTlsPolicy.setForceTls12WireCaptureForTesting(context, enabled)` (exposed via the `force_tls12_wire` intent extra in `validator-test-app`). This hook is strictly test-only: it is honoured only when `ApplicationInfo.FLAG_DEBUGGABLE` is set, throws `IllegalStateException` in non-debuggable/release builds, and is **not** part of the evaluated configuration. + +### 7.3 Manual Single-Case & Direct `adb` Testing +To exercise individual scenarios directly via `validator-test-app`: + +```bash +CA_B64="$(tr -d '\r\n' < tools/tls-lab-repro/out/pki/ca.b64)" +CLIENT_P12_B64="$(tr -d '\r\n' < tools/tls-lab-repro/out/pki/client.p12.b64)" + +# Single case via harness (example: reject TLS 1.3 ChaCha20) +./tools/tls-lab-repro/run_case.sh tls13-chacha-only http -- \ + -tls1_3 -ciphersuites TLS_CHACHA20_POLY1305_SHA256 \ + -status_file tools/tls-lab-repro/out/pki/good.der + +# Session resumption via harness (2 sequential requests in one app process) +REPEAT=2 ./tools/tls-lab-repro/run_resumption.sh resumption-tls13 http -- \ + -status_file tools/tls-lab-repro/out/pki/good.der + +# Direct adb launch with mTLS client certificate and repeat=2 +adb shell am start -S -W -n com.example.niap.cert.ext.testapp/.MainActivity \ + -e openurl "https://localhost:9443/" \ + -e type okhttp3 \ + -e ca_b64 "$CA_B64" \ + -e client_p12_b64 "$CLIENT_P12_B64" \ + -e client_p12_pass changeit \ + -e repeat 2 +``` + +For full harness options and lab reuse instructions, see [tools/tls-lab-repro/README.md](../tools/tls-lab-repro/README.md). diff --git a/niap-cc/niap-android-cert-ext/docs/FIA_XCU_EXT.1.md b/niap-cc/niap-android-cert-ext/docs/FIA_XCU_EXT.1.md new file mode 100644 index 0000000..1aa1606 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/docs/FIA_XCU_EXT.1.md @@ -0,0 +1,204 @@ +## Identification and Authentication (FIA) + +### FIA\_XCU\_EXT.1 Implementation of X.509 Functions + +FIA\_XCU\_EXT.1.1 +The TSF shall \[**selection**: *verify, assert*\] identities included in X.509 certificates. + +### FIA\_X509\_EXT.1 X.509 Certificate Validation + +FIA\_X509\_EXT.1.1 +The TSF shall \[**selection**: *invoke platform-provided functionality, implement functionality*\] to validate certificates in accordance with the following rules: + +* Certification path validation meets requirements of RFC 5280 for certificate paths of \[**selection**: *unlimited path length, maximum path length of \[**assignment**: 102\] certificates*\] and certificate paths exceeding the maximum path length are invalid. +* The current time is within the notBefore and notAfter values of all certificates in the certification path. +* The certification path shall terminate at a trust anchor element appropriate for the supported function. +* Certificates containing subjectUniqueID or issuerUniqueID fields are considered invalid. +* Certificates are signed using cryptographic signatures and hashes in accordance with RFC 8603, and \[**selection**: + * *\[**assignment**: list of supported cryptographic algorithms\]* + * *no other algorithms* + + \] and certificates signed using other cryptographic algorithms are considered invalid. + +* \[**selection**: + * *CRLs are signed using cryptographic signatures and hashes in accordance with RFC 8603 and \[**selection**:* + * *\[**assignment**: list of supported cryptographic algorithms\]* + * *no other algorithms* + + *\] and CRLs signed using other cryptographic algorithms are considered invalid;* + + * *OCSP responses are signed using \[**selection**:* + * *sha384WithRSAEncryption with key size of 3072 bits or greater,* + * *ecdsa-with-SHA384 using \[**selection**: secp384r1, secp521r1\],* + * *ecdsa-with-SHA512 using \[**selection**: secp384r1, secp521r1\],* + + *\] and \[**selection**:* + + * *\[**assignment**: list of other supported algorithms\]* + * *no other algorithms* + + *\] requested using the preferredSignatureAlgorithm extension and OCSP responses are considered invalid if using other algorithms;* + + * *No other algorithm constraints* + + \]. + + +FIA\_X509\_EXT.1.2 +The TSF shall \[**selection**: *invoke platform-provided functionality, implement*\] processing of the extensions indicated in RFC 5280, section 4.2, + +* Authority Key Identifier, +* Subject Key Identifier +* keyUsage +* and \[**selection**: + * *basicConstraints* + * *authorityInformationAccess* + * *cRLDistributionPoints* + * *certificatePolicies* + * *policyMapping* + * *Subject alternate name containing any of the following name types \[**selection**:* + * *rfc822Name* + * *dNSName* + * *directoryName* + * *uniformResourceIdentifier* + * *iPAddress* + * *\[**assignment**: other name types\]* + + *\]* + + * *extendedKeyUsage* + * *nameConstraints* + * *\[**assignment**: other extensions\]* + * *no other extensions* + + \]. + + +FIA\_X509\_EXT.1.3 +The TSF shall \[**selection**: *invoke platform-provided functionality, implement functionality*\] to validate revocation status of the certificate using \[**selection**: + +* *The Online Certificate Status Protocol (OCSP) as specified in RFC 6960* +* *Certificate Revocation Lists (CRL) as specified in RFC 5280 and refined by RFC 8603* +* *Certificate Revocation Lists as specified in RFC 5280* +* *Based on validity period: Certificates expiring within \[**assignment**: time less than 24 hours\] of the current time are considered valid when no other valid revocation status information is available* +* *Administrative notification of revocation: \[**assignment**: administrative action upon notification\] using \[**assignment**: method to invalidate use of certificates in supported functions\] when the certificate is revoked.* +* *Direct association with Certification Authority: \[**assignment**: direct revocation status information implementations\]* + +\]. + +FIA\_X509\_EXT.1.4 +The TSF shall \[**selection**: + +* *not obtain revocation status information by the TSF due to \[**selection**: determining that the certificate expires within \[**assignment**: time less than 24 hours\], determining that the \[assignment: supported function\] validates revocation status using \[**assignment**: methods supported by the function\]\]* +* *\[**selection**: invoke platform-provided functionality, implement functionality\] to obtain supported revocation status information via \[**selection**:* +* *Network connection to \[**selection**: CA, CRL distribution point, OCSP responder, \[**assignment**: alternate sources \]\]* +* *Local revocation status information from \[**selection**: cached CRL, embedded CA repository, local OCSP responder, administrator configuration\]* +* *An OCSP TLS Status Request Extension (OCSP stapling) as specified in RFC 6066,* +* *An OCSP TLS Multiple Certificate Status Request Extension (OCSP multi-stapling) as specified in RFC 6961* + *\]* + +\]. + +FIA\_X509\_EXT.1.5 +The TSF shall \[**selection**: *invoke platform-provided functionality, implement functionality, pass context information to the supported function*\] to validate that the context of the certificate path and trust store element is consistent with the supported function use via \[**selection**: + +* *processing \[**selection**:* + * *\[**assignment**: trust store context rules\]* + * *extendedKeyUsage field constraints in the leaf certificate including: \[**selection**:* + * *\[**assignment**: trust store context rules\],* + * *extendedKeyUsage (EKU) field constraints in the leaf certificate including: \[**selection**:* + * *Certificates used for trusted updates and executable code integrity verification shall have the Code Signing Purpose (id-kp 3 with OID 1.3.6.1.5.5.7.3.3),* + * *Client certificates presented for TLS shall have the Client Authentication purpose (id-kp 2 with OID 1.3.6.1.5.5.7.3.2),* + * *Server certificates presented for TLS shall have the Server Authentication purpose (id-kp 1 with OID 1.3.6.1.5.5.7.3.1),* + * *Delegated OCSP signerโ€™s certificates presented for OCSP responses shall have the OCSP Signing purpose (id-kp 9 with OID 1.3.6.1.5.5.7.3.9),* + * *Server certificates presented for EST shall have the CMC Registration Authority (RA) purpose (id-kp-cmcRA with OID 1.3.6.1.5.5.7.3.28),* + * *Certificates representing a Registration Authority have the CMC Registration Authority Purpose (id-kp-cmcRA with OID 1.3.6.1.5.5.7.3.28),* + * *Certificates representing a Registration Authority have the v3 CMP Registration Authority Purpose (id-kp-cmcRA with OID 1.3.6.1.5.5.7.3.28)* + * *SMIME certificates presented to protect email have the email protection purpose (id-kp-emailProtection with OID 1.3.6.1.5.5.7.3.4),* + * *IPsec and IKE certificates used in conjunction with other functions requiring an explicit EKU also have the IPsec-IKE purpose (id-kp-ipsecIKE with OID 1.3.6.1.5.5.7.3.17) in accordance with RFC 4945, section 5.1.3.12,* + * *\[**assignment**: other EKU values required by supported functions\]* + + *\]* + + *\] and rejects the certificate if the context requirements are not met,* + + *\]* + +* *passing \[**selection**: certification path, \[**assignment**: context from certification path processing\] passed to the supported function\]* + +\]. + +FIA\_X509\_EXT.1.6 +The TSF shall \[**selection**: *manage trust stores, use platform-managed trust stores*\] used for certification path validation. + +### FIA\_X509\_EXT.2 X.509 Certificate Support for Functions + +FIA\_X509\_EXT.2.1 +The TSF shall \[**selection**: *invoke platform-provided functionality to validate, validate*\] X.509v3 certificates in accordance with FIA\_X509\_EXT.1 to support \[**assignment**: *supported functions*\] using \[**selection**: + +* *\[**selection**: TLS, DTLS, IPsec or IKE , SMIME, SSH, \[**assignment**: other authenticated communications protocol\]\]* +* *\[**selection**: code signing for system software updates, code signing for software integrity testing, integrity verification for TSF protected data, administrator authentication, user authentication , \[**assignment**: other uses\]\]* + +\]. + +FIA\_X509\_EXT.2.2 +For each function indicated in FIA\_X509\_EXT.2.1, the TSF shall \[**selection**: *invoke the TOE platform to determine, determine*\] whether the \[**selection**: *administrator is allowed to configure certificate acceptance, supported function determines acceptance via \[**assignment**: method of determining acceptance\], certificate is accepted, certificate is not accepted*\] when valid certificate revocation status information cannot be obtained from a source indicated in FIA\_X509\_EXT.1.3. + +### FIA\_X509\_EXT.3 X.509 Certificate Requests + +FIA\_X509\_EXT.3.1 +The TSF shall \[**selection**: *invoke the TOE platform to generate, generate*\] Certificate Requests as specified by \[**selection**: + +* *RFC 2986 (PKCS-10)* +* *RFC 7030 as updated by RFC 8996 (EST)* +* *RFC 5272 as updated by RFC 6402 (CMC)* +* *RFC 5272 as updated by RFC 8756 (CNSA CMC)* +* *RFC 4210 as updated by RFC 6712 and RFC 9481 (v2 CMP)* +* *RFC 4210 as updated by RFC 6712 and RFC 9480 (v3 CMP)* + +\] and be able to provide the following information in the request: public key, \[**selection**: + +* *Subject DN consisting of values for \[**selection**:* + * *U* + * *O* + * *OU* + * *CN* + * *\[**assignment**: other subject attributes\]* + + *\]* + +* *one or more of the following SAN types \[**selection**:* + * *rfc822Name* + * *dNSName* + * *directoryName* + * *uniformResourceIdentifier* + * *iPAddress* + * *\[**assignment**: other SAN types\]* + + *\]* + +\] and \[**selection**: + +* *\[**assignment**: list of other certificate field and extension values\]* +* *\[**assignment**: list of identifying information\]* +* *no other information.* + +\]. + +FIA\_X509\_EXT.3.2 +The TSF shall \[**selection**: *invoke platform-provided functionality, provide functionality*\] to validate the certificate path in accordance with FIA\_X509\_EXT.1 upon receiving the CA Certificate Response, and validate that the certificate path of the response is consistent with the intended usage. + +### FIA\_XCU\_EXT.2 X.509 Certificate Acquisition + +FIA\_XCU\_EXT.2.1 +The TSF shall \[**selection**: + +* *request certificates from an \[**selection**: external, embedded \] CA,* +* *obtain certificates from an embedded CA* + +\] to represent \[**assignment**: *TOE functions*\] for \[**selection**: + +* *\[**selection**: TLS, DTLS, IPsec or IKE , SMIME, SSH, \[**assignment**: other authenticated communications protocol\]\]* +* *\[**selection**: code signing for system software updates, code signing for software integrity testing, integrity verification for TSF protected data, administrator authentication, user authentication, \[**assignment**: other uses\]\]* + +\]. diff --git a/niap-cc/niap-android-cert-ext/docs/RELEASE-NOTES.md b/niap-cc/niap-android-cert-ext/docs/RELEASE-NOTES.md new file mode 100644 index 0000000..9d2b9c1 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/docs/RELEASE-NOTES.md @@ -0,0 +1,122 @@ +# Release Notes โ€” NIAP Android TLS/X.509 Library (`cert-lib`) Resubmission + +**Baseline compared against:** `2026-11-19` submission (`submission/2026-11-19`, commit `3ee0ecc`) +**Target track:** App-level library (`cert-lib`, `validator-test-app`, `cert-manager`, `cert-test-app`) +**Audience:** NIAP evaluation laboratory and internal security reviewer + +--- + +## 1. Summary + +This resubmission resolves all five TLS and X.509 findings reported by the evaluation laboratory against the `2026-11-19` package (`validator-test-app` v1.0 / `cert-lib`): + +1. Unapproved TLS 1.3 cipher suite (`TLS_CHACHA20_POLY1305_SHA256`) can no longer be negotiated. +2. Stapled OCSP responses are now unconditionally parsed and verified for revocation status, responder authorization, signature validity, and `FIA_X509_EXT.1.1` cryptographic constraints (SHA-384/SHA-512; EC P-384/P-521 or RSA โ‰ฅ 3072). +3. Missing stapled OCSP responses are hard-rejected (fail-closed, no override). +4. Mutual TLS (client-certificate authentication) is supported in `NiapCertHelper` and `validator-test-app`. +5. TLS session resumption is enabled via cached `SSLContext` reuse and testable in `validator-test-app`. + +All app-level code uses **public Android SDK APIs only** (zero non-SDK / hidden platform API dependencies) and has been verified on stock-policy Android 17 (API 37) and Android 16 (API 36) devices with `26/26` matrix pass and `0` hidden-API denials on both. + +--- + +## 2. Lab Findings, Fixes, and Verification Evidence + +| Lab Finding (`2026-11-19`) | Root Cause & Fix | Verification Evidence (`http` & `okhttp3`) | +|---|---|---| +| **1. TLS 1.3 ChaCha20 advertised and negotiable** (`tls13-chacha-only` returned HTTP 200) | Added `NiapTlsPolicy` (single source of truth for allowed cipher suites and protocols). On **API 37+**, `VerifiableSSLSocketFactory` (`EmsVerifyingInputStream`) inspects the server's `ServerHello` on the wire and aborts with a fatal `handshake_failure` alert (40) and `SSLHandshakeException` if the server selects any non-allowlisted suite (e.g. `0x1303`). On **API โ‰ค 36**, TLS 1.3 is not offered at all (TLS 1.2 only; only the 4 allowlisted TLS 1.2 suites appear in `ClientHello`). | **API 37**: `tls13-chacha-only` rejected at `ServerHello` (`Server selected cipher suite 0x1303 (TLS_CHACHA20_POLY1305_SHA256), which is not in the NIAP allowlist`); `tls13-aes128-only` โ†’ HTTP 200; `tls12-chacha-only` โ†’ `no shared cipher`.
**API 36**: `tls13-chacha-only` & `tls13-aes128-only` rejected (`TLSV1_ALERT_PROTOCOL_VERSION`); `ClientHello` advertises only 4 TLS 1.2 suites; `tls12-chacha-only` โ†’ `no shared cipher`; `tls12-approved` โ†’ HTTP 200. | +| **2. Stapled OCSP not checked (revoked, unauthorized signer, corrupt, and SHA-256 staples accepted)** | Converted `NiapX509TrustManager` and `CombinedTrustManager` to session-aware `X509ExtendedTrustManager` so the platform `TrustManagerImpl` receives the `SSLSocket`/`SSLEngine` session. Added `OcspStapleValidator` to enforce offline-only (`ONLY_END_ENTITY`, `NO_FALLBACK`) revocation checks and `FIA_X509_EXT.1.1` OCSP signature algorithm (SHA-384/SHA-512) and signer key (P-384/P-521 or RSA โ‰ฅ 3072) rules. | **API 37 & API 36**: `baseline-good-staple` โ†’ HTTP 200; `staple-revoked` โ†’ `CertificateRevokedException`; `staple-badsigner` โ†’ `Responder's certificate is not authorized to sign OCSP responses`; `staple-corrupt` โ†’ `Error verifying OCSP Response's signature`; `staple-sha256` โ†’ `OCSP response signature algorithm OID 1.2.840.10045.4.3.2 is not permitted by FIA_X509_EXT.1.1`. | +| **3. Missing OCSP staple accepted** (`no-staple` returned HTTP 200) | `NiapX509TrustManager.verifyStapledOcsp()` unconditionally fails closed if no stapled OCSP response is present for the handshake (no developer override, no CRL/online-OCSP fallback). | **API 37 & API 36**: `no-staple` โ†’ `SSLHandshakeException: Revocation status unavailable: server did not staple an OCSP response (OCSP stapling is required)`. | +| **4. Mutual authentication (mTLS) not testable** | Added `X509KeyManager` overloads to `NiapCertHelper` (`openConnection`, `createSSLSocketFactory`, `configureOkHttp`), routed `NiapCertManager.getSslSocketFactory(...)` and `verifyMtls(...)` through `NiapCertHelper`, deprecated `NiapCertManager.getSslContext(...)`, and added `client_p12_b64` / `client_p12_pass` intent extras to `validator-test-app`. | **API 37 & API 36**: `mtls-required-with-cert` โ†’ HTTP 200 (server trace confirms `depth=1 CN=NIAP Lab Repro Client CA`, `depth=0 CN=niap-test-client`); `mtls-required-no-cert` โ†’ rejected (`TLSV1_ALERT_CERTIFICATE_REQUIRED` on TLS 1.3 / `SSLV3_ALERT_HANDSHAKE_FAILURE` on TLS 1.2). | +| **5. Session resumption not testable** (`Reused=0` across requests) | `NiapCertHelper` now caches `SSLContext`, `NiapX509TrustManager`, and `VerifiableSSLSocketFactory` per `(TrustAnchorOptions, SHA-256(anchors), keyManager identity, requireEms)`. `validator-test-app` preserves the singleton across sequential requests and adds the `repeat` extra (closing each TCP connection via `Connection: close` + `disconnect()` / `connectionPool.evictAll()` to force fresh TLS handshakes against the shared session cache). | **API 37**: `resumption-repeat` โ†’ `RESUMED` (TLS 1.3 `psk(41)`), `resumption-tls12` โ†’ `RESUMED` (TLS 1.2 ticket), `resumption-tls12-noticket` โ†’ `RESUMED` (TLS 1.2 session ID).
**API 36**: all three resumption modes โ†’ `RESUMED` over TLS 1.2 (tickets and session IDs, app `resumed=true`). | + +--- + +## 3. Platform-Version-Dependent Behavior (API โ‰ค 36 vs. API 37+) + +Stock-policy Android 16 (API 36) devices do not expose `javax.net.ssl.ExtendedSSLSession.getStatusResponses()` at runtime, and reflecting on Conscrypt's internal session class is denied by hidden-API enforcement. Because TLS 1.3 encrypts the server `Certificate` and `status_request` extensions, an app-level library cannot read TLS 1.3 OCSP staples without public platform API support. In TLS 1.2, however, the server's `CertificateStatus` message is sent in plaintext before `ChangeCipherSpec`. + +`cert-lib` probes `ExtendedSSLSession.getStatusResponses()` once at runtime (`NiapTlsPolicy.isPublicStapleApiAvailable`) and adapts automatically: + +| Behavior | Android 16 and below (API โ‰ค 36) | Android 17 and above (API 37+) | +|---|---|---| +| **Protocols offered** | **TLS 1.2 only**, regardless of ``. TLS 1.3 is omitted from `ClientHello`. | **TLS 1.2 + TLS 1.3** by default (`false`), or **TLS 1.2 only** if `true`. | +| **OCSP staple source** | Plaintext TLS 1.2 `CertificateStatus` handshake message captured on the wire (`Tls12HandshakeTap` + `WireOcspRegistry` for `SSLSocket`). | Public `javax.net.ssl.ExtendedSSLSession.getStatusResponses()` API. | +| **TLS 1.3-only servers** | **Unsupported** โ€” fails with `TLSV1_ALERT_PROTOCOL_VERSION`. | **Supported** (subject to NIAP cipher allowlist and valid OCSP staple). | +| **`SSLEngine` connections** | **Fail closed** (wire capture requires `SSLSocket`). | **Supported** via `ExtendedSSLSession.getStatusResponses()`. | +| **TLS 1.3 cipher advertisement** | No TLS 1.3 suites are advertised in `ClientHello`. | Platform Conscrypt always advertises all 3 TLS 1.3 suites (including ChaCha20) when TLS 1.3 is enabled; `VerifiableSSLSocketFactory` rejects any unapproved suite at `ServerHello` before handshake completion, so ChaCha20 is never negotiated. | + +> **Requirement for TLS 1.3 with mandatory OCSP stapling on API โ‰ค 36:** The **OS-integrated (platform) version** is required on Android 16 and below, because only platform code can access encrypted TLS 1.3 stapled OCSP responses inside the TLS stack. + +--- + +## 4. Other Changes Since `2026-11-19` + +* **Session-aware trust manager & fail-closed session-less path**: `NiapX509TrustManager` and `CombinedTrustManager` extend `X509ExtendedTrustManager`; the legacy 2-argument `checkServerTrusted(chain, authType)` fails closed because it lacks an `SSLSession` to verify OCSP stapling. +* **Extended Master Secret (EMS, RFC 7627)**: Enforced on all TLS 1.2 handshakes (`true`). Servers omitting extension `0x0017` are aborted with a fatal alert and `SSLHandshakeException`. +* **Cipher allowlist validation**: `NiapTlsPolicy.APPROVED_SUITES` (`0x1301`, `0x1302`, `0xC02B`, `0xC02F`, `0xC02C`, `0xC030`) is the AEAD subset of the NIST SP 800-52 Rev. 2 recommended cipher suites supported by the platform TLS stack (AES-CCM suites are also SP 800-52 Rev. 2-approved but are not offered by the platform TLS stack; ChaCha20-Poly1305 is not a FIPS-approved algorithm and is therefore refused). XML `` may only narrow this list further (e.g. AES-256-only if an evaluation requires it); any unknown or non-approved suite throws `IllegalArgumentException` at config load. +* **`SSLContext` caching & client certificates**: `NiapCertHelper` caches `SSLContext`/`TrustManager`/`SSLSocketFactory` tuples to preserve session caches and adds `X509KeyManager` overloads. `NiapCertManager.getSslContext(...)` is `@Deprecated`. +* **Hostname verification & `EstClient` fail-closed**: Removed permissive `hostnameVerifier { _, _ -> true }` bypasses from `EstClient` and `CertTestActivity`. `EstClient.acquireCertificate()` now fails closed on custom CA PEM parsing/configuration errors instead of falling back to system CAs. +* **Key-type validation restored**: `NiapCertValidator` explicitly rejects unsupported public key types (anything other than EC or RSA) rather than silently allowing them. +* **Hidden-API guards**: Added static scanner `tools/check-no-hidden-api.sh`, configured Android Lint (`PrivateApi`, `DiscouragedPrivateApi`, `SoonBlockedPrivateApi`, `BlockedPrivateApi`) as fatal errors across app-level modules, and added PID-scoped `hiddenapi` logcat auditing to `tools/tls-lab-repro`. +* **Build & packaging improvements**: Dynamic `testbedRoot` resolution in `settings.gradle.kts`, `-PskipTestbedCopy=true` opt-out to avoid writing outside the repository, and `tools/package-submission.sh` (runs hidden-API checks, Lint, unit tests, builds AAR/APKs, and emits `MANIFEST.txt` + `SHA256SUMS`). +* **`validator-test-app` testability & build identity**: + * Added `client_p12_b64`, `client_p12_pass`, `repeat`, and debuggable-only `force_tls12_wire` intent extras. + * Added `versionName = "1.1.0"` (`versionCode = 2`), `BuildConfig.BUILD_TIME`, and `BuildConfig.GIT_SHA`, logged (`I/TestApp : Build: ...`) and displayed on launch. +* **Documentation**: Updated `README.md`, added evaluated-configuration guidance in `docs/AGD-TLS-guidance.md`, and added the reusable host harness in `tools/tls-lab-repro/`. + +--- + +## 5. Verification Summary + +All device tests were run under **stock hidden-API policy** (`hidden_api_policy = null`, `hidden_api_policy_pre_p_apps = null`, `hidden_api_policy_p_apps = null`) against OpenSSL 4.1.0 via `adb reverse tcp:9443 tcp:9443`, testing both `HttpsURLConnection` (`http`) and `OkHttp` (`okhttp3`). + +| Target / Check | Environment / Build | Result | +|---|---|---| +| **Android 17 (API 37) device matrix** | Pixel 8 (`shiba`), `google/shiba/shiba:17/CP4A.261205.008.B2/16937301:userdebug/dev-keys`, auto-selected `api37+` profile (TLS 1.2 + 1.3, public `ExtendedSSLSession` API) | **26 / 26 PASS**; **6 / 6 resumption PASS** (TLS 1.3 PSK, TLS 1.2 ticket, TLS 1.2 SID); **0** hidden-API denials / **0** `niap` warnings | +| **Android 17 (API 37) forced TLS 1.2 wire-capture** | Same Pixel 8 (`shiba`) with debuggable-only `force_tls12_wire=true` (`api36` profile) + default-mode sanity check | **26 / 26 PASS** (+ 2 / 2 default TLS 1.3 sanity PASS); **6 / 6 resumption PASS**; **0** hidden-API denials / **0** `niap` warnings | +| **Android 16 (API 36) device matrix** | Pixel (`stallion`), `google/stallion/stallion:Baklava/BP2A.250805.062/eng.wkouki:userdebug/dev-keys`, auto-selected `api36` profile (automatic TLS 1.2 pinning + `CertificateStatus` wire capture, no test flags) | **26 / 26 PASS**; **6 / 6 resumption PASS** (TLS 1.2 ticket & SID); **0** hidden-API denials / **0** `niap` warnings | +| **Automated static & unit checks** | `tools/check-no-hidden-api.sh`, Android Lint (`PrivateApi` checks), `:cert-lib:testDebugUnitTest` | **PASS** (0 hidden-API violations, 0 lint errors, all JVM unit tests pass) | + +--- + +## 6. Known Limitations + +1. **Mandatory OCSP stapling**: Stapled OCSP is hard-enforced with no override and no CRL/online-OCSP fallback. Endpoints whose CA does not operate an OCSP responder (e.g., Let's Encrypt) or servers that do not staple a valid SHA-384/SHA-512 OCSP response cannot be used. +2. **Resumed sessions**: On resumed TLS handshakes, the platform TLS stack does not re-invoke `checkServerTrusted`; certificate chain and stapled OCSP checks run on full handshakes only. +3. **API โ‰ค 36 scope**: TLS 1.3-only servers and `SSLEngine`-based connections are unsupported on API โ‰ค 36 (fail closed). TLS 1.3 with mandatory OCSP stapling on API โ‰ค 36 requires the OS-integrated platform version. + +--- + +## 7. How to Test + +### 7.1 `validator-test-app` Intent Extras (`com.example.niap.cert.ext.testapp/.MainActivity`) + +| Extra | Type / Values | Default | Purpose | +|---|---|---|---| +| `openurl` | `String` | `https://www.google.com` | Target HTTPS URL | +| `type` | `http` \| `okhttp3` | `http` | Client stack (`HttpsURLConnection` vs `OkHttpClient`) | +| `ca_b64` | `String` (base64) | *(none)* | Custom trust anchor (DER or PEM) | +| `client_p12_b64` | `String` (base64) | *(none)* | PKCS#12 client certificate + key for mTLS | +| `client_p12_pass` | `String` | `changeit` | Password for `client_p12_b64` | +| `repeat` | `Int` / `String` | `1` | Sequential fresh-connection requests sharing one session cache | +| `force_tls12_wire` | `Boolean` | `false` | **Debuggable test-only hook** (not part of evaluated configuration; throws `IllegalStateException` in release builds) to force the API โ‰ค 36 TLS 1.2 wire-capture OCSP path on API 37+ | + +### 7.2 Automated Harness (`tools/tls-lab-repro`) + +```bash +# 1. Install validator-test-app-strict-debug.apk and forward port 9443 +adb install -r validator-test-app-strict-debug.apk +adb reverse tcp:9443 tcp:9443 + +# 2. Generate P-384 / ecdsa-with-SHA384 test PKI, OCSP staples, and client PKCS#12 +./tools/tls-lab-repro/gen_pki.sh + +# 3. Run the full 26-case matrix (auto-selects expected_fixed.tsv on API 37+ or expected_fixed_api36.tsv on API <= 36) +./tools/tls-lab-repro/run_matrix.sh + +# Optional: exercise the API <= 36 TLS 1.2 wire-capture path on an API 37+ device (debuggable build only) +EXTRA_EXTRAS="-e force_tls12_wire true" EXPECTED=api36 ./tools/tls-lab-repro/run_matrix.sh +``` + +See [tools/tls-lab-repro/README.md](../tools/tls-lab-repro/README.md) and [docs/AGD-TLS-guidance.md](AGD-TLS-guidance.md) for single-case (`run_case.sh`), resumption (`run_resumption.sh`), and direct `adb shell am start` examples. diff --git a/niap-cc/niap-android-cert-ext/docs/SUBMISSION.md b/niap-cc/niap-android-cert-ext/docs/SUBMISSION.md new file mode 100644 index 0000000..ee3eba6 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/docs/SUBMISSION.md @@ -0,0 +1,57 @@ +# Updating the submission copy in `security-certification-resources` + +This repository (`github.com/KVVat/niap-android-cert-ext`) is the **source of truth** for the app-level library track. +The copy under `security-certification-resources/niap-cc/niap-android-cert-ext` is generated from it. Do not edit that copy by hand; regenerate it with the steps below. + +## Reference to use + +| Item | Value | +|---|---| +| Branch | `fix/tls-lab-findings` | +| Release tag | `resubmission-2026-12-04` (also recorded as `Git Commit` in `MANIFEST.txt`) | +| Previous submission (2026-11-19) | branch `submission/2026-11-19` (exact snapshot of the earlier package) | + +## 1. Build the package (in this repository) + +```bash +git checkout resubmission-2026-12-04 # or the branch head for a newer drop +./tools/package-submission.sh dist/ +``` + +- The script requires a clean git tree. It runs the hidden-API static check, Android Lint and the cert-lib unit tests, then builds everything with `-PskipTestbedCopy=true`. +- Output (in `dist//`): + - `niap-android-cert-ext.zip`: the app-level source tree (this is what goes into `niap-cc/`) + - `niap-cert-lib-release.zip`: library sources, tests and the release AAR + - `cert-lib-release.aar`, `validator-test-app-strict-debug.apk`, `validator-test-app-relaxed-debug.apk`, `cert-manager-debug.apk`, `cert-test-app-debug.apk` + - `SHA256SUMS` and `MANIFEST.txt` (commit, branch, tool versions, file list) +- **Do not run the script inside `security-certification-resources`.** There the folder is not part of this git repository, so the clean-tree check and the `git ls-files`-based file selection do not work. + +## 2. Update `niap-cc/niap-android-cert-ext` + +```bash +SCR=~/AndroidStudioProjects/security-certification-resources +PKG=/dist/ + +rm -rf "$SCR/niap-cc/niap-android-cert-ext" # the previous drop is preserved in branch submission/2026-11-19 +unzip -q "$PKG/niap-android-cert-ext.zip" -d "$SCR/niap-cc/" # creates niap-cc/niap-android-cert-ext/ +mkdir -p "$SCR/niap-cc/niap-android-cert-ext/build/distributions" +cp "$PKG"/*.zip "$PKG/SHA256SUMS" "$PKG/MANIFEST.txt" "$SCR/niap-cc/niap-android-cert-ext/build/distributions/" +``` + +Hand the APKs and the AAR from `$PKG` to the evaluation lab as separate deliverables. The `build/` folder is only a local artifact location, and the copied `.gitignore` excludes it from git. + +## 3. Verify the copy builds in place + +```bash +cd "$SCR/niap-cc/niap-android-cert-ext" +./gradlew --console=plain -PskipTestbedCopy=true \ + :cert-lib:testDebugUnitTest :cert-lib:assembleRelease :validator-test-app:assembleStrictDebug +``` + +`settings.gradle.kts` finds `testbed-core` and `testbedui-plugins` automatically: it checks one level up (standalone checkout) and then three levels up (this layout). You can also pass `-PtestbedRoot=`. Always pass `-PskipTestbedCopy=true` so that no APKs are copied into the test runner's resources. + +## 4. Commit in `security-certification-resources` + +- Commit only the source tree, i.e. what `niap-android-cert-ext.zip` contains. Do not commit `build/`, `dist/` or generated outputs. +- In the commit / pull request message, record the source tag or commit and the `SHA256SUMS` of the delivered artifacts. +- The OS-level PoC (`poc_patch_for_26q2`, `cert-manager-system`, `cert-testapp-system`, `strict-browser-app`, `poc-design`) is intentionally not part of the submission copy. diff --git a/niap-cc/niap-android-cert-ext/docs/cetrt-manager.arch.md b/niap-cc/niap-android-cert-ext/docs/cetrt-manager.arch.md new file mode 100644 index 0000000..afc5e54 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/docs/cetrt-manager.arch.md @@ -0,0 +1,161 @@ +# cert-manager Architecture & Design + +## 1. Component Architecture (Client, IPC, Service) + +```mermaid +graph TD + subgraph Client Layer / App Process + APP[Client Application] + CM[CertManager
Client Interface / API] + end + + subgraph IPC Layer + AIDL[ICertManager.aidl
Binder IPC] + end + + subgraph Service Layer / FGS Process + FGS[CertManagerService
Foreground Service] + ORCH[CertOrchestrator
Workflow Controller] + end + + subgraph Service Core Engines + CSR[CsrEngine
PKCS#10 Generation] + EST[EstClient
Acquisition Engine] + VAL[CertValidator
NiapCertValidator Wrapper] + KS[KeyStoreEngine
Android KeyStore] + end + + APP -->|Calls API| CM + CM -->|Binds & Calls| AIDL + AIDL -->|Dispatches to| FGS + FGS -->|Delegates to| ORCH + ORCH -->|1. Generate CSR| CSR + ORCH -->|2. Acquire Cert| EST + ORCH -->|3. Validate Cert| VAL + ORCH -->|4. Store Cert| KS +``` + +## 2. Protocol-Agnostic Certificate Acquisition Flow + +```mermaid +graph TD + subgraph 1. Common CSR Generation + CSR[CsrEngine
Enforces P-384 / SHA-384 / SAN] + end + subgraph 2. Abstract Acquisition Layer + INT[IAcquisitionClient
Interface] + EST[EstClient] + CMC[CmcClient
Future] + CMP[CmpClient
Future] + INT --- EST + INT --- CMC + INT --- CMP + end + subgraph 3. Common Validation + VAL[CertValidator
Enforces FIA_X509_EXT.1 Rules] + end + CSR -->|PKCS#10| INT + INT -->|Cert Response| VAL +``` + +## 3. Operational Use Cases & Enrollment Workflows + +```mermaid +graph TD + subgraph 1. Zero-Touch / MDM Provisioning + MDM[MDM Config / Managed Configs] -->|Auto Trigger| FGS[CertManagerService] + FGS -->|Silent EST Enrollment| CA[CA Server] + end + + subgraph 2. Auto Rotation / Scheduled Job + WM[WorkManager Cron] -->|Check Expiry < 24h| FGS + end + + subgraph 3. User Interactive Enrollment + UI[Settings UI Activity] -->|User enters PIN/Token| FGS + end + + subgraph Target Consumers of Acquired Certificates + KS[Android KeyStore / KeyChain API] + FGS -->|Stores Verified Cert| KS + KS -->|mTLS Authentication| BROWSER[Chrome / Web Browsers] + KS -->|EAP-TLS Wi-Fi / VPN| NET[VPN Clients / Enterprise Wi-Fi] + KS -->|API Mutual Auth| APPS[Dedicated Enterprise Apps] + end +``` + +### Explanation of Certificate Consumers + +Acquired client certificates are stored in the **Android KeyStore** and made available system-wide via Android's `KeyChain API`. This means the certificates managed by `cert-manager` can be utilized across the entire Android device ecosystem: + +1. **Web Browsers (Chrome / Edge / Enterprise Browsers)**: When accessing high-security government or corporate intranet web portals requiring mTLS, Android prompts the user with a certificate selection dialog to authenticate using the acquired certificate. +2. **Network Security (VPN & EAP-TLS Wi-Fi)**: The stored certificates can be selected in VPN client configurations (e.g., Cisco AnyConnect) or 802.1X Wi-Fi settings for secure network onboarding. +3. **Dedicated Enterprise Applications**: Other enterprise apps (secure mailers, ERPs) can request access to the certificate via KeyChain for backend API mutual authentication. + +## 4. Security Functional Requirements (SFR) Selection & Traceability + +To satisfy NIAP Common Criteria (CC) and MDFPP requirements, `cert-manager` enforces strict architectural selections mapped directly to the official SFRs: + +```mermaid +graph TD + subgraph FIA_X509_EXT.3.1 Selection Mapping + GEN[Generate Mode
BouncyCastle Builder] --> FMT[Format
RFC 2986 PKCS#10 / RFC 7030 EST] + FMT --> DN[Subject DN
CN / O / OU / C] + FMT --> SAN[SAN Extensions
dNSName / iPAddress] + FMT --> OTHER[Other Info
no other information] + end +``` + +### FIA_X509_EXT.3.1 (Certificate Requests) +* **Generation Mode**: `[generate]` + * *Implementation*: The TOE module directly generates the PKCS#10 ASN.1 structure and DER encoding using Bouncy Castle (`JcaPKCS10CertificationRequestBuilder`), while leveraging Android KeyStore for secure asymmetric hardware key generation. +* **Request Protocol/Format**: `[RFC 2986 (PKCS-10), RFC 7030 (EST)]` + * *Implementation*: CSRs are strictly formatted as PKCS#10 requests and transmitted over EST `/simpleenroll` endpoints. (CMC and CMP are out of scope). +* **Subject DN Attributes**: `[O, OU, CN, and assignment: C]` + * *Implementation*: Parses and constructs organizational and common name attributes into the X.500 principal structure. + * *Note on 'U' Attribute*: In MDFPP requirements, `U` appears as a shorthand representation for `UID` (LDAP User ID: `0.9.2342.19200300.100.1.1`). Bouncy Castle's `BCStyle` natively supports `UID`. `cert-manager` supports `UID` mapping when provided in the subject DN string to fulfill this requirement seamlessly. +* **Subject Alternative Names (SAN)**: `[rfc822Name, dNSName, directoryName, uniformResourceIdentifier, iPAddress]` + * *Implementation*: Bouncy Castle's `GeneralName` core architecture natively supports all standard X.509 v3 SAN tags (Tag 0 through Tag 8). `cert-manager` is capable of constructing and encoding any of these required SAN types (`rfc822Name` for email, `dNSName` for domains, `directoryName` for DNs, `uniformResourceIdentifier` for URIs, and `iPAddress` for IP addresses) into the certificate request extension when provided in the enrollment configuration. +* **Other Information**: `[no other information]` + * *Implementation*: Minimizes attack surface by excluding unnecessary challenge passwords or non-standard attributes. + +### FIA_X509_EXT.3.2 (Certificate Path Validation) +* **Validation Mode**: `[provide functionality]` + * *Implementation*: Instead of relying solely on OS defaults, `CertValidator` wraps `NiapCertValidator` to actively enforce SHA-384/P-384 algorithm constraints, basic constraints (non-CA), and EKU rules upon receiving the certificate response. + +### FIA_XCU_EXT.2.1 (Certificate Acquisition) +* **Acquisition Source**: `[request certificates from an external CA]` + * *Implementation*: Communicates securely via OkHttp with external enterprise or government CAs (e.g., Cisco EST server) over TLS. +* **Target Protocol Selection**: `[TLS, IPsec or IKE]` + * *Implementation*: While the acquisition transport itself uses TLS (HTTPS), the acquired certificates are stored in Android KeyStore and exposed system-wide via `KeyChain API`. This architecture allows Android OS daemons (VPN clients, IPsec/IKEv2 services like StrongSwan, and Wi-Fi EAP-TLS supplicants) to authenticate network connections using the acquired certificates. + * *Server/Gateway Readiness*: Modern enterprise VPN gateways (e.g., Cisco ASA, StrongSwan) natively support EST/SCEP integration. Devices enroll via EST over TLS, then authenticate IPsec tunnels using the acquired hardware-backed certificates. + +```mermaid +sequenceDiagram + autonumber + participant Chrome as Android Chrome / Partner App
(TLS Client) + participant Mgr as Cert Manager Service
(EST Client) + participant Proxy as EST/CAS Proxy Server
(Basic Auth Protected) + participant CAS as Google Cloud CAS
(Private Sub-CA) + participant TestSrv as mTLS Test Endpoint
(Requires CA-signed Cert) + + Note over Mgr, Proxy: Phase 1: Certificate Acquisition (EST) + Mgr->>Mgr: 1. Generate P-384 Key in AndroidKeyStore + Mgr->>Mgr: 2. Construct & Sign PKCS#10 CSR (SHA384) + Mgr->>Proxy: 3. POST CSR over HTTPS (w/ Basic Auth) + Proxy->>Proxy: 4. Authenticate Basic Credentials + Proxy->>CAS: 5. Request signature via Google CAS API + CAS->>CAS: 6. Sign & Issue Certificate (SHA-384) + CAS-->>Proxy: 7. Return issued certificate + Proxy-->>Mgr: 8. Return Base64 PKCS#7 response + Mgr->>Mgr: 9. Validate signature & path constraints + Mgr->>Mgr: 10. Store certificate chain in Android KeyStore/KeyChain + + Note over Chrome, TestSrv: Phase 2: Real-World Verification (mTLS) + Chrome->>TestSrv: 11. Access secure page via HTTPS + TestSrv-->>Chrome: 12. Request Client Certificate (TLS Handshake) + Note over Chrome: 13. Android System Prompt:
"Select certificate for authentication" + Chrome->>Chrome: 14. User selects installed 'test_client_cert' + Chrome->>TestSrv: 15. Complete TLS client authentication (mTLS) + TestSrv-->>Chrome: 16. Return secure content (Success!) +``` \ No newline at end of file diff --git a/niap-cc/niap-android-cert-ext/docs/niap-cert-ext-design-note.md b/niap-cc/niap-android-cert-ext/docs/niap-cert-ext-design-note.md new file mode 100644 index 0000000..3d4367a --- /dev/null +++ b/niap-cc/niap-android-cert-ext/docs/niap-cert-ext-design-note.md @@ -0,0 +1,60 @@ +# NIAP Certificate Extension Library Design Note + +**Agent / Author**: Antigravity (Draft) + +**1. Introduction** + +* **1.1 Goal and Scope:** The primary goal of this project is to implement strict X.509 certificate validation and management functions required for NIAP compliance on Android. This library will act as an extension to the Android platform's native capabilities to satisfy specific `FIA_X509_EXT` and `FIA_XCU_EXT` requirements. +* **1.2 Audience:** Internal developers and evaluation authorities. +* **1.3 Definitions and Acronyms:** + * **TOE**: Target of Evaluation (The system/app running on the Android device being evaluated). + * **NIAP**: National Information Assurance Partnership. + * **CSR**: Certificate Signing Request. + * **EST**: Enrollment over Secure Transport (RFC 7030). + * **AKID/SKID**: Authority Key Identifier / Subject Key Identifier. + +**2. Background and Motivation** + +* **2.1 Problem Statement:** + * The standard Android security provider (Conscrypt) is lenient regarding some X.509 extensions and does not strictly enforce all validation rules required by NIAP (e.g., presence of specific extensions, Name Constraints). + * Additionally, NIAP requires the TOE to support CSR issuance and certificate acquisition, but native Android devices do not provide these functions by default. Therefore, these features must be added to the TOE. + * *(Japanese reference: ใพใŸใ€CSRใฎ็™บ่กŒใ‚„่จผๆ˜Žๆ›ธใฎๅ–ๅพ—ใŒNIAPใงใฏTOEใซ่ฆๆฑ‚ใ•ใ‚Œใ‚‹ใŒAndroidใƒ‡ใƒใ‚คใ‚นใฏใ“ใฎๆฉŸ่ƒฝใ‚’ๆŒใŸใชใ„ใŸใ‚่ฟฝๅŠ ใฎๅฟ…่ฆใŒใ‚ใ‚‹)* +* **2.2 Justification:** + * To achieve NIAP certification, we need to complement Conscrypt's behavior with a library that performs strict post-handshake checks. + * We need to provide standard-compliant mechanisms for certificate enrollment (CSR and EST) within the TOE. +* **2.3 Requirements:** + * **OS**: Android OS (Targeting TOE environment). + * **Standards**: RFC 8603 (CNSA) algorithm constraints, RFC 9580 (relevant if OpenPGP style headers are used, but primarily standard X.509/TLS focus here). + * Support for custom TrustAnchor and isolated TrustStore. +* **2.4 Schedule:** + * *TBD (To be defined after design finalization)* + +**3. High-Level Design and Architecture** + +* **3.1 System Context:** + * The library will be integrated into the TOE (Android application). It will be used in conjunction with HTTP clients like OkHttp or direct `SSLSocket` usage to enforce strict security policies. +* **3.2 Architectural Overview:** + * **Module 1: Validation Core (Android Archive - AAR)** + * **NiapCertValidator**: Core logic for strict X.509 checks. Specific restrictions to be enforced include: + * **Algorithm Constraints**: Restrict to RFC 8603 (CNSA) profiles (e.g., enforcing SHA-384 with ECDSA P-384). + * **Mandatory Extension Checks**: Verify presence of AKID (Authority Key Identifier), SKID (Subject Key Identifier), and KeyUsage. + * **Field Enforcement**: Strict checking of Basic Constraints, EKU (Extended Key Usage), and Name Constraints (which Conscrypt may ignore). + * **Revocation Checks**: Enforce OCSP Stapling and support fallback to Out-of-Band CRL fetching. + * **Network Security Features** (Carried over from NIAPSEC/SecureURL): + * Enforce HTTPS (blocking non-secure connections). + * Hostname and TLD validation. + * **Config Support**: Ability to read these strict validation rules and policies from an **XML file placed in resources** (e.g., `res/xml/niap_security_config.xml`). + * **Helpers / Integration**: Provide easy integration for: + * **OkHttp3**: Via `Interceptor` or custom `X509TrustManager`. + * **Ktor**: Via engine-specific TLS configuration using custom `TrustManager`. + * **java.net**: Via custom `SSLSocketFactory` applied to `HttpsURLConnection`. + * **Module 2: Certificate Management (Execution Module)** + * **CSR Generator**: Generates PKCS#10 CSRs using Bouncy Castle. + * **EST Client**: Handles certificate acquisition via EST. + * **Form Factor Options**: + * *Option A (Library)*: Included in the AAR, called directly by the app. + * *Option B (Service)*: An Android Service in a dedicated application (APK) to satisfy the "executable" requirement and allow IPC (Inter-Process Communication). +* **3.3 Key Design Decisions:** + * **Language**: Java / Kotlin for Android SDK. + * **Libraries**: Bouncy Castle (for CSR generation and advanced crypto operations not supported by default Android providers). + * **Integration**: Transport-agnostic validator to allow use in different layers (Socket, HTTP). diff --git a/niap-cc/niap-android-cert-ext/est-server/Dockerfile b/niap-cc/niap-android-cert-ext/est-server/Dockerfile new file mode 100644 index 0000000..66f8a21 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/est-server/Dockerfile @@ -0,0 +1,129 @@ +# ============================================================================= +# EST Validation Server โ€” Multi-stage Docker Build +# Based on Cisco libest (https://github.com/cisco/libest) +# Purpose: NIAP / Common Criteria Android certificate enrollment testing +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Stage 1: builder +# Compile libest from source on Ubuntu 22.04 +# ----------------------------------------------------------------------------- +FROM ubuntu:22.04 AS builder + +ENV DEBIAN_FRONTEND=noninteractive + +# Install build dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + git \ + build-essential \ + autoconf \ + automake \ + libtool \ + libssl-dev \ + pkg-config \ + ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +# Clone libest (pin branch/tag for reproducibility) +# To update: run `git ls-remote https://github.com/cisco/libest HEAD` +# and set LIBEST_REF to the new commit hash. +ARG LIBEST_REF=main + +WORKDIR /build +RUN git clone --depth 1 --branch ${LIBEST_REF} \ + https://github.com/cisco/libest.git libest \ + && cd libest \ + && git rev-parse HEAD | tee /LIBEST_COMMIT \ + && echo "Cloned libest at commit: $(cat /LIBEST_COMMIT)" + +# NIAP requirement: use SHA-384 for certificate signing (default is SHA-256) +# Compliance with FIA_X509_EXT and related PP requirements +RUN sed -i 's/^default_md[[:space:]]*=.*/default_md = sha384/' \ + /build/libest/example/server/estExampleCA.cnf \ + && echo "=== SHA setting verification ===" \ + && grep -n "default_md" /build/libest/example/server/estExampleCA.cnf + +# Build libest core library +WORKDIR /build/libest +# Two known issues fixed here: +# 1. configure.ac has duplicate AM_INIT_AUTOMAKE (fatal error on Ubuntu 22.04 autotools) +# 2. estclient.c references FIPS_mode/FIPS_mode_set removed in OpenSSL 3.x +# โ†’ estclient is not needed; build only the core library (src/) +# +# ARM64 note: libest's estserver.c uses `char c` for the getopt return value. +# On ARM64 Linux, char is unsigned by default, so getopt's end-of-options (-1) +# becomes 255 and never terminates the option loop โ†’ show_usage_and_exit() called. +# Fix: CFLAGS="-fsigned-char" forces signed char behavior. +RUN awk 'BEGIN{n=0} /AM_INIT_AUTOMAKE/{n++; if(n==2)next} {print}' \ + configure.ac > /tmp/configure.ac.patched \ + && mv /tmp/configure.ac.patched configure.ac \ + && echo "=== AM_INIT_AUTOMAKE count (must be 1) ===" \ + && grep -c "AM_INIT_AUTOMAKE" configure.ac \ + && autoreconf --force --install --verbose 2>&1 | tail -5 \ + && ./configure --disable-safec CFLAGS="-fsigned-char" \ + # Build order: + # 1. safe_c_stub โ†’ produces libsafe_lib.a + # 2. Inject FIPS compat stubs into libsafe_lib.a (OpenSSL 3.x support) + # 3. src โ†’ produces libest.so + && make -j"$(nproc)" -C safe_c_stub \ + # OpenSSL 3.x compatibility: + # FIPS_mode / FIPS_mode_set were removed in OpenSSL 3.0. + # libest was written for OpenSSL 1.x, so we provide stub implementations. + # Injecting into libsafe_lib.a resolves the symbols for both libest.so + # and the estserver binary at link time. + && printf 'int FIPS_mode_set(int r){(void)r;return 0;}\nint FIPS_mode(void){return 0;}\n' \ + > /tmp/fips_compat.c \ + && gcc -c -o /tmp/fips_compat.o /tmp/fips_compat.c \ + && ar rcs /build/libest/safe_c_stub/lib/libsafe_lib.a /tmp/fips_compat.o \ + && echo "=== FIPS compat stubs injected into libsafe_lib.a ===" \ + && make -j"$(nproc)" -C src + +# Build EST sample server binary only (skip estclient which has FIPS references) +WORKDIR /build/libest/example/server +RUN make -j"$(nproc)" \ + && echo "=== Build artifact ===" \ + && ls -lh estserver \ + && file estserver + +# ----------------------------------------------------------------------------- +# Stage 2: runtime +# Minimal runtime: NGINX + OpenSSL + compiled estserver binary +# ----------------------------------------------------------------------------- +FROM ubuntu:22.04 + +ENV DEBIAN_FRONTEND=noninteractive + +# Install runtime dependencies only +RUN apt-get update && apt-get install -y --no-install-recommends \ + nginx \ + openssl \ + libssl3 \ + curl \ + && rm -rf /var/lib/apt/lists/* + +# Copy compiled estserver binary +# Note: example/server/estserver is a libtool wrapper script. +# The actual binary is at .libs/estserver +COPY --from=builder /build/libest/example/server/.libs/estserver /usr/local/bin/estserver + +# Copy libest shared library and update linker cache +COPY --from=builder /build/libest/src/est/.libs/libest-*.so /usr/local/lib/ +RUN ln -sf /usr/local/lib/libest-*.so /usr/local/lib/libest.so && ldconfig + +# Copy sample server working directory (contains CA config files) +COPY --from=builder /build/libest/example/server/ /opt/estserver/ + +# Record the libest commit used in this image for reproducibility +COPY --from=builder /LIBEST_COMMIT /opt/estserver/LIBEST_COMMIT + +# Copy runtime config files +COPY nginx.conf /etc/nginx/nginx.conf +COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +# Port definitions: +# 8443 = EST endpoints (HTTPS + mTLS) +# 8080 = Admin HTTP (CA cert download, health check) +EXPOSE 8080 8443 + +CMD ["/entrypoint.sh"] diff --git a/niap-cc/niap-android-cert-ext/est-server/README.md b/niap-cc/niap-android-cert-ext/est-server/README.md new file mode 100644 index 0000000..15bb417 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/est-server/README.md @@ -0,0 +1,590 @@ +# EST Validation Server โ€” Setup Guide + +> **Purpose**: EST (Enrollment over Secure Transport) server for testing NIAP / Common Criteria +> Android certificate enrollment. Cisco libest + NGINX in a single container. +> +> **Deployment options:** +> +> | Option | Environment | EST enroll | mTLS test | Docker required | +> |--------|------------|-----------|-----------|-----------------| +> | **Cloud Run** | Company device, any machine | โœ… | โŒ | No | +> | **Cloud Run + LB** | Company GCP with budget | โœ… | โœ… | No | +> | **Local Docker** | Personal dev machine only | โœ… | โœ… | Yes | +> +> `gcloud run deploy --source .` builds on Google Cloud Build โ€” +> no local Docker installation required. + +--- + +## Architecture Overview + +``` +Android device / emulator + โ”‚ + โ”‚ HTTPS (mTLS optional) :8443 โ† EST protocol + โ”‚ HTTPS (mTLS required) :8081 โ† mTLS test endpoint + โ–ผ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Docker container โ”‚ +โ”‚ โ”‚ +โ”‚ NGINX :8443 (HTTPS + mTLS optional) โ”‚ +โ”‚ โ””โ”€ proxy โ”€โ”€โ–ถ libest :8085 โ”‚ +โ”‚ โ””โ”€ issues certs (CA) โ”‚ +โ”‚ โ”‚ +โ”‚ NGINX :8081 (HTTPS + mTLS required) โ”‚ +โ”‚ โ””โ”€ /protected/ โ† mTLS test โ”‚ +โ”‚ โ”‚ +โ”‚ NGINX :8080 (HTTP) โ”‚ +โ”‚ โ””โ”€ /cacert.pem โ† CA cert download โ”‚ +โ”‚ โ””โ”€ /health โ† health check โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”‚ + โ”‚ HTTP :8080 + โ–ผ +Developer browser (CA cert download) +``` + +### CA Certificate Role + +A throwaway Root CA is auto-generated on first container start. This CA: +1. Signs the server's TLS certificate (used by NGINX) +2. Signs CSRs from Android clients (used by libest) + +--- + +## Prerequisites + +### Cloud Run deployment (no Docker needed) + +| Tool | Check | +|------|-------| +| gcloud CLI | `gcloud version` | +| GCP project with billing enabled | โ€” | + +```bash +# Install gcloud CLI (example for macOS via Homebrew) +brew install --cask google-cloud-sdk +# Add to profile (e.g., ~/.zshrc): export PATH=/opt/homebrew/share/google-cloud-sdk/bin:"$PATH" +gcloud auth login +gcloud config set project +``` + +### Local Docker (personal dev machine only) + +| Tool | Version | Check | +|------|---------|-------| +| Docker | 20.x+ | `docker --version` | +| Docker Compose | v2+ | `docker compose version` | +| curl | any | `curl --version` | + +Internet access is required at image build time (to clone libest). After startup the server runs fully offline. + +--- + +## Certificate Profiles + +Set `EST_CERT_PROFILE` in `docker-compose.yml`: + +| Profile | Purpose | CA key | Server key | Signature | NIAP validator | +|---------|---------|--------|-----------|-----------|----------------| +| `general` | Basic EST verification | RSA-4096 | RSA-2048 | SHA-256 | โŒ not compliant | +| `niap` | NIAP/CC validation | ECDSA P-384 | ECDSA P-384 | SHA-384 | โœ… all checks pass | + +**NIAP profile server certificate extensions:** +- AKID (2.5.29.35), SKID (2.5.29.14), KeyUsage (2.5.29.15) โ€” FIA_X509_EXT.1.2 +- EKU: `serverAuth` (1.3.6.1.5.5.7.3.1) โ€” NiapCertValidator.kt +- EKU: `id-kp-cmcRA` (1.3.6.1.5.5.7.3.28) โ€” FIA_XCU_EXT.1.md ยง5 EST-specific requirement +- basicConstraints: CA:FALSE + +**Client certificates issued by libest (both profiles):** +- SHA-384 signature, AKID, SKID, KeyUsage, EKU (clientAuth) + +--- + +## Setup + +### 1. Check out the repository + +```bash +git clone +cd niap-android-cert-ext/est-server +``` + +### 2. Build the Docker image + +Clones and compiles libest from source. **First build takes 5โ€“10 minutes.** + +```bash +docker compose build +``` + +Verify the build log output: +``` +=== SHA setting verification === +default_md = sha384 โ† NIAP SHA-384 requirement in place +=== Build artifact === +estserver: ELF 64-bit LSB executable โ† binary built successfully +``` + +> **Reproducibility**: After startup, check the libest commit used with: +> `docker exec est-validation-server cat /opt/estserver/LIBEST_COMMIT` +> Record this in your test report. + +### 3. Start the server + +```bash +docker compose up -d +``` + +Wait for the health check to pass: +```bash +docker compose ps +# est-validation-server ... healthy +``` + +Watch the CA initialization log: +```bash +docker compose logs -f +``` + +Expected output: +``` +[est-entrypoint] CA initialization complete. CA certificate info: +[est-entrypoint] EST server startup confirmed. +[est-entrypoint] Starting NGINX [profile: general] +[est-entrypoint] EST (HTTPS + mTLS): https://localhost:8443/.well-known/est/ +[est-entrypoint] CA cert: http://localhost:8080/cacert.pem +``` + +### 4. Smoke test (curl) + +```bash +# Health check +curl http://localhost:8080/health +# โ†’ OK + +# CA cert info +curl -s http://localhost:8080/cacert.pem | openssl x509 -noout -subject -dates +# โ†’ subject=C=JP, ST=Tokyo, O=NIAP Test Lab, CN=EST Validation Root CA + +# EST /cacerts endpoint +curl -ks --cacert <(curl -s http://localhost:8080/cacert.pem) \ + https://localhost:8443/.well-known/est/cacerts \ + | openssl base64 -d | openssl pkcs7 -inform DER -print_certs -noout + +# EST /simpleenroll +openssl req -newkey rsa:2048 -nodes -keyout /tmp/client.key \ + -subj "/CN=test-client" -out /tmp/client.csr 2>/dev/null +curl -sk \ + --cacert <(curl -s http://localhost:8080/cacert.pem) \ + -u "estuser:estpwd" \ + -H "Content-Type: application/pkcs10" \ + --data-binary @/tmp/client.csr \ + https://localhost:8443/.well-known/est/simpleenroll \ + | openssl base64 -d | openssl pkcs7 -inform DER -print_certs -noout +# โ†’ subject=CN=test-client +``` + +### 4.5. Test the mTLS endpoint manually (curl) + +Once you have successfully enrolled a client certificate in the previous step, you can verify the mTLS enforcement endpoint on port `8081` using standard command line tools. + +1. **Extract the client certificate to a PEM file**: + ```bash + # Convert the returned PKCS#7 bundle from simpleenroll into standard PEM format + curl -sk \ + --cacert <(curl -s http://localhost:8080/cacert.pem) \ + -u "estuser:estpwd" \ + -H "Content-Type: application/pkcs10" \ + --data-binary @/tmp/client.csr \ + https://localhost:8443/.well-known/est/simpleenroll \ + | openssl base64 -d | openssl pkcs7 -inform DER -print_certs -out /tmp/client.crt + ``` + +2. **Verify the issued certificate meets NIAP requirements (SHA-384 / ECDSA P-384 / clientAuth)**: + ```bash + openssl x509 -in /tmp/client.crt -noout -text | grep -E "Signature Algorithm|Public Key Algorithm|ASN1 OID|Extended Key Usage" -A 1 + # Expected Output: + # Signature Algorithm: ecdsa-with-SHA384 + # Public Key Algorithm: id-ecPublicKey + # ASN1 OID: secp384r1 + # Extended Key Usage: + # TLS Web Client Authentication + ``` + +3. **Establish an mTLS session using the issued client key and cert**: + ```bash + curl -v -k --cacert <(curl -s http://localhost:8080/cacert.pem) \ + --key /tmp/client.key \ + --cert /tmp/client.crt \ + https://localhost:8081/protected/ + + # Expected HTTP Response: 200 OK + # Body output should contain: + # mTLS OK + # Client: C=JP, ST=Tokyo, O=NIAP Test Lab, CN=test-client + ``` + +--- + + +## Switching to NIAP Profile + +```bash +# Edit docker-compose.yml: set EST_CERT_PROFILE=niap, then restart +docker compose down +docker compose up -d +docker compose logs -f # watch NIAP cert generation + +# Verify server cert NIAP extensions +docker exec est-validation-server \ + openssl x509 -in /opt/estserver/estCA/private/estserver.crt -noout -text \ + | grep -A 5 "Extended Key Usage" +# โ†’ Server Authentication (1.3.6.1.5.5.7.3.1) โœ“ +# โ†’ 1.3.6.1.5.5.7.3.28 (cmcRA) โœ“ +``` + +--- + +## Android App Integration + +### 5. Download and deploy the CA cert + +The Android emulator reaches the host machine at `10.0.2.2`. For a real device on USB, +use the host machine's LAN IP or set up ADB port forwarding. + +```bash +# Download CA cert +curl -o cacert.pem http://localhost:8080/cacert.pem + +# Place in app's raw resources +cp cacert.pem \ + ../cert-test-app/src/main/res/raw/est_validation_ca.pem +``` + +### 6. Configure the Android app + +| Setting | Value | +|---------|-------| +| EST server URL (emulator) | `https://10.0.2.2:8443/.well-known/est/` | +| EST server URL (real device) | `https://:8443/.well-known/est/` | +| Trust anchor | downloaded `cacert.pem` | +| Auth | `estuser:estpwd` | + +### 7. Connectivity check from the device + +```bash +# Emulator +adb shell nc -w 2 10.0.2.2 8443 < /dev/null; echo $? # 0 = connected + +# Real device via ADB port forward +adb reverse tcp:8443 tcp:8443 +adb reverse tcp:8080 tcp:8080 +# then use https://localhost:8443/.well-known/est/ in the app +``` + +### 8. Manual test with the cert-test-app (real device) + +Set up ADB port forwarding first (run on the host machine each time you reconnect the device): + +```bash +adb reverse tcp:8443 tcp:8443 # EST/HTTPS (NGINX โ†’ Host) +adb reverse tcp:8081 tcp:8081 # mTLS test endpoint (NGINX โ†’ Host) +adb reverse tcp:8080 tcp:8080 # HTTP admin / CA cert download (NGINX โ†’ Host) +``` + +App settings to use: + +| Field | Value | +|-------|-------| +| EST Server URL | `https://localhost:8443/.well-known/est/` | +| Auth Token | `estuser:estpwd` | +| CA PEM URL | `http://localhost:8080/cacert.pem` | +| mTLS Endpoint | `https://localhost:8081/protected/` | + +The app downloads the CA PEM automatically from the CA PEM URL on each Enroll attempt. +Leave CA PEM URL blank only if you have embedded the CA cert as a raw resource (`est_validation_ca`) in the app. + +> **Note**: `adb reverse` must be re-run after every device reconnect (USB unplug/replug or `adb kill-server`). + +--- + +## Troubleshooting + +### Build fails + +**Symptom**: errors during `autogen.sh` or `make` + +- Docker memory allocation must be โ‰ฅ 4 GB (Docker Desktop โ†’ Settings โ†’ Resources) +- Internet access required for libest clone + +```bash +# Rebuild without cache +docker compose build --no-cache +``` + +### `estserver` exits immediately + +**Symptom**: log shows "EST server exited immediately" + +**Known root cause (ARM64 / Apple Silicon)**: libest's `estserver.c` declares `char c` for the +getopt return value. On ARM64 Linux, `char` is unsigned by default, so getopt's end-of-options +sentinel (-1) becomes 255, falls through to `default:`, and calls `show_usage_and_exit()`. +Fixed by building with `CFLAGS="-fsigned-char"` (already in the Dockerfile). + +Other causes: +- `libest.so` link error โ†’ `ldd /usr/local/bin/estserver` +- CA directory permission issue โ†’ `ls -la /opt/estserver/estCA/` + +```bash +# Manual test inside container +docker exec -it est-validation-server bash +cd /opt/estserver +estserver -p 8085 \ + -c estCA/private/estservercertandkey.pem \ + -k estCA/private/estservercertandkey.pem \ + -r estrealm -v +``` + +### Cannot connect from Android + +**Symptom**: TLS handshake error or timeout + +1. Check TCP connectivity: `adb shell nc -w 2 10.0.2.2 8443 < /dev/null` +2. Test with curl: `curl -v --cacert cacert.pem https://10.0.2.2:8443/.well-known/est/cacerts` +3. Verify the `cacert.pem` in the app matches the current container CA + +> **Note**: `docker compose down` โ†’ `up` generates a **new CA**. Re-download `cacert.pem` +> and update the app's trust anchor each time you recreate the container. + +### Persist CA across restarts + +```bash +docker run -d \ + -v est-ca-data:/opt/estserver/estCA \ + -p 8443:8443 -p 8080:8080 \ + est-validation-server:local +``` + +--- + +## Stop and Clean Up + +```bash +docker compose down + +# Remove image too (requires rebuild) +docker compose down --rmi local +``` + +--- + +## Cloud Run Deployment (optional) + +> **Note on TLS trust**: Cloud Run presents a Google-signed certificate. When using this endpoint +> from the Android app, leave CA PEM URL blank or do not apply the downloaded CA cert as the TLS +> trust anchor โ€” use the system trust store instead. The CA PEM is still needed to validate issued +> client certificates. + +--- + +### Architecture and limitations + +Cloud Run terminates TLS at Google's infrastructure before the request reaches the container. +As a result: + +| Feature | Cloud Run only | Cloud Run + LB | +|---------|---------------|----------------| +| EST enroll (`/simpleenroll`) | โœ… | โœ… | +| CA cert download (`/cacert.pem`) | โœ… | โœ… | +| mTLS test (`/protected/`) | โŒ | โœ… | + +**Why mTLS does not work on Cloud Run alone:** +The client certificate is stripped at the Cloud Run proxy โ€” nginx inside the container never +receives it, so `ssl_verify_client` has no effect. + +--- + +### Option A: Cloud Run only (EST enroll, no mTLS test) + +This is the current setup. **Local Docker is not required** โ€” `gcloud run deploy --source .` +builds the container on Google Cloud Build, so deployment works from any machine with the +gcloud CLI installed (including company devices where Docker is unavailable). + +For Android app configuration when using Cloud Run: +- EST Server URL: `https:///.well-known/est/` +- CA PEM URL: leave blank (Cloud Run presents a Google-signed cert; system trust store is used) +- mTLS endpoint: requires local Docker or Option B (Cloud LB) + +--- + +### Option B: Cloud Run + Cloud Load Balancer (full mTLS on cloud) โ€” requires budget approval + +> This option is documented for reference when deploying to a company GCP environment with +> an approved budget. The LB forwarding rule incurs a fixed charge (~$18/month) regardless +> of traffic volume โ€” not suitable for personal accounts or short-term validation. + +Add a Cloud Load Balancer in front of Cloud Run to perform mTLS termination. +The LB verifies the client certificate and forwards cert info as an HTTP header +(`X-Forwarded-Client-Cert`) to Cloud Run, where nginx reads it. + +``` +Android device + โ”‚ HTTPS + client cert (mTLS) + โ–ผ +Cloud Load Balancer + โ”‚ - Verifies client cert against EST CA + โ”‚ - Adds X-Forwarded-Client-Cert header + โ–ผ +Cloud Run :8080 + โ”‚ + โ–ผ +nginx /protected/ + - Checks X-Forwarded-Client-Cert header + - 200 if present, 401 if absent +``` + +#### nginx change for `/protected/` on port 8080 + +```nginx +location /protected/ { + if ($http_x_forwarded_client_cert = "") { + return 401 "mTLS required\n"; + } + add_header Content-Type "text/plain"; + return 200 "mTLS OK\nClient-Cert: $http_x_forwarded_client_cert\n"; +} +``` + +#### Cloud LB setup + +```bash +# 1. Create a serverless NEG for Cloud Run +gcloud compute network-endpoint-groups create est-neg \ + --region=asia-northeast1 \ + --network-endpoint-type=serverless \ + --cloud-run-service=est-validation-server + +# 2. Create backend service +gcloud compute backend-services create est-backend \ + --load-balancing-scheme=EXTERNAL_MANAGED \ + --global + +gcloud compute backend-services add-backend est-backend \ + --network-endpoint-group=est-neg \ + --network-endpoint-group-region=asia-northeast1 \ + --global + +# 3. Create URL map, HTTPS proxy, forwarding rule +gcloud compute url-maps create est-url-map --default-service=est-backend +gcloud compute ssl-certificates create est-cert --domains= +gcloud compute target-https-proxies create est-https-proxy \ + --url-map=est-url-map \ + --ssl-certificates=est-cert +gcloud compute forwarding-rules create est-forwarding-rule \ + --load-balancing-scheme=EXTERNAL_MANAGED \ + --target-https-proxy=est-https-proxy \ + --global --ports=443 + +# 4. Enable mTLS: upload EST CA cert as trust config +gcloud certificate-manager trust-configs create est-trust-config \ + --location=global \ + --ca-certs=<(curl -s https:///cacert.pem) + +gcloud compute target-https-proxies update est-https-proxy \ + --server-tls-policy=... # attach trust config via server TLS policy +``` + +> Once approved and deployed, this setup enables full cloud-based mTLS testing without +> requiring Docker on the test device. + +--- + +### Prerequisites (first-time setup) + +1. Create a GCP project and enable billing +2. Install and configure gcloud CLI: + ```bash + # Example for macOS via Homebrew; adjust for other OS platforms: + brew install --cask google-cloud-sdk + # Add to profile configuration: + # export PATH=/opt/homebrew/share/google-cloud-sdk/bin:"$PATH" + source ~/.zshrc + gcloud auth login + gcloud config set project + ``` +3. Grant required IAM permissions to the default Compute Engine service account + (needed once per project โ€” Cloud Run source deploy requires these): + ```bash + SA="-compute@developer.gserviceaccount.com" + gcloud projects add-iam-policy-binding --member="serviceAccount:$SA" --role="roles/cloudbuild.builds.builder" + gcloud projects add-iam-policy-binding --member="serviceAccount:$SA" --role="roles/storage.objectAdmin" + gcloud projects add-iam-policy-binding --member="serviceAccount:$SA" --role="roles/artifactregistry.writer" + ``` + > Find your project number: `gcloud projects describe --format="value(projectNumber)"` + +### Deploy + +```bash +cd est-server +gcloud run deploy est-validation-server \ + --source . \ + --region asia-northeast1 \ + --allow-unauthenticated \ + --max-instances 1 \ + --memory 512Mi \ + --port 8080 +``` + +After deployment: +- CA cert: `https:///cacert.pem` +- Health: `https:///health` +- EST enroll: `https:///.well-known/est/` +- mTLS test (`/protected/`): requires Cloud LB (Option B) or local Docker + +--- + +## Packet Capture (PCAP) for NIAP/CC Verification + +To provide cryptographic verification of the TLS and mTLS handshakes (e.g., confirming TLS 1.3 usage, client cert submission, and SHA-384 algorithms in TLS 1.2 `CertificateVerify`), evaluators can record traffic within the container using `tcpdump`. + +1. **Start packet capture on target interfaces inside the container**: + ```bash + docker exec -it est-validation-server tcpdump -i any -w /opt/estserver/handshake.pcap "port 8443 or port 8081" + ``` + +2. **Execute your test case** (either through `curl` or the Android client app). + +3. **Stop the capture** with `Ctrl+C`. + +4. **Copy the PCAP file to the host machine for Wireshark analysis**: + ```bash + docker cp est-validation-server:/opt/estserver/handshake.pcap ./handshake.pcap + ``` + +--- + +## File Layout + + +``` +est-server/ +โ”œโ”€โ”€ Dockerfile Multi-stage build: compiles Cisco libest from source +โ”œโ”€โ”€ docker-compose.yml Local dev/test Compose definition +โ”œโ”€โ”€ nginx.conf mTLS reverse proxy (ports 8443/8080) +โ”œโ”€โ”€ entrypoint.sh CA init โ†’ estserver start โ†’ NGINX start +โ””โ”€โ”€ README.md This guide +``` + +--- + +## Version Info + +| Component | Version | +|-----------|---------| +| Base image | ubuntu:22.04 | +| libest | main branch (commit pinned at build time) | +| NGINX | Ubuntu 22.04 package | +| OpenSSL | Ubuntu 22.04 package (libssl3) | +| Signature algorithm | SHA-384 (NIAP requirement) | +| ARM64 fix | `CFLAGS=-fsigned-char` (unsigned char getopt bug) | diff --git a/niap-cc/niap-android-cert-ext/est-server/docker-compose.yml b/niap-cc/niap-android-cert-ext/est-server/docker-compose.yml new file mode 100644 index 0000000..a0f8d30 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/est-server/docker-compose.yml @@ -0,0 +1,29 @@ +services: + est-server: + build: + context: . + dockerfile: Dockerfile + args: + # libest branch/tag/commit hash (pin for reproducibility) + # Example: LIBEST_REF: "a464ba8a66717419ba71d289ef82c7b2315b2006" + # To find the latest commit: git ls-remote https://github.com/cisco/libest HEAD + LIBEST_REF: main + image: est-validation-server:local + container_name: est-validation-server + ports: + - "8443:8443" # EST endpoints (HTTPS + mTLS optional) + - "8081:8081" # mTLS test endpoint (HTTPS + mTLS required) + - "8080:8080" # Admin HTTP (CA cert download, health check) + environment: + - TZ=Asia/Tokyo + # Certificate profile: + # general = basic EST protocol verification (RSA-2048, SHA-256, minimal extensions) + # niap = full NIAP/CC validator compliance (ECDSA P-384, SHA-384, all extensions) + - EST_CERT_PROFILE=niap + healthcheck: + test: ["CMD", "curl", "-sf", "http://localhost:8080/health"] + interval: 10s + timeout: 5s + retries: 3 + start_period: 20s + restart: unless-stopped diff --git a/niap-cc/niap-android-cert-ext/est-server/entrypoint.sh b/niap-cc/niap-android-cert-ext/est-server/entrypoint.sh new file mode 100644 index 0000000..78db070 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/est-server/entrypoint.sh @@ -0,0 +1,338 @@ +#!/bin/bash +# ============================================================================= +# EST Validation Server โ€” Entrypoint Script +# +# Certificate profile selection: +# EST_CERT_PROFILE=general (default) โ€” basic protocol verification +# EST_CERT_PROFILE=niap โ€” passes all NIAP/CC validator checks +# +# Directory layout (follows libest ESTcommon.sh conventions): +# /opt/estserver/ +# estExampleCA.cnf โ† CA config (used by openssl ca) +# trustedcerts.crt โ† EST_TRUSTED_CERTS (client cert verification) +# estCA/ +# cacert.crt โ† EST_CACERTS_RESP (CA cert returned by /cacerts) +# index.txt, serial, newcerts/ โ† OpenSSL CA database +# private/ +# cakey.pem โ† CA private key +# estserver.key โ† Server private key +# estserver.crt โ† Server certificate +# estservercertandkey.pem โ† cert+key combined (used for -c/-k args) +# estserver-chain.pem โ† cert+CACert chain (used by NGINX ssl_certificate) +# +# NIAP requirements (NiapCertValidator.kt): +# - Signature: SHA-384 or stronger +# - Key size: RSA-3072+ or ECDSA P-384+ +# - Mandatory extensions: AKID(2.5.29.35), SKID(2.5.29.14), KeyUsage(2.5.29.15) +# - EKU: serverAuth (1.3.6.1.5.5.7.3.1) +# - basicConstraints: CA:FALSE (leaf cert) +# - EST-specific (FIA_XCU_EXT.1.md ยง5): cmcRA OID (1.3.6.1.5.5.7.3.28) +# ============================================================================= +set -euo pipefail + +WORK_DIR="/opt/estserver" +CA_DIR="${WORK_DIR}/estCA" +PRIV_DIR="${CA_DIR}/private" +PROFILE="${EST_CERT_PROFILE:-general}" +LOG_TAG="[est-entrypoint]" + +log() { echo "${LOG_TAG} $*"; } +die() { echo "${LOG_TAG} ERROR: $*" >&2; exit 1; } + +log "==================================================" +log " EST Validation Server starting" +log " Certificate profile: ${PROFILE}" +log "==================================================" + +# ============================================================================= +# Step 1: Write CA config file used by libest +# (directory layout follows ESTcommon.sh variable conventions) +# ============================================================================= +log "Writing estExampleCA.cnf..." +cat > "${WORK_DIR}/estExampleCA.cnf" << 'OPENSSL_CA_CNF_EOF' +# EST Sample CA config (NIAP/CC compliant) +# Path conventions follow ESTcommon.sh: +# EST_OPENSSL_CAPRIVKEY = estCA/private/cakey.pem +# EST_OPENSSL_CACERT = estCA/cacert.crt + +[ ca ] +default_ca = CA_default + +[ CA_default ] +dir = ./estCA +certs = $dir/certs +crl_dir = $dir/crl +database = $dir/index.txt +new_certs_dir = $dir/newcerts +certificate = $dir/cacert.crt +serial = $dir/serial +private_key = $dir/private/cakey.pem +x509_extensions = usr_cert +default_days = 365 +default_crl_days = 30 +# NIAP requirement: SHA-384 or stronger (FIA_X509_EXT.1.1 / RFC 8603 CNSA) +default_md = sha384 +preserve = no +policy = policy_match +# Allow re-enrollment with the same subject name (required for EST /reenroll) +unique_subject = no + +[ policy_match ] +countryName = optional +stateOrProvinceName = optional +organizationName = optional +organizationalUnitName = optional +commonName = supplied +emailAddress = optional + +[ req ] +default_bits = 3072 +default_md = sha384 +distinguished_name = req_distinguished_name +attributes = req_attributes + +[ req_distinguished_name ] +countryName = Country Name (2 letter code) +stateOrProvinceName = State or Province Name +organizationName = Organization Name +commonName = Common Name + +[ req_attributes ] + +# --------------------------------------------------------------------------- +# [ usr_cert ] โ€” extensions for client certs issued by libest via /simpleenroll +# Compliant with NIAP FIA_X509_EXT.1.2: +# - basicConstraints: CA:FALSE (end-entity) +# - AKID, SKID: required (2.5.29.35, 2.5.29.14) +# - KeyUsage: required (2.5.29.15) +# - EKU: clientAuth (for TLS client authentication) +# --------------------------------------------------------------------------- +[ usr_cert ] +basicConstraints = CA:FALSE +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid,issuer +keyUsage = critical,digitalSignature +extendedKeyUsage = clientAuth + +[ v3_ca ] +basicConstraints = critical,CA:true,pathlen:0 +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +keyUsage = critical,keyCertSign,cRLSign +OPENSSL_CA_CNF_EOF + +log "estExampleCA.cnf written." + +# ============================================================================= +# Step 2: Initialize CA (first boot only) +# ============================================================================= +if [ -f "${PRIV_DIR}/estservercertandkey.pem" ]; then + log "CA already initialized. Skipping." +else + log "==================================================" + log " Initializing Certificate Authority [${PROFILE}]" + log "==================================================" + + # Create directory layout expected by libest + mkdir -p "${CA_DIR}/newcerts" "${CA_DIR}/certs" "${CA_DIR}/crl" "${PRIV_DIR}" + chmod 700 "${PRIV_DIR}" + touch "${CA_DIR}/index.txt" + echo "unique_subject = no" > "${CA_DIR}/index.txt.attr" + echo "01" > "${CA_DIR}/serial" + + cd "${WORK_DIR}" + + if [ "${PROFILE}" = "niap" ]; then + # ------------------------------------------------------------------ + # NIAP profile + # CA: ECDSA P-384, SHA-384 + # ------------------------------------------------------------------ + log "[NIAP] Generating Root CA (ECDSA P-384, SHA-384)..." + + openssl ecparam -name secp384r1 -genkey -noout \ + -out "${PRIV_DIR}/cakey.pem" + chmod 600 "${PRIV_DIR}/cakey.pem" + + openssl req -new -x509 \ + -sha384 \ + -days 3650 \ + -key "${PRIV_DIR}/cakey.pem" \ + -out "${CA_DIR}/cacert.crt" \ + -subj "/C=JP/ST=Tokyo/O=NIAP Test Lab/CN=EST Validation Root CA" \ + -extensions v3_ca \ + -config "${WORK_DIR}/estExampleCA.cnf" + + log "[NIAP] Generating server certificate (ECDSA P-384, SHA-384, full NIAP extensions)..." + + openssl ecparam -name secp384r1 -genkey -noout \ + -out "${PRIV_DIR}/estserver.key" + chmod 600 "${PRIV_DIR}/estserver.key" + + # Server certificate extensions (mandatory NIAP extensions + EST-specific EKU) + cat > "${WORK_DIR}/server_ext.cnf" << 'SERVER_EXT_EOF' +[ server_cert ] +# FIA_X509_EXT.1.2: AKID, SKID, KeyUsage required +basicConstraints = CA:FALSE +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid,issuer +keyUsage = critical,digitalSignature +# EKU: +# serverAuth (1.3.6.1.5.5.7.3.1) โ€” TLS server authentication (NiapCertValidator.kt) +# id-kp-cmcRA (1.3.6.1.5.5.7.3.28) โ€” EST-specific requirement (FIA_XCU_EXT.1.md ยง5) +extendedKeyUsage = serverAuth,1.3.6.1.5.5.7.3.28 +# SAN: Android emulator access (10.0.2.2 = host machine) and real device via host IP +subjectAltName = @san_names + +[ san_names ] +DNS.1 = est-server +DNS.2 = localhost +IP.1 = 127.0.0.1 +IP.2 = 10.0.2.2 + +[ req ] +distinguished_name = req_dn +[ req_dn ] +SERVER_EXT_EOF + + openssl req -new \ + -sha384 \ + -key "${PRIV_DIR}/estserver.key" \ + -out "${CA_DIR}/estserver.csr" \ + -subj "/C=JP/ST=Tokyo/O=NIAP Test Lab/CN=est-server" + + openssl x509 -req \ + -sha384 \ + -days 397 \ + -in "${CA_DIR}/estserver.csr" \ + -CA "${CA_DIR}/cacert.crt" \ + -CAkey "${PRIV_DIR}/cakey.pem" \ + -CAcreateserial \ + -out "${PRIV_DIR}/estserver.crt" \ + -extfile "${WORK_DIR}/server_ext.cnf" \ + -extensions server_cert + + log "[NIAP] Server certificate extensions:" + openssl x509 -in "${PRIV_DIR}/estserver.crt" -noout -text \ + | grep -A 20 "X509v3 extensions:" + + else + # ------------------------------------------------------------------ + # General profile (basic protocol verification) + # CA: RSA-4096, SHA-256 / Server: RSA-2048, SHA-256 + # ------------------------------------------------------------------ + log "[General] Generating Root CA (RSA-4096, SHA-256)..." + + openssl req -x509 \ + -newkey rsa:4096 \ + -sha256 \ + -days 3650 \ + -nodes \ + -keyout "${PRIV_DIR}/cakey.pem" \ + -out "${CA_DIR}/cacert.crt" \ + -subj "/C=JP/ST=Tokyo/O=NIAP Test Lab/CN=EST Validation Root CA" \ + -addext "basicConstraints=critical,CA:true" \ + -addext "subjectKeyIdentifier=hash" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" + chmod 600 "${PRIV_DIR}/cakey.pem" + + log "[General] Generating server certificate (RSA-2048, SHA-256)..." + + openssl req -newkey rsa:2048 \ + -nodes \ + -keyout "${PRIV_DIR}/estserver.key" \ + -out "${CA_DIR}/estserver.csr" \ + -subj "/C=JP/ST=Tokyo/O=NIAP Test Lab/CN=est-server" + chmod 600 "${PRIV_DIR}/estserver.key" + + # General profile does not need NIAP validator compliance; + # a simple cert without extensions is sufficient for EST protocol verification. + openssl x509 -req \ + -sha256 \ + -days 365 \ + -in "${CA_DIR}/estserver.csr" \ + -CA "${CA_DIR}/cacert.crt" \ + -CAkey "${PRIV_DIR}/cakey.pem" \ + -CAcreateserial \ + -out "${PRIV_DIR}/estserver.crt" + fi + + # ------------------------------------------------------------------ + # Create combined PEM files required by estserver + # (cert+key โ†’ passed to both -c and -k arguments) + # ------------------------------------------------------------------ + cat "${PRIV_DIR}/estserver.crt" "${PRIV_DIR}/estserver.key" \ + > "${PRIV_DIR}/estservercertandkey.pem" + chmod 600 "${PRIV_DIR}/estservercertandkey.pem" + + # Certificate chain for NGINX (server cert + CA cert) + cat "${PRIV_DIR}/estserver.crt" "${CA_DIR}/cacert.crt" \ + > "${PRIV_DIR}/estserver-chain.pem" + + # EST_TRUSTED_CERTS: trust store for verifying client certificates + cp "${CA_DIR}/cacert.crt" "${WORK_DIR}/trustedcerts.crt" + + log "CA initialization complete. CA certificate info:" + openssl x509 -in "${CA_DIR}/cacert.crt" -noout \ + -subject -issuer -dates -fingerprint -sha256 + log "libest commit: $(cat ${WORK_DIR}/LIBEST_COMMIT)" +fi + +# ============================================================================= +# Step 3: Expose CA cert via HTTP for Android TrustStore setup +# ============================================================================= +mkdir -p /var/www/html +cp "${CA_DIR}/cacert.crt" /var/www/html/cacert.pem +log "CA cert available at: http://localhost:8080/cacert.pem" + +# ============================================================================= +# Step 4: Start libest EST server (port 8085, TLS) +# ============================================================================= +log "==================================================" +log " Starting libest EST server (port 8085, TLS)" +log "==================================================" + +# Environment variables used by libest (same naming as ESTcommon.sh) +export EST_TRUSTED_CERTS="${WORK_DIR}/trustedcerts.crt" +export EST_CACERTS_RESP="${CA_DIR}/cacert.crt" +export EST_OPENSSL_CACONFIG="${WORK_DIR}/estExampleCA.cnf" + +cd "${WORK_DIR}" + +# estserver arguments (per runserver.sh): +# -c/-k: combined cert+key PEM (same file for both) +# -r: HTTP Basic auth realm +# -v: verbose logging +# -p: listen port (default 8085) +estserver \ + -p 8085 \ + -c "estCA/private/estservercertandkey.pem" \ + -k "estCA/private/estservercertandkey.pem" \ + -r "estrealm" \ + -v & + +EST_PID=$! +log "EST server PID: ${EST_PID}" + +# Wait up to 15 seconds for startup confirmation +for i in $(seq 1 15); do + sleep 1 + if ! kill -0 "${EST_PID}" 2>/dev/null; then + die "EST server exited immediately. Check 'docker compose logs' for details." + fi +done +log "EST server startup confirmed." + +# ============================================================================= +# Step 5: Start NGINX +# NGINX terminates TLS/mTLS on 8443 and reverse-proxies to estserver on 8085 +# ============================================================================= +log "==================================================" +log " Starting NGINX [profile: ${PROFILE}]" +log " EST (HTTPS + mTLS optional): https://localhost:8443/.well-known/est/" +log " mTLS test (HTTPS + mTLS req): https://localhost:8081/protected/" +log " Admin (HTTP): http://localhost:8080/" +log " CA cert: http://localhost:8080/cacert.pem" +log " Health check: http://localhost:8080/health" +log "==================================================" + +exec nginx -g 'daemon off;' diff --git a/niap-cc/niap-android-cert-ext/est-server/nginx.conf b/niap-cc/niap-android-cert-ext/est-server/nginx.conf new file mode 100644 index 0000000..b641a2c --- /dev/null +++ b/niap-cc/niap-android-cert-ext/est-server/nginx.conf @@ -0,0 +1,170 @@ +# ============================================================================= +# NGINX config โ€” EST Validation Server +# ============================================================================= +# Port layout: +# 8443 (HTTPS + mTLS optional) ... EST protocol endpoints (RFC 7030) +# 8081 (HTTPS + mTLS required) ... mTLS test endpoint (/protected/) +# 8080 (HTTP) ... CA cert download and health check only +# ============================================================================= + +events { + worker_connections 1024; +} + +http { + # Detailed log format including mTLS verification result and client cert info + log_format est_log '$remote_addr "$request" $status ' + 'ssl_verify=$ssl_client_verify ' + 'client_cn="$ssl_client_s_dn" ' + 'issuer="$ssl_client_i_dn"'; + + access_log /var/log/nginx/access.log est_log; + error_log /var/log/nginx/error.log info; + + # ========================================================================= + # Server 1: EST endpoints (HTTPS + optional mTLS) + # + # Why ssl_verify_client optional: + # - /simpleenroll is initial enrollment, no client cert exists yet + # - /reenroll requires an existing cert (verified internally by estserver) + # - /cacerts requires no authentication + # Final authentication decision is delegated to estserver + # ========================================================================= + server { + listen 8443 ssl; + server_name _; + + # Server certificate chain (estserver.crt + cacert.crt) + # Path matches estserver-chain.pem generated by entrypoint.sh + ssl_certificate /opt/estserver/estCA/private/estserver-chain.pem; + ssl_certificate_key /opt/estserver/estCA/private/estserver.key; + + # TLS versions and cipher suites + # Aligned with NIAP niap_security_config.xml allowed-cipher-suites: + # TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384 (TLS 1.3, managed by NGINX) + # TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + # TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; + ssl_prefer_server_ciphers on; + + # mTLS: client certificate verification + ssl_client_certificate /opt/estserver/estCA/cacert.crt; + ssl_verify_client optional; + ssl_verify_depth 2; + + # ----------------------------------------------------------------------- + # EST protocol routing (RFC 7030 ยง3.2.2) + # Proxy to background estserver + # ----------------------------------------------------------------------- + location /.well-known/est/ { + # estserver runs its own TLS, so proxy via HTTPS + # SSL verification disabled (self-signed CA within same container) + proxy_pass https://127.0.0.1:8085; + proxy_ssl_verify off; + + # Forward mTLS verification result to estserver via HTTP headers + proxy_set_header X-SSL-Client-Verify $ssl_client_verify; + proxy_set_header X-SSL-Client-Subject $ssl_client_s_dn; + proxy_set_header X-SSL-Client-Issuer $ssl_client_i_dn; + proxy_set_header X-SSL-Client-Serial $ssl_client_serial; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + + # EST CSR/cert responses are binary โ€” disable buffering + proxy_buffering off; + proxy_read_timeout 30s; + } + } + + # ========================================================================= + # Server 2: mTLS test endpoint (HTTPS + mTLS required) + # + # Separate from EST (8443) so mTLS testing is not tied to the EST server. + # ssl_verify_client on โ€” unlike 8443 which uses "optional" for /simpleenroll. + # Returns client cert info on success; nginx rejects with 400 if no cert. + # ========================================================================= + server { + listen 8081 ssl; + server_name _; + + ssl_certificate /opt/estserver/estCA/private/estserver-chain.pem; + ssl_certificate_key /opt/estserver/estCA/private/estserver.key; + + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; + ssl_prefer_server_ciphers on; + + ssl_client_certificate /opt/estserver/estCA/cacert.crt; + ssl_verify_client on; + ssl_verify_depth 2; + + location /protected/ { + add_header Content-Type "text/plain"; + return 200 "mTLS OK\nClient: $ssl_client_s_dn\nIssuer: $ssl_client_i_dn\nSerial: $ssl_client_serial\n"; + } + + location / { + return 200 "mTLS Test Server\n /protected/ โ€” requires valid client certificate\n"; + add_header Content-Type "text/plain"; + } + } + + # ========================================================================= + # Server 3: Plain HTTP admin interface + # + # Endpoints: + # /cacert.pem ... CA cert download for Android app TrustStore setup + # /health ... container health check (Cloud Run compatible) + # No TLS, no auth (local dev only โ€” do not expose in production) + # ========================================================================= + server { + listen 8080; + server_name _; + root /var/www/html; + + # CA cert download + location /cacert.pem { + add_header Content-Type "application/x-pem-file"; + add_header Content-Disposition 'attachment; filename="cacert.pem"'; + add_header Cache-Control "no-cache, no-store"; + } + + # Health check (for docker-compose / Cloud Run liveness probe) + location /health { + access_log off; + return 200 "OK\n"; + add_header Content-Type "text/plain"; + } + + # EST endpoints for Cloud Run (no mTLS โ€” TLS terminated by Cloud Run proxy) + # Used when Cloud Run exposes only port 8080. + location /.well-known/est/ { + proxy_pass https://127.0.0.1:8085; + proxy_ssl_verify off; + + # No client cert available on this path โ€” send empty headers + proxy_set_header X-SSL-Client-Verify ""; + proxy_set_header X-SSL-Client-Subject ""; + proxy_set_header X-SSL-Client-Issuer ""; + proxy_set_header X-SSL-Client-Serial ""; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + + proxy_buffering off; + proxy_read_timeout 30s; + } + + # Default: brief server info + location / { + return 200 "EST Validation Server\nEndpoints:\n EST: /.well-known/est/\n CA cert: /cacert.pem\n Health: /health\n"; + add_header Content-Type "text/plain"; + } + } +} diff --git a/niap-cc/niap-android-cert-ext/gradle.properties b/niap-cc/niap-android-cert-ext/gradle.properties new file mode 100644 index 0000000..abda456 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/gradle.properties @@ -0,0 +1,2 @@ +android.useAndroidX=true +org.gradle.jvmargs=-Xmx4096m -Dfile.encoding=UTF-8 diff --git a/niap-cc/niap-android-cert-ext/gradle/wrapper/gradle-wrapper.jar b/niap-cc/niap-android-cert-ext/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..980502d Binary files /dev/null and b/niap-cc/niap-android-cert-ext/gradle/wrapper/gradle-wrapper.jar differ diff --git a/niap-cc/niap-android-cert-ext/gradle/wrapper/gradle-wrapper.properties b/niap-cc/niap-android-cert-ext/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..eeaa4c5 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +#Tue Feb 17 14:07:26 JST 2026 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/niap-cc/niap-android-cert-ext/gradlew b/niap-cc/niap-android-cert-ext/gradlew new file mode 100755 index 0000000..faf9300 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright ยฉ 2015-2021 the original authors. +# +# 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 +# +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions ยซ$varยป, ยซ${var}ยป, ยซ${var:-default}ยป, ยซ${var+SET}ยป, +# ยซ${var#prefix}ยป, ยซ${var%suffix}ยป, and ยซ$( cmd )ยป; +# * compound commands having a testable exit status, especially ยซcaseยป; +# * various built-in commands including ยซcommandยป, ยซsetยป, and ยซulimitยป. +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/niap-cc/niap-android-cert-ext/settings.gradle.kts b/niap-cc/niap-android-cert-ext/settings.gradle.kts new file mode 100644 index 0000000..f0f2888 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/settings.gradle.kts @@ -0,0 +1,53 @@ +/* + * Copyright 2026 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. + */ + +import java.io.File + +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS) + repositories { + google() + mavenCentral() + } +} +rootProject.name = "niap-android-cert-ext" + +val testbedRoot: File = providers.gradleProperty("testbedRoot").orNull + ?.takeIf { it.isNotBlank() } + ?.let { file(it).canonicalFile } + ?: listOf("..", "../../..") + .map { file(it).canonicalFile } + .firstOrNull { File(it, "testbedui-plugins/common-utils").isDirectory } + ?: file("..").canonicalFile + +gradle.extra["testbedRoot"] = testbedRoot + +include(":cert-lib") +include(":cert-manager") +include(":validator-test-app") +include(":agent-test") +include(":cert-test-app") + +include(":common-utils") +project(":common-utils").projectDir = File(testbedRoot, "testbedui-plugins/common-utils") + diff --git a/niap-cc/niap-android-cert-ext/testbed-mcp-reference.md b/niap-cc/niap-android-cert-ext/testbed-mcp-reference.md new file mode 100644 index 0000000..195c580 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/testbed-mcp-reference.md @@ -0,0 +1,398 @@ +# Testbed Automation MCP Reference for LLMs + +This document is a comprehensive Model Context Protocol (MCP) tool reference for LLM agents to control and observe physical or emulated devices within the Testbed Automation environment. + +It is updated from the baseline specifications and incorporates recent additions (such as streaming and ping utilities), precise parameter definitions, and concrete **execution examples**. + +--- + +## 1. Sensing (Device State and Screen Analysis) + +Tools in this category allow agents to inspect screen layouts, query power configurations, and check hardware parameters. + +### `get_ui_dump` +* **Description**: Captures the current screen's UI layout hierarchy. By default, it yields a token-efficient flat list format (~1KB) optimized for LLMs. +* **Parameters**: + * `format` (String / Optional / Default: `"summary"`): Output style. `"summary"` = compact flat list, `"json"` = traditional full-tree JSON. + * `include_image` (Boolean / Optional / Default: `false`): Whether to include base64-encoded screenshot data (valid only when `format="json"`). + * `image_quality` (Int / Optional / Default: `2`): Screen compression level (1 = 100%, 2 = 50%, 3 = 33%, 4 = 25%). +* **Returns**: + * If `format="summary"`: A plain-text flat list where each line represents a node containing its index, class identifier, human-readable label, action coordinates, and state indicators. + * If `format="json"`: A structured JSON payload containing the hierarchical `json_dump` string and optional base64 `screenshot` data. +* **Examples**: + * **Request (Default: summary format)**: + ```json + {} + ``` + * **Response (summary format)**: + ```text + Screen: 1080x2400 | App: com.example.app + โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + [0] ImageButton "Back" tap(73,205) clickable + [1] TextView "Settings" at(540,205) + [2] CheckBox "Option A" tap(540,484) clickable checked=true โ˜… + [3] CheckBox "Option B" tap(540,625) clickable checked=false + โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ scrollable: RecyclerView โ”€ + ``` + * **Request (JSON format)**: + ```json + { + "format": "json", + "include_image": true + } + ``` + * **Response (JSON format)**: + ```json + { + "json_dump": "{\"className\":\"android.widget.FrameLayout\",\"bounds\":\"[0,0][1080,2400]\",\"children\":[...]}" + } + ``` + +### `get_device_state` +* **Description**: Checks screen power state (ON/OFF), screen lock status, and current active foreground package details. +* **Parameters**: None +* **Returns**: A JSON state map. +* **Examples**: + * **Request**: `{}` + * **Response**: + ```json + { + "is_screen_on": true, + "is_locked": false, + "foreground_package": "com.google.android.apps.nexuslauncher" + } + ``` + +### `get_device_info` +* **Description**: Queries hardware and operating system parameters from the system (wrapper around `getprop` entries). +* **Parameters**: None +* **Returns**: A JSON dictionary containing hardware specifications. +* **Examples**: + * **Request**: `{}` + * **Response**: + ```json + { + "model": "Pixel 8", + "os_version": "37", + "abi": "arm64-v8a", + "screen_size": "1080x2400" + } + ``` + +### `start_stream` (New) +* **Description**: Initiates automatic streaming of base64-encoded device screenshots at standard regular intervals. +* **Parameters**: + * `fps` (Float / Optional / Default: `1.0`): Target frames per second. + * `image_quality` (Int / Optional / Default: `2`): Screen compression level (1 to 4). +* **Returns**: Operation status success message. +* **Examples**: + * **Request**: + ```json + { + "fps": 2.0, + "image_quality": 3 + } + ``` + * **Response**: `"Stream started"` + +### `stop_stream` (New) +* **Description**: Terminates active screenshot streaming operations. +* **Parameters**: None +* **Returns**: Operation status success message. +* **Examples**: + * **Request**: `{}` + * **Response**: `"Stream stopped"` + +--- + +## 2. Action (UI Interactions and Gestures) + +These tools execute physical interactions on the device. Following command invocation, they automatically wait for the screen to settle into an idle state and **return a summary of interactable elements only** (a layout list containing only clickable, checkable, or scrollable nodes). + +### `tap` +* **Description**: Simulates a tap action at the specified (x, y) screen coordinates. +* **Parameters**: + * `x` (Int / Required): Target X coordinate. + * `y` (Int / Required): Target Y coordinate. +* **Returns**: An interactable UI elements summary layout list. +* **Examples**: + * **Request**: + ```json + { + "x": 500, + "y": 1000 + } + ``` + * **Response**: (Latest interactable UI layout summary) + +### `input_text` +* **Description**: Sends a raw text string to the currently focused text input control. +* **Parameters**: + * `text` (String / Required): The text string to send. Spaces and special characters are managed and escaped automatically. +* **Returns**: An interactable UI elements summary layout list. +* **Examples**: + * **Request**: + ```json + { + "text": "Hello World" + } + ``` + * **Response**: (Latest interactable UI layout summary) + +### `swipe` +* **Description**: Initiates a linear drag gesture between start and end screen coordinates. +* **Parameters**: + * `start_x` (Int / Required) + * `start_y` (Int / Required) + * `end_x` (Int / Required) + * `end_y` (Int / Required) +* **Returns**: An interactable UI elements summary layout list. +* **Examples**: + * **Request**: + ```json + { + "start_x": 500, + "start_y": 1500, + "end_x": 500, + "end_y": 500 + } + ``` + * **Response**: (Latest interactable UI layout summary) + +### `press_key` +* **Description**: Dispatches a standard hardware or system physical key button press. +* **Parameters**: + * `keycode` (String / Required): Key event identifier (e.g., `"BACK"`, `"HOME"`, `"ENTER"`). +* **Returns**: An interactable UI elements summary layout list. +* **Examples**: + * **Request**: + ```json + { + "keycode": "BACK" + } + ``` + * **Response**: (Latest interactable UI layout summary) + +--- + +## 3. System (ADB Commands and Package Administration) + +### `execute_adb_shell` +* **Description**: Executes an arbitrary ADB shell command on the target system. +* **Parameters**: + * `command` (String / Required): Terminal command to run. +* **Returns**: Combined plain text streams of `stdout` and `stderr`. +* **Examples**: + * **Request**: + ```json + { + "command": "ls -l /sdcard" + } + ``` + * **Response**: + ```text + total 0 + drwxrwxr-x 2 root sdcard_rw 4096 ... + ``` + *(Note: Depending on individual tool wrapper specifications, stdout/stderr streams might sometimes be delivered inside a structured JSON response object, but they are typically returned as simple text values.)* + +### `open_settings` +* **Description**: Direct-launches specific system settings pages using target system Intents. +* **Parameters**: + * `panel` (String / Required): Settings partition code. Valid keys: `ROOT`, `SECURITY`, `WIFI`, `APP_DETAILS`, `DEVELOPER`. +* **Returns**: A layout representation string of the opened settings layout. +* **Examples**: + * **Request**: + ```json + { + "panel": "SECURITY" + } + ``` + * **Response**: (Settings page UI layout representation) + +### `push_file` +* **Description**: Transports local host files onto target paths of the connected device. +* **Parameters**: + * `host_path` (String / Required): Source file path on the host computer. + * `device_path` (String / Required): Destination file path on the target device. +* **Returns**: Operation status success or error message. +* **Examples**: + * **Request**: + ```json + { + "host_path": "/tmp/test.apk", + "device_path": "/data/local/tmp/test.apk" + } + ``` + * **Response**: `"File pushed successfully"` + +### `pull_file` +* **Description**: Downloads files from target locations on the device to the host system. +* **Parameters**: + * `device_path` (String / Required): Target file path on the device. + * `host_path` (String / Required): Destination path on the host computer. +* **Returns**: Operation status success or error message. +* **Examples**: + * **Request**: + ```json + { + "device_path": "/sdcard/screenshot.png", + "host_path": "/tmp/screenshot.png" + } + ``` + * **Response**: `"File pulled successfully"` + +### `install_app` +* **Description**: Installs a target application APK package from the host system. +* **Parameters**: + * `apk_path` (String / Required): Absolute file path to the source APK on the host. +* **Returns**: Installation terminal output. +* **Examples**: + * **Request**: + ```json + { + "apk_path": "/tmp/app.apk" + } + ``` + * **Response**: `"Success"` + +### `uninstall_app` +* **Description**: Removes an application package from the target device system. +* **Parameters**: + * `package_name` (String / Required): Target package unique identifier (e.g., `com.example.app`). +* **Returns**: Operation status confirmation. +* **Examples**: + * **Request**: + ```json + { + "package_name": "com.example.app" + } + ``` + * **Response**: `"Success"` + +--- + +## 4. Observe (Logging and Connection Diagnostics) + +### `get_logcat` +* **Description**: Captures memory-buffered system and application logs via Logcat. Applying specific query filters is highly recommended to protect token budgets. +* **Parameters**: + * `tags` (String[] / Optional / Default: `[]`): Filter logs matching target tag names. + * `level` (String / Optional / Default: `"V"`): Filter logs exceeding minimum priority levels (`V`, `D`, `I`, `W`, `E`, `F`). + * `grep_pattern` (String / Optional / Default: `""`): Filter entries matching regular expressions. + * `max_lines` (Int / Optional / Default: `100`): Maximum lines output boundary. + * `process` (String / Optional / Default: `""`): Filter logs matching specific processes. Supports package names (e.g., `"com.android.settings"`) or active PIDs (e.g., `"1234"`). Package strings are resolved to PIDs dynamically (first checking cached structures from ProcessNameResolver, then using `pidof` commands as fallback). +* **Returns**: A plain-text block of raw logs. +* **Examples**: + * **Targeting Tag Names**: + ```json + { + "tags": ["ActivityManager"], + "level": "I", + "max_lines": 5 + } + ``` + * **Targeting Package Processes**: + ```json + { + "process": "com.android.settings", + "level": "D", + "max_lines": 50 + } + ``` + * **Response Output**: + ```text + 04-09 02:00:00.000 1000 1000 I ActivityManager: Start proc ... + 04-09 02:00:01.000 1000 1000 I ActivityManager: Activity paused ... + ``` + +### `clear_logcat` +* **Description**: Purges all log entries currently present inside the system Logcat buffers. +* **Parameters**: None +* **Returns**: Operation status success message. +* **Examples**: + * **Request**: `{}` + * **Response**: `"Logcat cleared"` + +### `ping` (New) +* **Description**: Verifies continuous message connectivity with the on-device Mutton Agent. +* **Parameters**: None +* **Returns**: Latency response confirmation message. +* **Examples**: + * **Request**: `{}` + * **Response**: `"pong"` + +### `get_agent_version` +* **Description**: Queries the build version number of the Mutton Agent current running on the device. +* **Parameters**: None +* **Returns**: Build version tag. +* **Examples**: + * **Request**: `{}` + * **Response**: `"1.0.0"` + +--- + +## 5. Test Control (JUnit Test Orchestration) + +These test services are executed by compiling and deploying specialized test JAR plugins directly onto the TestBed Core architecture. Because these programs run inside dedicated processes independent from the targeted systems, they escape common target app sandboxes or Android Instrumentation execution limitations, offering high runtime flexibility. + +Management and development of these modules are conducted within the test suite projects (such as `niap-android-cert-ext`). If necessary, compile the plugin targets (including any shared modules like `common-utils`), build the final JAR, and register it inside the `plugins` folder of TestBed Core. + +### `junit_test_reload` +* **Description**: Triggers a hot-reload of registered test JAR assemblies inside TestBed Core. +* **Parameters**: None +* **Returns**: Operation reload status metrics. + +### `junit_test_list` +* **Description**: Queries a list of all current runnable test methods registered on the environment. +* **Parameters**: None +* **Returns**: A JSON array string of target class and method pointers. +* **Examples**: + * **Request**: `{}` + * **Response**: `["com.example.TestClass#testMethod1", "..."]` + +### `junit_test_execute` +* **Description**: Initiates async execution of specified JUnit tests. +* **Parameters**: + * `class_name` (String / Required): Absolute canonical identifier of the target class. + * `method_name` (String / Optional): Target test case method identifier. +* **Returns**: Initialization success message. + +### `junit_test_receive` +* **Description**: Captures current logs or structural exit results of target JUnit tests. +* **Parameters**: None +* **Returns**: A JSON payload containing execution statuses (`Running`, `Finished`), step traces, pass/fail state indicators, or exceptions stack traces. + +--- + +## 6. Health (Connection Auditing and Recovery) + +### `check_testbed_health` +* **Description**: Performs a holistic pipeline assessment, monitoring ADB connectivity status, physical devices links, and agent daemon processes. +* **Parameters**: None +* **Returns**: Diagnostic metrics JSON. +* **Examples**: + * **Response**: + ```json + { + "adbIsValid": true, + "deviceSerial": "localhost:38189", + "isRunning": false, + "deviceInfo": "..." + } + ``` + +### `cleanup_agent` +* **Description**: Forcefully kills and restarts the on-device automation agent daemon process (essential for recovering from standard system UiAutomation lockouts). +* **Parameters**: None +* **Returns**: Status confirmation message. + +--- + +## LLM Tips & Best Practices + +1. **Token Conservation**: `get_ui_dump` returns the highly efficient `summary` flat list by default (~1KB). Use `format="json"` only when full coordinate systems or specific layout attributes are strictly necessary. Always target `get_logcat` queries with restrictive `tags`, levels, or `max_lines` scopes. +2. **Automatic Wait Cycles**: UI action tools (such as `tap` or `input_text`) automatically wait for the screen layout to settle into an idle state before resolving their interactable element summaries. Making separate `get_ui_dump` calls immediately after these actions is redundant. +3. **Reading Flat Summaries**: Lines are structured using the format: `[Index] ClassName "Label" tap(x,y) flags`. The coordinate map returned by `tap(x,y)` can be passed directly to touch tools. Nodes featuring `at(x,y)` represent non-interactable layout positions. +4. **Layout Crash Recovery**: If you encounter recurring target acquisition errors (e.g., `rootInActiveWindow returned null` exception messages), issue a `cleanup_agent` command to re-initialize the target context and recover the channel connection. +5. **Space Escapes in Terminal Commands**: When executing raw terminal commands via `execute_adb_shell` that pass arguments containing space strings (e.g., `input text "hello world"`), be aware of the underlying parser limitations (some environments might require replacing spaces with escape strings like `input text hello%sworld`). High-level tools (such as `input_text`) manage these encodings automatically, but this is an important consideration when using raw terminal execution scripts. diff --git a/niap-cc/niap-android-cert-ext/tools/check-no-hidden-api.sh b/niap-cc/niap-android-cert-ext/tools/check-no-hidden-api.sh new file mode 100755 index 0000000..de124f1 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/tools/check-no-hidden-api.sh @@ -0,0 +1,219 @@ +#!/usr/bin/env bash +# +# Static guard preventing app-level Android modules from depending on +# non-SDK (hidden) platform APIs. +# +# Scans non-test Kotlin/Java sources (*.kt, *.java) under: +# cert-lib, cert-manager, validator-test-app, cert-test-app +# +# Per-line exemption syntax (must include a non-empty reason): +# // hidden-api-check: allow +# +# Usage: +# tools/check-no-hidden-api.sh + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" + +MODULES=( + "cert-lib" + "cert-manager" + "validator-test-app" + "cert-test-app" +) + +cd "$REPO_ROOT" + +# Collect non-test *.kt and *.java files across the app-level modules. +FILES=() +for mod in "${MODULES[@]}"; do + src_root="${mod}/src" + if [[ ! -d "$src_root" ]]; then + echo "Warning: source directory not found: ${src_root}" >&2 + continue + fi + for variant_dir in "${src_root}"/*; do + [[ -d "$variant_dir" ]] || continue + variant_name="$(basename "$variant_dir")" + case "$variant_name" in + test|test*|androidTest|androidTest*) + continue + ;; + esac + while IFS= read -r file; do + [[ -n "$file" ]] && FILES+=("$file") + done < <(find "$variant_dir" -type f \( -name "*.kt" -o -name "*.java" \) | LC_ALL=C sort) + done +done + +if [[ ${#FILES[@]} -eq 0 ]]; then + echo "Error: no source files found to scan." >&2 + exit 1 +fi + +awk ' +BEGIN { + n_rules = 0 + rules[++n_rules] = "Class\\.forName\\([[:space:]]*\"com\\.android\\." + names[n_rules] = "Class.forName(\"com.android.*\")" + + rules[++n_rules] = "Class\\.forName\\([[:space:]]*\"android\\." + names[n_rules] = "Class.forName(\"android.*\")" + + rules[++n_rules] = "com\\.android\\.org\\.conscrypt" + names[n_rules] = "com.android.org.conscrypt" + + rules[++n_rules] = "android\\.security\\.net\\.config" + names[n_rules] = "android.security.net.config" + + rules[++n_rules] = "\\.javaClass\\.getMethod\\(" + names[n_rules] = ".javaClass.getMethod(" + + rules[++n_rules] = "\\.javaClass\\.getDeclaredMethod\\(" + names[n_rules] = ".javaClass.getDeclaredMethod(" + + rules[++n_rules] = "\\.getClass\\(\\)\\.getMethod\\(" + names[n_rules] = ".getClass().getMethod(" + + rules[++n_rules] = "\\.getClass\\(\\)\\.getDeclaredMethod\\(" + names[n_rules] = ".getClass().getDeclaredMethod(" + + rules[++n_rules] = "getDeclaredMethod\\(" + names[n_rules] = "getDeclaredMethod(" + + rules[++n_rules] = "getDeclaredField\\(" + names[n_rules] = "getDeclaredField(" + + rules[++n_rules] = "setAccessible\\([[:space:]]*true[[:space:]]*\\)" + names[n_rules] = "setAccessible(true)" + + rules[++n_rules] = "isAccessible[[:space:]]*=[[:space:]]*true" + names[n_rules] = "isAccessible = true" + + rules[++n_rules] = "dalvik\\.system\\.VMRuntime" + names[n_rules] = "dalvik.system.VMRuntime" + + rules[++n_rules] = "sun\\.misc\\.Unsafe" + names[n_rules] = "sun.misc.Unsafe" + + violations = 0 + exemptions = 0 + files_scanned = 0 + in_block_comment = 0 + prev_file = "" +} + +function trim(s) { + sub(/^[[:space:]]+/, "", s) + sub(/[[:space:]]+$/, "", s) + return s +} + +{ + if (FILENAME != prev_file) { + in_block_comment = 0 + prev_file = FILENAME + files_scanned++ + } + + raw = $0 + sub(/\r$/, "", raw) + + # Check for an explicit per-line exemption comment with a non-empty reason: + # // hidden-api-check: allow + exempt_reason = "" + if (match(raw, /\/\/[[:space:]]*hidden-api-check:[[:space:]]*allow[[:space:]]+[^[:space:]].*$/)) { + exempt_reason = substr(raw, RSTART, RLENGTH) + sub(/^\/\/[[:space:]]*hidden-api-check:[[:space:]]*allow[[:space:]]+/, "", exempt_reason) + exempt_reason = trim(exempt_reason) + } + + # Strip block comments and line comments (respecting double-quoted strings) + # to inspect only active code. + code = "" + n_chars = length(raw) + in_str = 0 + escaped = 0 + pos = 1 + while (pos <= n_chars) { + ch = substr(raw, pos, 1) + nxt = (pos < n_chars) ? substr(raw, pos + 1, 1) : "" + if (in_block_comment) { + if (ch == "*" && nxt == "/") { + in_block_comment = 0 + pos += 2 + } else { + pos++ + } + } else if (in_str) { + code = code ch + if (escaped) { + escaped = 0 + } else if (ch == "\\") { + escaped = 1 + } else if (ch == "\"") { + in_str = 0 + } + pos++ + } else { + if (ch == "\"") { + in_str = 1 + code = code ch + pos++ + } else if (ch == "/" && nxt == "/") { + break + } else if (ch == "/" && nxt == "*") { + in_block_comment = 1 + pos += 2 + } else { + code = code ch + pos++ + } + } + } + + # Match against forbidden patterns; report all distinct matches on this line. + matched = "" + for (i = 1; i <= n_rules; i++) { + if (code ~ rules[i]) { + if (matched == "") { + matched = names[i] + } else { + matched = matched ", " names[i] + } + } + } + + if (matched != "") { + if (exempt_reason != "") { + exemptions++ + exempt_list[exemptions] = sprintf(" %s:%d: [%s] allow: %s", FILENAME, FNR, matched, exempt_reason) + } else { + violations++ + viol_list[violations] = sprintf(" %s:%d: [%s] %s", FILENAME, FNR, matched, trim(raw)) + } + } +} + +END { + print "Hidden-API static check: scanned " files_scanned " source file(s)." + if (exemptions > 0) { + print "Exemptions (" exemptions "):" + for (i = 1; i <= exemptions; i++) { + print exempt_list[i] + } + } + if (violations > 0) { + print "FAIL: found " violations " forbidden non-SDK/hidden-API pattern(s):" > "/dev/stderr" + for (i = 1; i <= violations; i++) { + print viol_list[i] > "/dev/stderr" + } + print "Use public SDK APIs only, or add \"// hidden-api-check: allow \" if strictly justified." > "/dev/stderr" + exit 1 + } + print "PASS: 0 hidden-API violations found (" exemptions " exemption(s))." + exit 0 +} +' "${FILES[@]}" diff --git a/niap-cc/niap-android-cert-ext/tools/package-submission.sh b/niap-cc/niap-android-cert-ext/tools/package-submission.sh new file mode 100755 index 0000000..65d0feb --- /dev/null +++ b/niap-cc/niap-android-cert-ext/tools/package-submission.sh @@ -0,0 +1,235 @@ +#!/usr/bin/env bash +# +# Reproducible packaging script for NIAP lab resubmission (app-level library track). +# +# Usage: +# tools/package-submission.sh [--allow-dirty] [outdir] +# +# Defaults: +# outdir = dist/ + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" + +ALLOW_DIRTY=false +OUT_DIR_ARG="" + +usage() { + cat <). +EOF +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --allow-dirty) + ALLOW_DIRTY=true + shift + ;; + -h|--help) + usage + exit 0 + ;; + -*) + echo "Error: unknown option: $1" >&2 + usage >&2 + exit 1 + ;; + *) + if [[ -n "$OUT_DIR_ARG" ]]; then + echo "Error: unexpected extra argument: $1" >&2 + usage >&2 + exit 1 + fi + OUT_DIR_ARG="$1" + shift + ;; + esac +done + +cd "$REPO_ROOT" + +# 1. Verify git cleanliness unless --allow-dirty is specified +GIT_STATUS="$(git status --porcelain)" +if [[ -n "$GIT_STATUS" && "$ALLOW_DIRTY" != "true" ]]; then + echo "Error: git working tree is dirty. Commit or stash changes, or pass --allow-dirty." >&2 + echo "$GIT_STATUS" >&2 + exit 1 +fi + +TREE_STATE="clean" +if [[ -n "$GIT_STATUS" ]]; then + TREE_STATE="dirty (--allow-dirty)" +fi + +# 2. Run non-SDK (hidden) platform API guards before building artifacts +echo "==> Running static hidden-API check..." +"${SCRIPT_DIR}/check-no-hidden-api.sh" + +echo "==> Running Android Lint hidden-API guard (-PskipTestbedCopy=true)..." +./gradlew --console=plain -PskipTestbedCopy=true \ + :cert-lib:lintDebug \ + :validator-test-app:lintStrictDebug \ + :cert-manager:lintDebug \ + :cert-test-app:lintDebug + +# 3. Resolve output directory +DATE_STAMP="$(date +%Y%m%d)" +if [[ -z "$OUT_DIR_ARG" ]]; then + OUT_DIR="${REPO_ROOT}/dist/${DATE_STAMP}" +elif [[ "$OUT_DIR_ARG" = /* ]]; then + OUT_DIR="$OUT_DIR_ARG" +else + OUT_DIR="${REPO_ROOT}/${OUT_DIR_ARG}" +fi + +mkdir -p "$OUT_DIR" + +echo "==> Packaging NIAP app-level submission into: ${OUT_DIR}" + +# 4. Build artifacts and run cert-lib unit tests without copying APKs to testbed-core +echo "==> Running Gradle build & unit tests (-PskipTestbedCopy=true)..." +./gradlew --console=plain -PskipTestbedCopy=true \ + :cert-lib:testDebugUnitTest \ + :cert-lib:assembleRelease \ + :validator-test-app:assembleStrictDebug \ + :validator-test-app:assembleRelaxedDebug \ + :cert-manager:assembleDebug \ + :cert-test-app:assembleDebug + +# 4. Locate and verify built artifacts +AAR_SRC="${REPO_ROOT}/cert-lib/build/outputs/aar/cert-lib-release.aar" +VALIDATOR_STRICT_APK="${REPO_ROOT}/validator-test-app/build/outputs/apk/strict/debug/validator-test-app-strict-debug.apk" +VALIDATOR_RELAXED_APK="${REPO_ROOT}/validator-test-app/build/outputs/apk/relaxed/debug/validator-test-app-relaxed-debug.apk" +CERT_MANAGER_APK="${REPO_ROOT}/cert-manager/build/outputs/apk/debug/cert-manager-debug.apk" +CERT_TEST_APP_APK="${REPO_ROOT}/cert-test-app/build/outputs/apk/debug/cert-test-app-debug.apk" + +for artifact in \ + "$AAR_SRC" \ + "$VALIDATOR_STRICT_APK" \ + "$VALIDATOR_RELAXED_APK" \ + "$CERT_MANAGER_APK" \ + "$CERT_TEST_APP_APK"; do + if [[ ! -f "$artifact" ]]; then + echo "Error: expected build artifact not found: $artifact" >&2 + exit 1 + fi +done + +# 5. Stage source zips in a temporary directory +STAGE_DIR="$(mktemp -d)" +trap 'rm -rf "$STAGE_DIR"' EXIT + +# Exclude platform-level modules and local/build/IDE/packaging files from git ls-files +filter_app_level_sources() { + git ls-files | LC_ALL=C sort | grep -Ev \ + '^(poc_patch_for_26q2/|cert-manager-system/|cert-testapp-system/|strict-browser-app/|poc-design/|dist/|\.idea/|\.gradle/|\.claude/|\.kotlin/|build/|[^/]+/build/|local\.properties$|\.DS_Store$|.*\.iml$|.*\.jks$|.*\.hprof$|\.env$|adb_key\..*|.*\.log$|.*\.class$)' +} + +# 5a. niap-android-cert-ext.zip (top folder: niap-android-cert-ext/) +FULL_STAGE="${STAGE_DIR}/niap-android-cert-ext" +mkdir -p "$FULL_STAGE" +while IFS= read -r relpath; do + [[ -z "$relpath" ]] && continue + [[ ! -e "${REPO_ROOT}/${relpath}" ]] && continue + dest="${FULL_STAGE}/${relpath}" + mkdir -p "$(dirname "$dest")" + cp -p "${REPO_ROOT}/${relpath}" "$dest" +done < <(filter_app_level_sources) + +rm -f "${OUT_DIR}/niap-android-cert-ext.zip" +(cd "$STAGE_DIR" && zip -r -X -q "${OUT_DIR}/niap-android-cert-ext.zip" niap-android-cert-ext) + +# 5b. niap-cert-lib-release.zip (top folder: niap-cert-lib/) +LIB_STAGE="${STAGE_DIR}/niap-cert-lib" +mkdir -p "$LIB_STAGE" +cp -p "${REPO_ROOT}/LICENSE" "${LIB_STAGE}/LICENSE" +cp -p "${REPO_ROOT}/README.md" "${LIB_STAGE}/README.md" +cp -p "$AAR_SRC" "${LIB_STAGE}/cert-lib-release.aar" + +while IFS= read -r relpath; do + [[ -z "$relpath" ]] && continue + [[ ! -e "${REPO_ROOT}/${relpath}" ]] && continue + dest="${LIB_STAGE}/${relpath}" + mkdir -p "$(dirname "$dest")" + cp -p "${REPO_ROOT}/${relpath}" "$dest" +done < <(filter_app_level_sources | grep '^cert-lib/') + +rm -f "${OUT_DIR}/niap-cert-lib-release.zip" +(cd "$STAGE_DIR" && zip -r -X -q "${OUT_DIR}/niap-cert-lib-release.zip" niap-cert-lib) + +# 6. Copy built AAR and APKs alongside the zips +cp -p "$AAR_SRC" "${OUT_DIR}/cert-lib-release.aar" +cp -p "$VALIDATOR_STRICT_APK" "${OUT_DIR}/validator-test-app-strict-debug.apk" +cp -p "$VALIDATOR_RELAXED_APK" "${OUT_DIR}/validator-test-app-relaxed-debug.apk" +cp -p "$CERT_MANAGER_APK" "${OUT_DIR}/cert-manager-debug.apk" +cp -p "$CERT_TEST_APP_APK" "${OUT_DIR}/cert-test-app-debug.apk" + +# 7. Write MANIFEST.txt +GIT_COMMIT="$(git rev-parse HEAD)" +GIT_BRANCH="$(git rev-parse --abbrev-ref HEAD)" +BUILD_DATE_UTC="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" +JAVA_VER="$(java -version 2>&1 | head -n 1)" +GRADLE_VER="$(./gradlew --version 2>/dev/null | grep -E '^Gradle ' | head -n 1 || echo "unknown")" +GIT_VER="$(git --version)" + +ARTIFACTS=( + "cert-lib-release.aar" + "cert-manager-debug.apk" + "cert-test-app-debug.apk" + "niap-android-cert-ext.zip" + "niap-cert-lib-release.zip" + "validator-test-app-relaxed-debug.apk" + "validator-test-app-strict-debug.apk" +) + +MANIFEST_FILE="${OUT_DIR}/MANIFEST.txt" +{ + echo "NIAP Android Cert Ext - Submission Package Manifest" + echo "===================================================" + echo "Date (UTC): ${BUILD_DATE_UTC}" + echo "Git Commit: ${GIT_COMMIT}" + echo "Git Branch: ${GIT_BRANCH}" + echo "Tree State: ${TREE_STATE}" + echo "" + echo "Tool Versions:" + echo " Java: ${JAVA_VER}" + echo " Gradle: ${GRADLE_VER}" + echo " Git: ${GIT_VER}" + echo " OS: $(uname -srm)" + echo "" + echo "Packaged Files:" + for f in "${ARTIFACTS[@]}"; do + size="$(wc -c < "${OUT_DIR}/${f}" | tr -d ' ')" + printf " %-40s %12s bytes\n" "$f" "$size" + done +} > "$MANIFEST_FILE" + +# 8. Write SHA256SUMS +SHA256_FILE="${OUT_DIR}/SHA256SUMS" +if command -v sha256sum >/dev/null 2>&1; then + HASH_CMD=(sha256sum) +else + HASH_CMD=(shasum -a 256) +fi + +( + cd "$OUT_DIR" + "${HASH_CMD[@]}" "${ARTIFACTS[@]}" "MANIFEST.txt" > "$SHA256_FILE" +) + +echo "==> Packaging complete:" +ls -lh "$OUT_DIR" diff --git a/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/README.md b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/README.md new file mode 100644 index 0000000..931f207 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/README.md @@ -0,0 +1,162 @@ +# TLS Lab Reproduction Harness (`tools/tls-lab-repro`) + +Reusable host-side OpenSSL + `adb` test harness for reproducing and verifying NIAP MDFPP TLS findings against `cert-lib` via `validator-test-app` (`com.example.niap.cert.ext.testapp`). + +## Contents + +| File | Purpose | +|---|---| +| `gen_pki.sh` | Generates a NIAP-compliant P-384 / `ecdsa-with-SHA384` server PKI, five stapled OCSP responses (`good`, `revoked`, `badsigner`, `corrupt`, `good-sha256`), a client CA + client leaf (`client.p12`), and single-line base64 files for `am start` extras. | +| `run_case.sh` | Runs a single test case (`http` or `okhttp3`) against `openssl s_server -www -trace`, captures PID-scoped `logcat`, and prints a one-line machine-parsable summary. | +| `run_resumption.sh` | Keeps one `openssl s_server` alive across multiple launches (`LAUNCHES=N`) or an in-app repeat (`REPEAT=N`), reporting per-connection `pre_shared_key`, `session_ticket`, `session_id`, and server reuse. | +| `run_matrix.sh` | Executes the full case matrix across `http` and `okhttp3`, auto-selects the expected profile from `ro.build.version.sdk` (`expected_fixed_api36.tsv` for API โ‰ค 36, `expected_fixed.tsv` for API 37+), and writes a Markdown report to `out/matrix_report.md`. | +| `expected_fixed.tsv` | Target behavior matrix for **Android 17+ (API 37+)** where `ExtendedSSLSession.getStatusResponses()` is public API (TLS 1.2 + TLS 1.3 enabled). | +| `expected_fixed_api36.tsv` | Target behavior matrix for **Android 16 and below (API โ‰ค 36)** where `cert-lib` runs in TLS-1.2-only mode and reads stapled OCSP responses from the plaintext TLS 1.2 `CertificateStatus` message. | + +Generated artifacts (PKI, logs, reports) are placed under `tools/tls-lab-repro/out/`, which is git-ignored. + +--- + +## Prerequisites + +- **OpenSSL 3.x / 4.x** with `-trace`, `-status_file`, `-www`, and `-Verify` support (defaults to `/opt/homebrew/bin/openssl` on macOS if present, otherwise `openssl` on `PATH`; override with `OPENSSL=...`). +- **`adb`** connected to an Android device with `validator-test-app` (`com.example.niap.cert.ext.testapp`) installed. +- **`perl`** and **`python3`** on the host (used for bounded `adb` timeouts, OCSP byte-flipping, and trace parsing). + +--- + +## Device Setup (`adb reverse`) + +Forward the device's `localhost:9443` to the host's `s_server` port before running any test: + +```bash +# Optional: set SERIAL if multiple devices are attached +export SERIAL= + +adb -s "$SERIAL" reverse tcp:9443 tcp:9443 +adb -s "$SERIAL" reverse --list +``` + +If using a different port, pass `PORT=` and forward that same port with `adb reverse`. + +--- + +## Usage + +### 1. Generate the Test PKI + +```bash +./tools/tls-lab-repro/gen_pki.sh +``` + +Options: +- Pass a custom output directory as `$1` (default: `tools/tls-lab-repro/out/pki`). +- `OCSP_DAYS=30` โ€” validity window for generated OCSP responses (default `30`). +- `P12_PASS=changeit` โ€” password for `client.p12` (default `changeit`). +- `OPENSSL=/path/to/openssl` โ€” override the OpenSSL binary. + +### 2. Run a Single Case + +```bash +# Baseline TLS 1.3 with valid SHA-384 OCSP staple (HttpsURLConnection) +./tools/tls-lab-repro/run_case.sh baseline-good-staple http -- \ + -status_file tools/tls-lab-repro/out/pki/good.der + +# TLS 1.3 ChaCha20-only (OkHttp) +./tools/tls-lab-repro/run_case.sh tls13-chacha-only okhttp3 -- \ + -tls1_3 -ciphersuites TLS_CHACHA20_POLY1305_SHA256 \ + -status_file tools/tls-lab-repro/out/pki/good.der + +# Mutual TLS with client PKCS#12 passed via EXTRA_EXTRAS +CLIENT_P12_B64="$(cat tools/tls-lab-repro/out/pki/client.p12.b64)" +EXTRA_EXTRAS="-e client_p12_b64 $CLIENT_P12_B64 -e client_p12_pass changeit" \ +./tools/tls-lab-repro/run_case.sh mtls-required-with-cert http -- \ + -Verify 1 -CAfile tools/tls-lab-repro/out/pki/client-ca.crt \ + -status_file tools/tls-lab-repro/out/pki/good.der +``` + +### 3. Run Session Resumption Tests + +```bash +# In-app repeat=2 against a single persistent s_server (recommended) +REPEAT=2 ./tools/tls-lab-repro/run_resumption.sh resumption-tls13 http -- \ + -status_file tools/tls-lab-repro/out/pki/good.der + +# Two sequential app launches against a single persistent s_server (TLS 1.2) +LAUNCHES=2 ./tools/tls-lab-repro/run_resumption.sh resumption-tls12 okhttp3 -- \ + -no_tls1_3 -status_file tools/tls-lab-repro/out/pki/good.der +``` + +### 4. Run the Full Matrix + +```bash +SERIAL= ./tools/tls-lab-repro/run_matrix.sh +``` + +`run_matrix.sh` automatically queries `adb shell getprop ro.build.version.sdk` on the target device and selects the matching expected profile: +- **API โ‰ค 36 (Android 16 and below)**: `expected_fixed_api36.tsv` (TLS 1.2 only; `baseline-good-staple` negotiates TLS 1.2, `tls13-chacha-only` and `tls13-aes128-only` fail with `protocol_version`, `resumption-repeat` resumes TLS 1.2). +- **API 37+ (Android 17 and above)**: `expected_fixed.tsv` (TLS 1.2 + TLS 1.3; `baseline-good-staple` negotiates TLS 1.3, `tls13-aes128-only` returns `200`, `tls13-chacha-only` fails on unapproved cipher selection). + +You can override the automatic selection with `EXPECTED=` (either `api36`, `api37`, or a path to a custom TSV file; `EXPECTED_FILE=` is also accepted as an alias): + +```bash +# Explicitly select the API <= 36 profile or a custom TSV +EXPECTED=api36 ./tools/tls-lab-repro/run_matrix.sh +EXPECTED=/path/to/custom.tsv ./tools/tls-lab-repro/run_matrix.sh +``` + +To verify the Android 16 (API โ‰ค 36) TLS 1.2 wire-capture OCSP path on an Android 17+ device (debuggable `validator-test-app` builds only), pass the test-only `force_tls12_wire` extra together with `EXPECTED=api36`: + +```bash +EXTRA_EXTRAS="-e force_tls12_wire true" EXPECTED=api36 ./tools/tls-lab-repro/run_matrix.sh +``` + +The selected profile and device API level are recorded at the top of `out/matrix_report.md`. The script exits `0` only if every case across both `http` and `okhttp3` matches the selected expected table. + +--- + +## Environment Variables + +| Variable | Default | Description | +|---|---|---| +| `OPENSSL` | `/opt/homebrew/bin/openssl` (or `openssl`) | OpenSSL binary path | +| `ADB` | `adb` | `adb` binary path | +| `SERIAL` | *(unset)* | Target device serial (`adb -s "$SERIAL"`) | +| `PORT` | `9443` | TCP port for `s_server` and `adb reverse` | +| `PKG` | `com.example.niap.cert.ext.testapp` | Installed test app package name | +| `OUT` | `tools/tls-lab-repro/out` | Root output directory for PKI, logs, and reports | +| `OCSP_DAYS` | `30` | OCSP staple validity in days (`gen_pki.sh`) | +| `P12_PASS` | `changeit` | Password for `client.p12` (`gen_pki.sh`, `run_matrix.sh`) | +| `EXTRA_EXTRAS` | *(empty)* | Additional `am start` flags forwarded by `run_case.sh` / `run_resumption.sh` | +| `REPEAT` | *(unset)* | In-app repeat count (`-e repeat N`) for `run_resumption.sh` | +| `LAUNCHES` | `2` (or `1` if `REPEAT` is set) | Sequential app launches for `run_resumption.sh` | +| `TYPES` | `http okhttp3` | Client stacks tested by `run_matrix.sh` | +| `EXPECTED` | *(auto-detected from `ro.build.version.sdk`)* | Override expected profile (`api36`, `api37`) or TSV path (`EXPECTED_FILE` is also supported as an alias) | + +--- + +## Reading Results + +- **One-line summary (`run_case.sh`)**: Tab-separated `key=value` fields: + ```text + case=baseline-good-staple type=http result=200 protocol=TLSv1.3 cipher=TLS_AES_128_GCM_SHA256 staple=yes detail=HTTP 200 + ``` +- **Per-connection resumption output (`run_resumption.sh`)**: One `conn=N` line per `ClientHello` showing `client_psk`, `client_ticket`, `client_sid`, `server_reused`, `protocol`, and `cipher`, followed by a final `case=...` summary line (`result=RESUMED` when all HTTP requests return `200` and at least one connection reused the session). +- **Raw logs**: Saved in `out/logs/..server.txt` (full OpenSSL `-trace`) and `out/logs/..client.txt` (PID-scoped `logcat -b main -b crash`). +- **Matrix report**: Written to `out/matrix_report.md`, listing expected vs. actual outcomes and `PASS`/`MISMATCH` status for every `(case, type)` pair. + +--- + +## Evaluation Lab Reuse Guide + +An independent NIAP evaluation lab can reuse this harness directly without modifying the Android platform or rebuilding the test app: + +1. **Install the submitted `validator-test-app` APK** on the target Android device and verify its SHA-256 hash. +2. **Establish `adb reverse tcp:9443 tcp:9443`** so the device reaches the lab's host OpenSSL server over USB without external network dependencies. +3. **Generate fresh PKI material** with `./tools/tls-lab-repro/gen_pki.sh` (or place lab-issued certificates and OCSP responses in `PKI_DIR` using the same filenames: `ca.b64`, `server.crt`, `server.key`, `good.der`, `revoked.der`, `badsigner.der`, `corrupt.der`, `good-sha256.der`, `client-ca.crt`, `client.p12.b64`). +4. **Execute `./tools/tls-lab-repro/run_matrix.sh`** to test all five evaluation areas across both `HttpsURLConnection` (`http`) and `OkHttp` (`okhttp3`): + - **TLS 1.3 / 1.2 cipher suite enforcement** (`tls13-chacha-only`, `tls13-aes128-only`, `tls12-chacha-only`, `tls12-approved`) + - **Stapled OCSP validation** (`baseline-good-staple`, `staple-revoked`, `staple-badsigner`, `staple-corrupt`, `staple-sha256`, `no-staple`) + - **Mutual TLS client authentication** (`mtls-required-no-cert`, `mtls-required-with-cert`) + - **Session resumption** (`resumption-repeat`) +5. **Archive `out/matrix_report.md` and `out/logs/`** as objective test evidence (both full TLS wire traces and device-side `NetworkWorker` logs are retained per test case). diff --git a/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/expected_fixed.tsv b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/expected_fixed.tsv new file mode 100644 index 0000000..ac0f170 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/expected_fixed.tsv @@ -0,0 +1,14 @@ +case s_server_args expected notes +baseline-good-staple -status_file {{PKI}}/good.der 200 Baseline TLS 1.3 handshake with valid SHA-384 OCSP staple +tls13-chacha-only -tls1_3 -ciphersuites TLS_CHACHA20_POLY1305_SHA256 -status_file {{PKI}}/good.der FAIL Library rejects server-selected ChaCha20-Poly1305 suite as not in NIAP allowlist +tls13-aes128-only -tls1_3 -ciphersuites TLS_AES_128_GCM_SHA256 -status_file {{PKI}}/good.der 200 AES-128-GCM currently on allowlist (note: policy may change) +tls12-chacha-only -no_tls1_3 -cipher ECDHE-ECDSA-CHACHA20-POLY1305 -status_file {{PKI}}/good.der FAIL Unapproved TLS 1.2 ChaCha20 suite rejected during handshake +tls12-approved -no_tls1_3 -cipher ECDHE-ECDSA-AES256-GCM-SHA384 -status_file {{PKI}}/good.der 200 Approved TLS 1.2 ECDHE-ECDSA-AES256-GCM-SHA384 suite with valid OCSP staple +staple-revoked -status_file {{PKI}}/revoked.der FAIL Stapled OCSP response reports certificate status revoked +staple-badsigner -status_file {{PKI}}/badsigner.der FAIL Stapled OCSP response signed by unauthorized key +staple-corrupt -status_file {{PKI}}/corrupt.der FAIL Stapled OCSP response has flipped signature byte (no embedded certs) +staple-sha256 -status_file {{PKI}}/good-sha256.der FAIL Stapled OCSP response signed with SHA-256 instead of approved SHA-384 +no-staple - FAIL Server omits OCSP staple; client must reject missing revocation status +mtls-required-no-cert -Verify 1 -CAfile {{PKI}}/client-ca.crt -status_file {{PKI}}/good.der FAIL Server requires client certificate (-Verify 1); none provided by client +mtls-required-with-cert -Verify 1 -CAfile {{PKI}}/client-ca.crt -status_file {{PKI}}/good.der 200 Server requires client certificate (-Verify 1); client presents valid P-384 client cert +resumption-repeat -status_file {{PKI}}/good.der RESUMED In-app repeat=2 against single s_server; second connection must resume session diff --git a/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/expected_fixed_api36.tsv b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/expected_fixed_api36.tsv new file mode 100644 index 0000000..b3336c1 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/expected_fixed_api36.tsv @@ -0,0 +1,14 @@ +case s_server_args expected notes +baseline-good-staple -status_file {{PKI}}/good.der 200 Baseline TLS 1.2 handshake with valid SHA-384 OCSP staple (API <= 36 TLS-1.2-only mode) +tls13-chacha-only -tls1_3 -ciphersuites TLS_CHACHA20_POLY1305_SHA256 -status_file {{PKI}}/good.der FAIL TLS 1.3-only server rejected (protocol_version); API <= 36 offers TLS 1.2 only +tls13-aes128-only -tls1_3 -ciphersuites TLS_AES_128_GCM_SHA256 -status_file {{PKI}}/good.der FAIL TLS 1.3-only server rejected (protocol_version); API <= 36 offers TLS 1.2 only +tls12-chacha-only -no_tls1_3 -cipher ECDHE-ECDSA-CHACHA20-POLY1305 -status_file {{PKI}}/good.der FAIL Unapproved TLS 1.2 ChaCha20 suite rejected during handshake +tls12-approved -no_tls1_3 -cipher ECDHE-ECDSA-AES256-GCM-SHA384 -status_file {{PKI}}/good.der 200 Approved TLS 1.2 ECDHE-ECDSA-AES256-GCM-SHA384 suite with valid OCSP staple +staple-revoked -status_file {{PKI}}/revoked.der FAIL Stapled OCSP response reports certificate status revoked +staple-badsigner -status_file {{PKI}}/badsigner.der FAIL Stapled OCSP response signed by unauthorized key +staple-corrupt -status_file {{PKI}}/corrupt.der FAIL Stapled OCSP response has flipped signature byte (no embedded certs) +staple-sha256 -status_file {{PKI}}/good-sha256.der FAIL Stapled OCSP response signed with SHA-256 instead of approved SHA-384 +no-staple - FAIL Server omits OCSP staple; client must reject missing revocation status +mtls-required-no-cert -Verify 1 -CAfile {{PKI}}/client-ca.crt -status_file {{PKI}}/good.der FAIL Server requires client certificate (-Verify 1); none provided by client +mtls-required-with-cert -Verify 1 -CAfile {{PKI}}/client-ca.crt -status_file {{PKI}}/good.der 200 Server requires client certificate (-Verify 1); client presents valid P-384 client cert (TLS 1.2) +resumption-repeat -status_file {{PKI}}/good.der RESUMED In-app repeat=2 against single s_server; second connection must resume TLS 1.2 session diff --git a/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/gen_pki.sh b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/gen_pki.sh new file mode 100755 index 0000000..06649a9 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/gen_pki.sh @@ -0,0 +1,154 @@ +#!/bin/bash +# Generates a NIAP-profile-compliant test PKI (P-384 / ecdsa-with-SHA384), +# stapled OCSP responses (good, revoked, badsigner, corrupt, sha256), and a +# client CA + client leaf PKCS#12 bundle for mutual TLS (mTLS) tests. +# +# Usage: +# gen_pki.sh [outdir] +# +# Environment variables: +# OPENSSL Path to OpenSSL binary (default: /opt/homebrew/bin/openssl if present, else openssl) +# OCSP_DAYS OCSP response validity in days (default: 30) +# P12_PASS Password for client.p12 (default: changeit) +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +DEFAULT_OPENSSL="/opt/homebrew/bin/openssl" +if [ -n "${OPENSSL:-}" ]; then + O="$OPENSSL" +elif [ -x "$DEFAULT_OPENSSL" ]; then + O="$DEFAULT_OPENSSL" +else + O="openssl" +fi + +if ! command -v "$O" >/dev/null 2>&1; then + echo "ERROR: OpenSSL binary not found: $O" >&2 + exit 1 +fi + +OCSP_DAYS="${OCSP_DAYS:-30}" +P12_PASS="${P12_PASS:-changeit}" +OUT_DIR="${1:-$SCRIPT_DIR/out/pki}" + +rm -rf "$OUT_DIR" +mkdir -p "$OUT_DIR" +OUT_DIR="$(cd "$OUT_DIR" && pwd)" +cd "$OUT_DIR" + +b64_single_line() { + base64 < "$1" | tr -d '\r\n' > "$2" +} + +# --- 1. Server Root CA (EC P-384, ecdsa-with-SHA384) --- +"$O" ecparam -name secp384r1 -genkey -noout -out ca.key +"$O" req -x509 -new -key ca.key -sha384 -days 3650 \ + -subj "/CN=NIAP Lab Repro Root CA" \ + -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" \ + -addext "subjectKeyIdentifier=hash" \ + -out ca.crt +"$O" x509 -in ca.crt -outform DER -out ca.der + +# --- 2. Server Leaf (NIAP-compliant: P-384, SHA-384, AKID/SKID, KU digitalSignature, EKU serverAuth, CA:FALSE) --- +"$O" ecparam -name secp384r1 -genkey -noout -out server.key +"$O" req -new -key server.key -subj "/CN=localhost" -out server.csr +cat > server.ext <<'EOF' +basicConstraints=critical,CA:FALSE +keyUsage=critical,digitalSignature +extendedKeyUsage=serverAuth +subjectKeyIdentifier=hash +authorityKeyIdentifier=keyid +subjectAltName=DNS:localhost,IP:127.0.0.1 +authorityInfoAccess=OCSP;URI:http://127.0.0.1:8888 +EOF +"$O" x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \ + -sha384 -days 365 -extfile server.ext -out server.crt + +# --- 3. Unauthorized OCSP Signer (for badsigner test) --- +"$O" ecparam -name secp384r1 -genkey -noout -out rogue.key +"$O" req -x509 -new -key rogue.key -sha384 -days 3650 \ + -subj "/CN=Rogue OCSP Signer" \ + -addext "basicConstraints=critical,CA:FALSE" \ + -addext "keyUsage=critical,digitalSignature" \ + -addext "extendedKeyUsage=OCSPSigning" \ + -addext "subjectKeyIdentifier=hash" \ + -out rogue.crt + +# --- 4. OCSP Responder Index Databases --- +SERVER_SERIAL="$("$O" x509 -in server.crt -noout -serial | cut -d= -f2)" +REV_DATE="$(date -u +%y%m%d%H%M%SZ)" +printf "V\t301231235959Z\t\t%s\tunknown\t/CN=localhost\n" "$SERVER_SERIAL" > index-good.txt +printf "R\t301231235959Z\t%s\t%s\tunknown\t/CN=localhost\n" "$REV_DATE" "$SERVER_SERIAL" > index-revoked.txt + +# --- 5. Stapled OCSP Responses --- +"$O" ocsp -issuer ca.crt -cert server.crt -no_nonce -reqout req.der + +# good: CA-signed with ecdsa-with-SHA384 +"$O" ocsp -reqin req.der -index index-good.txt -CA ca.crt \ + -rsigner ca.crt -rkey ca.key -rmd sha384 -ndays "$OCSP_DAYS" \ + -respout good.der + +# revoked: CA-signed with ecdsa-with-SHA384, status=revoked +"$O" ocsp -reqin req.der -index index-revoked.txt -CA ca.crt \ + -rsigner ca.crt -rkey ca.key -rmd sha384 -ndays "$OCSP_DAYS" \ + -respout revoked.der + +# badsigner: status=good, signed by unauthorized rogue key +"$O" ocsp -reqin req.der -index index-good.txt -CA ca.crt \ + -rsigner rogue.crt -rkey rogue.key -rmd sha384 -ndays "$OCSP_DAYS" \ + -respout badsigner.der + +# good-sha256: CA-signed with ecdsa-with-SHA256 (outside approved SHA-384 OCSP algorithm) +"$O" ocsp -reqin req.der -index index-good.txt -CA ca.crt \ + -rsigner ca.crt -rkey ca.key -rmd sha256 -ndays "$OCSP_DAYS" \ + -respout good-sha256.der + +# corrupt: CA-signed good response (no embedded certs) with last signature byte flipped +"$O" ocsp -reqin req.der -index index-good.txt -CA ca.crt \ + -rsigner ca.crt -rkey ca.key -rmd sha384 -ndays "$OCSP_DAYS" \ + -resp_no_certs -respout good-nocerts.der +python3 - <<'PYEOF' +with open('good-nocerts.der', 'rb') as f: + data = bytearray(f.read()) +data[-1] ^= 0x01 +with open('corrupt.der', 'wb') as f: + f.write(bytes(data)) +PYEOF + +# --- 6. Client CA + Client Leaf (mTLS) --- +"$O" ecparam -name secp384r1 -genkey -noout -out client-ca.key +"$O" req -x509 -new -key client-ca.key -sha384 -days 3650 \ + -subj "/CN=NIAP Lab Repro Client CA" \ + -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" \ + -addext "subjectKeyIdentifier=hash" \ + -out client-ca.crt +"$O" x509 -in client-ca.crt -outform DER -out client-ca.der + +"$O" ecparam -name secp384r1 -genkey -noout -out client.key +"$O" req -new -key client.key -subj "/CN=niap-test-client" -out client.csr +cat > client.ext <<'EOF' +basicConstraints=critical,CA:FALSE +keyUsage=critical,digitalSignature +extendedKeyUsage=clientAuth +subjectKeyIdentifier=hash +authorityKeyIdentifier=keyid +EOF +"$O" x509 -req -in client.csr -CA client-ca.crt -CAkey client-ca.key -CAcreateserial \ + -sha384 -days 365 -extfile client.ext -out client.crt + +"$O" pkcs12 -export \ + -inkey client.key \ + -in client.crt \ + -certfile client-ca.crt \ + -name "niap-test-client" \ + -passout "pass:$P12_PASS" \ + -out client.p12 + +# --- 7. Base64 Encodings for Intent Extras --- +b64_single_line ca.der ca.b64 +b64_single_line client-ca.der client-ca.b64 +b64_single_line client.p12 client.p12.b64 + +echo "PKI generated in $OUT_DIR (OpenSSL: $("$O" version), OCSP_DAYS=$OCSP_DAYS)" diff --git a/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/run_case.sh b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/run_case.sh new file mode 100755 index 0000000..c36d73a --- /dev/null +++ b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/run_case.sh @@ -0,0 +1,219 @@ +#!/bin/bash +# Runs a single TLS reproduction case: starts OpenSSL s_server with the given +# options, launches validator-test-app on the target Android device, collects +# PID-scoped logcat and server trace logs, and prints a one-line machine-parsable +# summary. +# +# Usage: +# run_case.sh [-- ] +# +# Environment variables: +# OPENSSL Path to OpenSSL binary (default: /opt/homebrew/bin/openssl if present, else openssl) +# ADB Path to adb binary (default: adb) +# SERIAL Android device serial (optional; uses default adb device if unset) +# PORT Localhost / adb-reverse TCP port (default: 9443) +# PKG Target app package (default: com.example.niap.cert.ext.testapp) +# ACTIVITY Target activity (default: .MainActivity) +# OUT Output root directory (default: /out) +# PKI_DIR PKI directory (default: $OUT/pki) +# LOG_DIR Log directory (default: $OUT/logs) +# EXTRA_EXTRAS Extra `am start` intent flags (e.g. "-e client_p12_b64 ... -e repeat 2") +# WAIT_STEPS Poll iterations of 0.5s waiting for NetworkWorker result (default: 20) +set -euo pipefail + +if [ "$#" -lt 2 ]; then + echo "Usage: $0 [-- ]" >&2 + exit 2 +fi + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +DEFAULT_OPENSSL="/opt/homebrew/bin/openssl" +if [ -n "${OPENSSL:-}" ]; then + O="$OPENSSL" +elif [ -x "$DEFAULT_OPENSSL" ]; then + O="$DEFAULT_OPENSSL" +else + O="openssl" +fi + +ADB="${ADB:-adb}" +SERIAL="${SERIAL:-}" +PORT="${PORT:-9443}" +PKG="${PKG:-com.example.niap.cert.ext.testapp}" +ACTIVITY="${ACTIVITY:-.MainActivity}" +OUT="${OUT:-$SCRIPT_DIR/out}" +PKI_DIR="${PKI_DIR:-$OUT/pki}" +LOG_DIR="${LOG_DIR:-$OUT/logs}" +EXTRA_EXTRAS="${EXTRA_EXTRAS:-}" +WAIT_STEPS="${WAIT_STEPS:-20}" + +NAME="$1" +TYPE="$2" +shift 2 +if [ "${1:-}" = "--" ]; then + shift +fi + +if [ ! -f "$PKI_DIR/server.crt" ] || [ ! -f "$PKI_DIR/server.key" ] || [ ! -f "$PKI_DIR/ca.b64" ]; then + echo "ERROR: PKI files not found in $PKI_DIR. Run gen_pki.sh first." >&2 + exit 1 +fi + +mkdir -p "$LOG_DIR" +SLOG="$LOG_DIR/$NAME.$TYPE.server.txt" +CLOG="$LOG_DIR/$NAME.$TYPE.client.txt" +HLOG="$LOG_DIR/$NAME.$TYPE.hiddenapi.txt" + +ADB_CMD=("$ADB") +if [ -n "$SERIAL" ]; then + ADB_CMD+=(-s "$SERIAL") +fi + +EXTRA_ARGS=() +if [ -n "$EXTRA_EXTRAS" ]; then + # Split EXTRA_EXTRAS respecting shell quoting. + eval "EXTRA_ARGS=($EXTRA_EXTRAS)" +fi + +run_to() { + local secs="$1" + shift + perl -e 'alarm shift; exec @ARGV' "$secs" "$@" +} + +SPID="" +cleanup() { + if [ -n "$SPID" ]; then + kill "$SPID" 2>/dev/null || true + wait "$SPID" 2>/dev/null || true + SPID="" + fi +} +trap cleanup EXIT + +pkill -f "s_server -accept $PORT" 2>/dev/null || true + +"$O" s_server -accept "$PORT" \ + -cert "$PKI_DIR/server.crt" \ + -key "$PKI_DIR/server.key" \ + -www -trace "$@" >"$SLOG" 2>&1 & +SPID=$! + +sleep 0.5 +if ! kill -0 "$SPID" 2>/dev/null; then + echo "[$NAME/$TYPE] ERROR: s_server exited early. See $SLOG" >&2 + cat "$SLOG" >&2 + exit 1 +fi + +CA_B64="$(tr -d '\r\n' < "$PKI_DIR/ca.b64")" +AM_ARGS=( + shell am start -S -W -n "$PKG/$ACTIVITY" + -e openurl "https://localhost:$PORT/" + -e type "$TYPE" + -e ca_b64 "$CA_B64" +) +if [ "${#EXTRA_ARGS[@]}" -gt 0 ]; then + AM_ARGS+=("${EXTRA_ARGS[@]}") +fi + +run_to 20 "${ADB_CMD[@]}" "${AM_ARGS[@]}" >/dev/null + +get_app_pid() { + run_to 10 "${ADB_CMD[@]}" shell pidof "$PKG" 2>/dev/null | tr -d '\r' | awk '{print $1}' || true +} + +APP_PID="$(get_app_pid)" +FOUND=0 +for _ in $(seq 1 "$WAIT_STEPS"); do + if [ -n "$APP_PID" ]; then + LOG_SNAP="$(run_to 10 "${ADB_CMD[@]}" shell "logcat -d -b main -b crash --pid=$APP_PID -v brief" 2>/dev/null || true)" + if printf '%s\n' "$LOG_SNAP" | grep -q -E "Response Code:|Connection failed|Worker result"; then + FOUND=1 + break + fi + else + APP_PID="$(get_app_pid)" + fi + sleep 0.5 +done + +sleep 0.5 +if [ -n "$APP_PID" ]; then + run_to 15 "${ADB_CMD[@]}" shell "logcat -d -b main -b crash --pid=$APP_PID -v brief" >"$CLOG" 2>&1 || true +else + echo "ERROR: could not obtain APP_PID for $PKG" >"$CLOG" +fi + +cleanup + +grep -i 'hiddenapi' "$CLOG" >"$HLOG" 2>/dev/null || true +HIDDEN_DENIED="$(grep -i -c 'denied' "$HLOG" 2>/dev/null || true)" +HIDDEN_WARN="$(grep -i -c 'Accessing hidden' "$HLOG" 2>/dev/null || true)" +HIDDEN_NIAP="$(grep -i 'Accessing hidden' "$HLOG" 2>/dev/null | grep -i -c -E 'com[/.](android|example)[/.]niap' || true)" +if [ "$HIDDEN_DENIED" -gt 0 ]; then + HIDDEN_SUMMARY="DENIED(denied=$HIDDEN_DENIED,warn=$HIDDEN_WARN,niap=$HIDDEN_NIAP)" +elif [ "$HIDDEN_WARN" -gt 0 ]; then + HIDDEN_SUMMARY="warn(total=$HIDDEN_WARN,niap=$HIDDEN_NIAP)" +else + HIDDEN_SUMMARY="ok" +fi + +CODE="$(grep -o -E "(OkHttp )?Response Code: [0-9]+" "$CLOG" | head -1 | awk '{print $NF}' || true)" +if [ -n "$CODE" ]; then + APP_RESULT="$CODE" + DETAIL="HTTP $CODE" +elif [ "$FOUND" -eq 0 ]; then + APP_RESULT="TIMEOUT" + DETAIL="no NetworkWorker result" +else + APP_RESULT="FAIL" + DETAIL="$(grep -A2 "Connection failed" "$CLOG" | tail -n +2 | head -2 | tr '\r\n\t' ' ' | sed -E 's/[A-Z]\/[A-Za-z0-9_.]+\( *[0-9]+\): //g; s/ +/ /g; s/^ //; s/ $//' | cut -c1-160 || true)" + if [ -z "$DETAIL" ]; then + DETAIL="Connection failed" + fi +fi + +if [ "$HIDDEN_DENIED" -gt 0 ]; then + APP_RESULT="HIDDENAPI_DENIED" + DETAIL="hiddenapi denied ($HIDDEN_DENIED); $DETAIL" +fi + +TRACE_SUMMARY="$(python3 - "$SLOG" <<'PYEOF' +import re, sys + +text = open(sys.argv[1], 'r', errors='replace').read() +proto = "none" +cipher = "none" +staple = "no" + +m_sh = re.search(r'ServerHello, Length=\d+\n(.*?)(?=\n(?:Sent|Received)\s+(?:TLS\s+)?Record|\Z)', text, re.S) +if m_sh: + sh = m_sh.group(1) + m_cs = re.search(r'cipher_suite\s+\{[^}]+\}\s+(\S+)', sh) + if m_cs: + cipher = m_cs.group(1) + if re.search(r'extension_type=supported_versions\(43\).*?TLS 1\.3', sh, re.S): + proto = "TLSv1.3" + elif re.search(r'server_version=0x303\s*\(TLS 1\.2\)', sh): + proto = "TLSv1.2" + else: + m_v = re.search(r'server_version=\S+\s*\(([^)]+)\)', sh) + if m_v: + proto = m_v.group(1).replace(" ", "") + +if "CertificateStatus" in text: + staple = "yes" +else: + for m_sr in re.finditer(r'extension_type=status_request\(5\),\s*length=(\d+)', text): + if int(m_sr.group(1)) > 5: + staple = "yes" + break + +print(f"{proto}\t{cipher}\t{staple}") +PYEOF +)" + +IFS=$'\t' read -r PROTO CIPHER STAPLE <<< "$TRACE_SUMMARY" +printf 'case=%s\ttype=%s\tresult=%s\tprotocol=%s\tcipher=%s\tstaple=%s\thiddenapi=%s\tdetail=%s\n' \ + "$NAME" "$TYPE" "$APP_RESULT" "$PROTO" "$CIPHER" "$STAPLE" "$HIDDEN_SUMMARY" "$DETAIL" diff --git a/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/run_matrix.sh b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/run_matrix.sh new file mode 100755 index 0000000..16d0e51 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/run_matrix.sh @@ -0,0 +1,219 @@ +#!/bin/bash +# Runs the full TLS reproduction matrix across both HTTP stacks (http, okhttp3), +# compares each result against the expected TSV for the device's Android API +# level (expected_fixed_api36.tsv for API <= 36, expected_fixed.tsv for API 37+), +# and writes a Markdown report to $OUT/matrix_report.md. +# +# Usage: +# run_matrix.sh +# +# Environment variables: +# TYPES Space-separated client types (default: "http okhttp3") +# EXPECTED Override expected profile ("api36", "api37") or TSV file path +# (default: auto-selected from adb shell getprop ro.build.version.sdk) +# EXPECTED_FILE Alias for EXPECTED (file path or profile name) +# OUT Output directory (default: /out) +# PKI_DIR PKI directory (default: $OUT/pki) +# REPORT_FILE Markdown report path (default: $OUT/matrix_report.md) +# P12_PASS PKCS#12 password for mTLS cases (default: changeit) +# MTLS_EXTRA_EXTRAS Override intent extras for mtls-required-with-cert +# RESUMPTION_REPEAT In-app repeat count for resumption-* cases (default: 2) +# SERIAL, PORT, PKG, OPENSSL, ADB Forwarded to run_case.sh / run_resumption.sh +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +ADB="${ADB:-adb}" +SERIAL="${SERIAL:-}" +OUT="${OUT:-$SCRIPT_DIR/out}" +PKI_DIR="${PKI_DIR:-$OUT/pki}" +LOG_DIR="${LOG_DIR:-$OUT/logs}" +REPORT_FILE="${REPORT_FILE:-$OUT/matrix_report.md}" +TYPES="${TYPES:-http okhttp3}" +P12_PASS="${P12_PASS:-changeit}" +RESUMPTION_REPEAT="${RESUMPTION_REPEAT:-2}" + +export OUT PKI_DIR LOG_DIR P12_PASS + +ADB_CMD=("$ADB") +if [ -n "$SERIAL" ]; then + ADB_CMD+=(-s "$SERIAL") +fi + +run_to() { + local secs="$1" + shift + perl -e 'alarm shift; exec @ARGV' "$secs" "$@" +} + +DEVICE_SDK="$(run_to 10 "${ADB_CMD[@]}" shell getprop ro.build.version.sdk 2>/dev/null | tr -d '\r\n ' || true)" +EXPECTED_OVERRIDE="${EXPECTED:-${EXPECTED_FILE:-}}" + +if [ -n "$EXPECTED_OVERRIDE" ]; then + case "$EXPECTED_OVERRIDE" in + api36) + EXPECTED_FILE="$SCRIPT_DIR/expected_fixed_api36.tsv" + EXPECTED_PROFILE="api36 (override; TLS 1.2 only)" + ;; + api37|api37+|default) + EXPECTED_FILE="$SCRIPT_DIR/expected_fixed.tsv" + EXPECTED_PROFILE="api37+ (override; TLS 1.2 + 1.3)" + ;; + *) + EXPECTED_FILE="$EXPECTED_OVERRIDE" + EXPECTED_PROFILE="custom override ($(basename "$EXPECTED_FILE"))" + ;; + esac +else + case "$DEVICE_SDK" in + ''|*[!0-9]*) + echo "WARNING: Could not detect device SDK via adb getprop ro.build.version.sdk (got '${DEVICE_SDK:-}'); defaulting to expected_fixed.tsv (API 37+ profile)." >&2 + EXPECTED_FILE="$SCRIPT_DIR/expected_fixed.tsv" + EXPECTED_PROFILE="api37+ (fallback; SDK detection failed)" + ;; + *) + if [ "$DEVICE_SDK" -le 36 ]; then + EXPECTED_FILE="$SCRIPT_DIR/expected_fixed_api36.tsv" + EXPECTED_PROFILE="api36 (auto-detected SDK $DEVICE_SDK <= 36; TLS 1.2 only)" + else + EXPECTED_FILE="$SCRIPT_DIR/expected_fixed.tsv" + EXPECTED_PROFILE="api37+ (auto-detected SDK $DEVICE_SDK >= 37; TLS 1.2 + 1.3)" + fi + ;; + esac +fi + +if [ ! -f "$EXPECTED_FILE" ]; then + echo "ERROR: Expected matrix file not found: $EXPECTED_FILE" >&2 + exit 1 +fi + +echo "Using expected profile: $EXPECTED_PROFILE ($EXPECTED_FILE)" + +if [ ! -f "$PKI_DIR/ca.b64" ] || [ ! -f "$PKI_DIR/client.p12.b64" ]; then + echo "PKI not found in $PKI_DIR; generating with gen_pki.sh..." + "$SCRIPT_DIR/gen_pki.sh" "$PKI_DIR" +fi + +mkdir -p "$OUT" "$LOG_DIR" + +CLIENT_P12_B64="$(tr -d '\r\n' < "$PKI_DIR/client.p12.b64")" +DEFAULT_MTLS_EXTRAS="-e client_p12_b64 $CLIENT_P12_B64 -e client_p12_pass $P12_PASS" + +TMP_ROWS="$(mktemp)" +trap 'rm -f "$TMP_ROWS"' EXIT + +TOTAL=0 +PASSED=0 +MISMATCHED=0 + +extract_field() { + local line="$1" + local key="$2" + printf '%s\n' "$line" | tr '\t' '\n' | awk -F= -v k="$key" '$1 == k { sub(/^[^=]*=/, ""); print; exit }' +} + +escape_md() { + printf '%s' "$1" | sed 's/|/\\|/g' +} + +LINE_NO=0 +while IFS=$'\t' read -r CASE ARGS_TMPL EXPECTED NOTES <&3; do + LINE_NO=$((LINE_NO + 1)) + [ "$LINE_NO" -eq 1 ] && continue + [ -z "${CASE:-}" ] && continue + case "$CASE" in + \#*) continue ;; + esac + + S_ARGS=() + if [ -n "${ARGS_TMPL:-}" ] && [ "$ARGS_TMPL" != "-" ]; then + ARGS_EXPANDED="${ARGS_TMPL//\{\{PKI\}\}/$PKI_DIR}" + eval "S_ARGS=($ARGS_EXPANDED)" + fi + + for TYPE in $TYPES; do + TOTAL=$((TOTAL + 1)) + SUMMARY="" + STAPLE_OR_RESUMED="n/a" + + if [[ "$CASE" == resumption-* ]]; then + RES_OUT="$(REPEAT="$RESUMPTION_REPEAT" "$SCRIPT_DIR/run_resumption.sh" "$CASE" "$TYPE" -- ${S_ARGS[@]+"${S_ARGS[@]}"} "$LOG_DIR/$CASE.$TYPE.resumption.txt" + SUMMARY="$(printf '%s\n' "$RES_OUT" | grep '^case=' | tail -1 || true)" + STAPLE_OR_RESUMED="resumed=$(extract_field "$SUMMARY" resumed)" + else + CASE_EXTRA="${EXTRA_EXTRAS:-}" + if [ "$CASE" = "mtls-required-with-cert" ]; then + MTLS_PART="${MTLS_EXTRA_EXTRAS:-$DEFAULT_MTLS_EXTRAS}" + if [ -n "$CASE_EXTRA" ]; then + CASE_EXTRA="$CASE_EXTRA $MTLS_PART" + else + CASE_EXTRA="$MTLS_PART" + fi + fi + SUMMARY="$(EXTRA_EXTRAS="$CASE_EXTRA" "$SCRIPT_DIR/run_case.sh" "$CASE" "$TYPE" -- ${S_ARGS[@]+"${S_ARGS[@]}"} > "$TMP_ROWS" + done +done 3< "$EXPECTED_FILE" + +{ + echo "# TLS Lab Reproduction Matrix Report" + echo "" + echo "- **Generated (UTC)**: $(date -u '+%Y-%m-%d %H:%M:%S UTC')" + echo "- **Device API Level**: \`${DEVICE_SDK:-unknown}\`" + echo "- **Expected Profile**: \`$EXPECTED_PROFILE\`" + echo "- **Expected Table**: \`$EXPECTED_FILE\`" + echo "- **Device Serial**: \`${SERIAL:-}\`" + echo "- **Port**: \`${PORT:-9443}\`" + echo "- **Target Package**: \`${PKG:-com.example.niap.cert.ext.testapp}\`" + echo "- **Summary**: **$PASSED / $TOTAL matched** ($MISMATCHED mismatched)" + echo "" + echo "| Case | Type | Expected | Actual | Match | Protocol | Cipher | Staple / Resumed | HiddenAPI | Detail | Notes |" + echo "|---|---|---|---|---|---|---|---|---|---|---|" + cat "$TMP_ROWS" +} > "$REPORT_FILE" + +echo "" +echo "Matrix complete: $PASSED/$TOTAL matched ($MISMATCHED mismatched)." +echo "Report written to: $REPORT_FILE" + +if [ "$MISMATCHED" -gt 0 ]; then + exit 1 +fi diff --git a/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/run_resumption.sh b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/run_resumption.sh new file mode 100755 index 0000000..52f1d01 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/tools/tls-lab-repro/run_resumption.sh @@ -0,0 +1,318 @@ +#!/bin/bash +# Runs a TLS session resumption test against a single persistent OpenSSL s_server, +# supporting either multiple sequential app launches (LAUNCHES=N) or an in-app +# repeat count (REPEAT=N passed via `-e repeat N`). +# +# Reports per-connection ClientHello resumption offers (pre_shared_key, +# session_ticket, session_id) and whether the server reported session reuse, +# followed by a machine-parsable summary line. +# +# Usage: +# run_resumption.sh [-- ] +# +# Environment variables: +# OPENSSL Path to OpenSSL binary (default: /opt/homebrew/bin/openssl if present, else openssl) +# ADB Path to adb binary (default: adb) +# SERIAL Android device serial (optional; uses default adb device if unset) +# PORT Localhost / adb-reverse TCP port (default: 9443) +# PKG Target app package (default: com.example.niap.cert.ext.testapp) +# ACTIVITY Target activity (default: .MainActivity) +# OUT Output root directory (default: /out) +# PKI_DIR PKI directory (default: $OUT/pki) +# LOG_DIR Log directory (default: $OUT/logs) +# REPEAT In-app repeat count passed as `-e repeat ` (optional; overrides default LAUNCHES=2 to LAUNCHES=1) +# LAUNCHES Number of sequential `am start -S -W` runs (default: 1 if REPEAT set, else 2) +# EXTRA_EXTRAS Additional `am start` intent flags +# WAIT_STEPS Poll iterations of 0.5s per launch (default: 30) +set -euo pipefail + +if [ "$#" -lt 2 ]; then + echo "Usage: $0 [-- ]" >&2 + exit 2 +fi + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +DEFAULT_OPENSSL="/opt/homebrew/bin/openssl" +if [ -n "${OPENSSL:-}" ]; then + O="$OPENSSL" +elif [ -x "$DEFAULT_OPENSSL" ]; then + O="$DEFAULT_OPENSSL" +else + O="openssl" +fi + +ADB="${ADB:-adb}" +SERIAL="${SERIAL:-}" +PORT="${PORT:-9443}" +PKG="${PKG:-com.example.niap.cert.ext.testapp}" +ACTIVITY="${ACTIVITY:-.MainActivity}" +OUT="${OUT:-$SCRIPT_DIR/out}" +PKI_DIR="${PKI_DIR:-$OUT/pki}" +LOG_DIR="${LOG_DIR:-$OUT/logs}" +REPEAT="${REPEAT:-}" +if [ -n "$REPEAT" ]; then + LAUNCHES="${LAUNCHES:-1}" + MODE="repeat:$REPEAT" +else + LAUNCHES="${LAUNCHES:-2}" + MODE="launches:$LAUNCHES" +fi +EXTRA_EXTRAS="${EXTRA_EXTRAS:-}" +WAIT_STEPS="${WAIT_STEPS:-30}" + +NAME="$1" +TYPE="$2" +shift 2 +if [ "${1:-}" = "--" ]; then + shift +fi + +if [ ! -f "$PKI_DIR/server.crt" ] || [ ! -f "$PKI_DIR/server.key" ] || [ ! -f "$PKI_DIR/ca.b64" ]; then + echo "ERROR: PKI files not found in $PKI_DIR. Run gen_pki.sh first." >&2 + exit 1 +fi + +mkdir -p "$LOG_DIR" +SLOG="$LOG_DIR/$NAME.$TYPE.server.txt" +CLOG="$LOG_DIR/$NAME.$TYPE.client.txt" +HLOG="$LOG_DIR/$NAME.$TYPE.hiddenapi.txt" +: > "$CLOG" + +ADB_CMD=("$ADB") +if [ -n "$SERIAL" ]; then + ADB_CMD+=(-s "$SERIAL") +fi + +EXTRA_ARGS=() +if [ -n "$EXTRA_EXTRAS" ]; then + eval "EXTRA_ARGS=($EXTRA_EXTRAS)" +fi +if [ -n "$REPEAT" ]; then + EXTRA_ARGS+=(-e repeat "$REPEAT") +fi + +run_to() { + local secs="$1" + shift + perl -e 'alarm shift; exec @ARGV' "$secs" "$@" +} + +SPID="" +cleanup() { + if [ -n "$SPID" ]; then + kill "$SPID" 2>/dev/null || true + wait "$SPID" 2>/dev/null || true + SPID="" + fi + pkill -f "s_server -accept $PORT" 2>/dev/null || true +} +trap cleanup EXIT + +pkill -f "s_server -accept $PORT" 2>/dev/null || true + +# Use a PTY (macOS `script`) or `stdbuf -oL` so s_server -trace flushes line-by-line +# instead of block-buffering 4 KB and truncating the final connection's trace on exit. +if command -v stdbuf >/dev/null 2>&1; then + stdbuf -oL "$O" s_server -accept "$PORT" \ + -cert "$PKI_DIR/server.crt" \ + -key "$PKI_DIR/server.key" \ + -www -trace "$@" >"$SLOG" 2>&1 & +elif [ "$(uname -s)" = "Darwin" ] && command -v script >/dev/null 2>&1; then + script -q /dev/null "$O" s_server -accept "$PORT" \ + -cert "$PKI_DIR/server.crt" \ + -key "$PKI_DIR/server.key" \ + -www -trace "$@" >"$SLOG" 2>&1 & +else + "$O" s_server -accept "$PORT" \ + -cert "$PKI_DIR/server.crt" \ + -key "$PKI_DIR/server.key" \ + -www -trace "$@" >"$SLOG" 2>&1 & +fi +SPID=$! + +sleep 0.5 +if ! kill -0 "$SPID" 2>/dev/null; then + echo "[$NAME/$TYPE] ERROR: s_server exited early. See $SLOG" >&2 + cat "$SLOG" >&2 + exit 1 +fi + +get_app_pid() { + run_to 10 "${ADB_CMD[@]}" shell pidof "$PKG" 2>/dev/null | tr -d '\r' | awk '{print $1}' || true +} + +CA_B64="$(tr -d '\r\n' < "$PKI_DIR/ca.b64")" +EXPECTED_RESPONSES_PER_LAUNCH="${REPEAT:-1}" +ALL_FOUND=1 + +for RUN in $(seq 1 "$LAUNCHES"); do + AM_ARGS=( + shell am start -S -W -n "$PKG/$ACTIVITY" + -e openurl "https://localhost:$PORT/" + -e type "$TYPE" + -e ca_b64 "$CA_B64" + ) + if [ "${#EXTRA_ARGS[@]}" -gt 0 ]; then + AM_ARGS+=("${EXTRA_ARGS[@]}") + fi + + run_to 20 "${ADB_CMD[@]}" "${AM_ARGS[@]}" >/dev/null + + APP_PID="$(get_app_pid)" + RUN_FOUND=0 + for _ in $(seq 1 "$WAIT_STEPS"); do + if [ -n "$APP_PID" ]; then + LOG_SNAP="$(run_to 10 "${ADB_CMD[@]}" shell "logcat -d -b main -b crash --pid=$APP_PID -v brief" 2>/dev/null || true)" + RESP_CNT="$(printf '%s\n' "$LOG_SNAP" | grep -c -E "(OkHttp )?Response Code: [0-9]+" || true)" + FAIL_CNT="$(printf '%s\n' "$LOG_SNAP" | grep -c -E "Connection failed" || true)" + if [ "$((RESP_CNT + FAIL_CNT))" -ge "$EXPECTED_RESPONSES_PER_LAUNCH" ] || [ "$FAIL_CNT" -ge 1 ]; then + RUN_FOUND=1 + break + fi + else + APP_PID="$(get_app_pid)" + fi + sleep 0.5 + done + + if [ "$RUN_FOUND" -eq 0 ]; then + ALL_FOUND=0 + fi + + sleep 0.5 + { + echo "=== RUN $RUN (PID=${APP_PID:-unknown}) ===" + if [ -n "$APP_PID" ]; then + run_to 15 "${ADB_CMD[@]}" shell "logcat -d -b main -b crash --pid=$APP_PID -v brief" 2>&1 || true + else + echo "ERROR: could not obtain APP_PID for $PKG" + fi + } >> "$CLOG" +done + +cleanup + +grep -i 'hiddenapi' "$CLOG" >"$HLOG" 2>/dev/null || true + +python3 - "$SLOG" "$CLOG" "$HLOG" "$NAME" "$TYPE" "$MODE" "$ALL_FOUND" <<'PYEOF' +import re, sys + +slog_path, clog_path, hlog_path, name, rtype, mode, all_found = sys.argv[1:8] +stext = open(slog_path, 'r', errors='replace').read() +ctext = open(clog_path, 'r', errors='replace').read() +hlines = [l for l in open(hlog_path, 'r', errors='replace').read().splitlines() if l.strip()] +hidden_denied = sum(1 for l in hlines if 'denied' in l.lower()) +hidden_warn = sum(1 for l in hlines if 'accessing hidden' in l.lower()) +hidden_niap = sum(1 for l in hlines if 'accessing hidden' in l.lower() and re.search(r'com[/.](android|example)[/.]niap', l, re.I)) +if hidden_denied > 0: + hidden_summary = f"DENIED(denied={hidden_denied},warn={hidden_warn},niap={hidden_niap})" +elif hidden_warn > 0: + hidden_summary = f"warn(total={hidden_warn},niap={hidden_niap})" +else: + hidden_summary = "ok" + +# Split trace into per-connection segments starting at each ClientHello. +positions = [m.start() for m in re.finditer(r'ClientHello, Length=\d+', stext)] +segments = [] +for i, pos in enumerate(positions): + end = positions[i + 1] if i + 1 < len(positions) else len(stext) + segments.append(stext[pos:end]) + +prev_server_sids = set() +any_reused = False +nst_total = len(re.findall(r'NewSessionTicket, Length=\d+', stext)) +first_proto = "none" +first_cipher = "none" + +for idx, seg in enumerate(segments, 1): + # Isolate ClientHello and ServerHello blocks within this connection segment. + m_ch = re.match(r'(ClientHello, Length=\d+\n.*?)(?=\n(?:Sent|Received)\s+(?:TLS\s+)?Record|\Z)', seg, re.S) + ch = m_ch.group(1) if m_ch else seg + + m_sh = re.search(r'(ServerHello, Length=\d+\n.*?)(?=\n(?:Sent|Received)\s+(?:TLS\s+)?Record|\Z)', seg, re.S) + sh = m_sh.group(1) if m_sh else "" + + # ClientHello offers (OpenSSL 3.x prints pre_shared_key(41); OpenSSL 4.x prints psk(41)) + psk = "yes" if re.search(r'extension_type=(?:pre_shared_key|psk)\(41\)', ch) else "no" + + m_tkt = re.search(r'extension_type=session_ticket\(35\),\s*length=(\d+)', ch) + if not m_tkt: + ticket = "no" + elif int(m_tkt.group(1)) == 0: + ticket = "empty(len=0)" + else: + ticket = f"yes(len={m_tkt.group(1)})" + + m_csid = re.search(r'session_id\s*\(len=(\d+)\):(?:\s*([0-9A-Fa-f]+))?', ch) + if m_csid: + csid_len = int(m_csid.group(1)) + csid_hex = (m_csid.group(2) or "").strip() + matched_prev = "yes" if (csid_len > 0 and csid_hex in prev_server_sids) else "no" + sid_info = f"len={csid_len},matched_prev={matched_prev}" + else: + sid_info = "len=0,matched_prev=no" + + # ServerHello protocol, cipher, and session_id + proto = "none" + cipher = "none" + if sh: + m_cs = re.search(r'cipher_suite\s+\{[^}]+\}\s+(\S+)', sh) + if m_cs: + cipher = m_cs.group(1) + if re.search(r'extension_type=supported_versions\(43\).*?TLS 1\.3', sh, re.S): + proto = "TLSv1.3" + elif re.search(r'server_version=0x303\s*\(TLS 1\.2\)', sh): + proto = "TLSv1.2" + m_ssid = re.search(r'session_id\s*\(len=(\d+)\):(?:\s*([0-9A-Fa-f]+))?', sh) + if m_ssid and int(m_ssid.group(1)) > 0 and m_ssid.group(2): + prev_server_sids.add(m_ssid.group(2).strip()) + + if idx == 1: + first_proto, first_cipher = proto, cipher + + # Detect server-reported reuse: + # 1) Explicit "Reused," line from s_server + # 2) TLS 1.3 ServerHello includes extension_type=pre_shared_key(41) / psk(41) + # 3) TLS 1.2 abbreviated handshake: ServerHello present, Finished sent, no Certificate sent + reused = False + if "Reused," in seg: + reused = True + elif re.search(r'extension_type=(?:pre_shared_key|psk)\(41\)', sh): + reused = True + elif sh and "Finished," in seg and not re.search(r'\bCertificate,\s*Length=', seg): + reused = True + + if reused: + any_reused = True + + print( + f"conn={idx}\tclient_psk={psk}\tclient_ticket={ticket}\t" + f"client_sid={sid_info}\tserver_reused={'yes' if reused else 'no'}\t" + f"protocol={proto}\tcipher={cipher}" + ) + +codes = re.findall(r'(?:OkHttp )?Response Code: (\d+)', ctext) +fails = len(re.findall(r'Connection failed', ctext)) + +if fails > 0: + result = "FAIL" +elif all_found == "0" and not codes: + result = "TIMEOUT" +elif any_reused and len(codes) >= 2 and all(c == "200" for c in codes): + result = "RESUMED" +elif codes and all(c == "200" for c in codes): + result = "200" +else: + result = "FAIL" + +detail = f"codes={','.join(codes) if codes else 'none'} fails={fails}" +if hidden_denied > 0: + result = "HIDDENAPI_DENIED" + detail = f"hiddenapi denied ({hidden_denied}); {detail}" +print( + f"case={name}\ttype={rtype}\tmode={mode}\tresult={result}\t" + f"protocol={first_proto}\tcipher={first_cipher}\tconnections={len(segments)}\t" + f"new_session_tickets={nst_total}\tresumed={'yes' if any_reused else 'no'}\t" + f"hiddenapi={hidden_summary}\tdetail={detail}" +) +PYEOF diff --git a/niap-cc/niap-android-cert-ext/validator-test-app/build.gradle.kts b/niap-cc/niap-android-cert-ext/validator-test-app/build.gradle.kts new file mode 100644 index 0000000..fd16ee3 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/validator-test-app/build.gradle.kts @@ -0,0 +1,145 @@ +/* + * Copyright 2026 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. + */ + +import java.io.File +import java.time.Instant +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +val gitShortSha: String = run { + val gitMarker = File(rootDir, ".git") + if (!gitMarker.exists()) { + "unknown" + } else { + try { + val proc = ProcessBuilder("git", "rev-parse", "--short", "HEAD") + .directory(rootDir) + .redirectErrorStream(true) + .start() + val out = proc.inputStream.bufferedReader().readText().trim() + if (proc.waitFor() == 0 && out.isNotEmpty()) out else "unknown" + } catch (_: Exception) { + "unknown" + } + } +} + +val buildTimestamp: String = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'") + .withZone(ZoneOffset.UTC) + .format(Instant.now()) + +android { + namespace = "com.example.niap.cert.ext.testapp" + compileSdk = 34 + + defaultConfig { + applicationId = "com.example.niap.cert.ext.testapp" + minSdk = 32 + targetSdk = 34 + versionCode = 2 + versionName = "1.1.0" + + buildConfigField("String", "BUILD_TIME", "\"$buildTimestamp\"") + buildConfigField("String", "GIT_SHA", "\"$gitShortSha\"") + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildFeatures { + buildConfig = true + viewBinding = true + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + flavorDimensions.add("mode") + productFlavors { + create("strict") { + dimension = "mode" + } + create("relaxed") { + dimension = "mode" + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = "1.8" + } + lint { + error += setOf( + "PrivateApi", + "DiscouragedPrivateApi", + "SoonBlockedPrivateApi", + "BlockedPrivateApi" + ) + abortOnError = true + } +} + +dependencies { + implementation(project(":cert-lib")) + implementation("androidx.core:core-ktx:1.12.0") + implementation("androidx.appcompat:appcompat:1.6.1") + implementation("androidx.work:work-runtime-ktx:2.9.0") + implementation("com.squareup.okhttp3:okhttp:4.12.0") +} + +val testbedRoot = gradle.extra["testbedRoot"] as File +val skipTestbedCopy = providers.gradleProperty("skipTestbedCopy") + .map { it.isEmpty() || it.equals("true", ignoreCase = true) } + .getOrElse(false) + +tasks.register("copyApkToCore") { + description = "Copies the generated APKs to the TestBed Core resources directory." + enabled = !skipTestbedCopy + onlyIf { !skipTestbedCopy } + + from(layout.buildDirectory.dir("outputs/apk")) + include("**/*-debug.apk") + val coreResourcesDir = File(testbedRoot, "testbed-core/composeApp/resources") + into(coreResourcesDir) + eachFile { + path = name + } + includeEmptyDirs = false + doFirst { + coreResourcesDir.mkdirs() + } + doLast { + println("โœ… APKs copied to: ${coreResourcesDir.absolutePath}") + } +} + +if (!skipTestbedCopy) { + tasks.configureEach { + if (name == "assemble" || name == "assembleDebug" || name.startsWith("assemble")) { + finalizedBy("copyApkToCore") + } + } +} diff --git a/niap-cc/niap-android-cert-ext/validator-test-app/src/main/AndroidManifest.xml b/niap-cc/niap-android-cert-ext/validator-test-app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..918d672 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/validator-test-app/src/main/AndroidManifest.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + diff --git a/niap-cc/niap-android-cert-ext/validator-test-app/src/main/kotlin/com/example/niap/cert/ext/testapp/MainActivity.kt b/niap-cc/niap-android-cert-ext/validator-test-app/src/main/kotlin/com/example/niap/cert/ext/testapp/MainActivity.kt new file mode 100644 index 0000000..2cb1344 --- /dev/null +++ b/niap-cc/niap-android-cert-ext/validator-test-app/src/main/kotlin/com/example/niap/cert/ext/testapp/MainActivity.kt @@ -0,0 +1,101 @@ +/* + * Copyright 2026 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. + */ + +package com.example.niap.cert.ext.testapp + +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import android.util.Log +import androidx.work.Data +import androidx.work.OneTimeWorkRequest +import androidx.work.WorkManager +import com.android.niap.cert.validator.NiapCertValidator + +class MainActivity : AppCompatActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + setContentView(android.R.layout.simple_list_item_1) + + val textView = findViewById(android.R.id.text1) + + val url = intent.getStringExtra("openurl") ?: "https://www.google.com" + val type = intent.getStringExtra("type") ?: "http" + val caB64 = intent.getStringExtra("ca_b64") + val clientP12B64 = intent.getStringExtra("client_p12_b64") + val clientP12Pass = intent.getStringExtra("client_p12_pass") ?: "changeit" + val repeat = (intent.getStringExtra("repeat")?.toIntOrNull() + ?: intent.getIntExtra("repeat", 1)).coerceAtLeast(1) + val forceTls12Wire = intent.getBooleanExtra("force_tls12_wire", false) || + intent.getStringExtra("force_tls12_wire")?.let { + it.equals("true", ignoreCase = true) || it == "1" + } == true + val buildId = "v${BuildConfig.VERSION_NAME} (${BuildConfig.GIT_SHA}, ${BuildConfig.BUILD_TIME})" + Log.i("TestApp", "Build: $buildId") + Log.d("TestApp", "Build Time: ${BuildConfig.BUILD_TIME}") + if (forceTls12Wire) { + Log.w("TestApp", "TEST MODE: forcing TLS 1.2 wire-capture OCSP path") + } + Log.d( + "TestApp", + "URL to test: $url with type: $type repeat=$repeat " + + "forceTls12Wire=$forceTls12Wire " + + "hasCa=${!caB64.isNullOrEmpty()} hasClientCert=${!clientP12B64.isNullOrEmpty()}" + ) + + val modeBanner = if (forceTls12Wire) "\nTEST MODE: forcing TLS 1.2 wire-capture OCSP path" else "" + textView.text = "Build: $buildId$modeBanner\nTesting $url using $type (repeat=$repeat)..." + + val dataBuilder = Data.Builder() + .putString("url", url) + .putString("type", type) + .putInt("repeat", repeat) + .putBoolean("force_tls12_wire", forceTls12Wire) + if (!caB64.isNullOrEmpty()) { + dataBuilder.putString("ca_b64", caB64) + } + if (!clientP12B64.isNullOrEmpty()) { + dataBuilder.putString("client_p12_b64", clientP12B64) + dataBuilder.putString("client_p12_pass", clientP12Pass) + } + val data = dataBuilder.build() + + val workRequest = OneTimeWorkRequest.Builder(NetworkWorker::class.java) + .setInputData(data) + .build() + + Log.d("TestApp", "Enqueuing NetworkWorker...") + val workManager = WorkManager.getInstance(applicationContext) + workManager.cancelAllWork() + workManager.enqueue(workRequest) + + workManager.getWorkInfoByIdLiveData(workRequest.id) + .observe(this) { workInfo -> + if (workInfo != null) { + if (workInfo.state.isFinished) { + val status = workInfo.state.name + val error = workInfo.outputData.getString("error") + if (error != null) { + textView.text = "Build: $buildId$modeBanner\nResult: $status\nError: $error" + } else { + textView.text = "Build: $buildId$modeBanner\nResult: $status" + } + } + } + } + } +} diff --git a/niap-cc/niap-android-cert-ext/validator-test-app/src/main/kotlin/com/example/niap/cert/ext/testapp/NetworkWorker.kt b/niap-cc/niap-android-cert-ext/validator-test-app/src/main/kotlin/com/example/niap/cert/ext/testapp/NetworkWorker.kt new file mode 100644 index 0000000..812650a --- /dev/null +++ b/niap-cc/niap-android-cert-ext/validator-test-app/src/main/kotlin/com/example/niap/cert/ext/testapp/NetworkWorker.kt @@ -0,0 +1,244 @@ +/* + * Copyright 2026 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. + */ + +package com.example.niap.cert.ext.testapp + +import android.content.Context +import android.util.Base64 +import android.util.Log +import androidx.work.Data +import androidx.work.Worker +import androidx.work.WorkerParameters +import com.android.niap.cert.validator.NiapCertHelper +import com.android.niap.cert.validator.NiapTlsPolicy +import java.io.ByteArrayInputStream +import java.io.InputStream +import java.net.URL +import java.security.KeyStore +import java.security.cert.X509Certificate +import java.util.concurrent.atomic.AtomicReference +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.KeyManagerFactory +import javax.net.ssl.SSLSession +import javax.net.ssl.X509KeyManager +import okhttp3.OkHttpClient +import okhttp3.Request + +class NetworkWorker(context: Context, params: WorkerParameters) : Worker(context, params) { + + private data class SessionSnapshot( + val protocol: String, + val cipher: String, + val sessionIdHex: String, + val creationTime: Long + ) + + override fun doWork(): Result { + val urlString = inputData.getString("url") ?: return Result.failure() + val type = inputData.getString("type") ?: "http" + val caB64 = inputData.getString("ca_b64") + val clientP12B64 = inputData.getString("client_p12_b64") + val clientP12Pass = inputData.getString("client_p12_pass") ?: DEFAULT_P12_PASSWORD + val repeat = inputData.getInt("repeat", 1).coerceAtLeast(1) + val forceTls12Wire = inputData.getBoolean("force_tls12_wire", false) + Log.d( + "NetworkWorker", + "Starting request to $urlString using $type (repeat=$repeat, forceTls12Wire=$forceTls12Wire)" + ) + + try { + if (forceTls12Wire) { + Log.w("NetworkWorker", "TEST MODE: forcing TLS 1.2 wire-capture OCSP path") + NiapTlsPolicy.setForceTls12WireCaptureForTesting(applicationContext, true) + } else if (NiapTlsPolicy.isForceTls12WireCaptureEnabled) { + NiapTlsPolicy.setForceTls12WireCaptureForTesting(applicationContext, false) + } + val helper = NiapCertHelper.getInstance(applicationContext) + Log.d("NetworkWorker", "Calling validateUrl") + helper.validateUrl(urlString) + Log.d("NetworkWorker", "validateUrl passed") + + val caBytes = if (!caB64.isNullOrEmpty()) { + Base64.decode(caB64, Base64.DEFAULT) + } else { + null + } + val newTrustAnchors: () -> Map? = { + caBytes?.let { mapOf("test_ca" to ByteArrayInputStream(it)) } + } + + val clientKeyManager = if (!clientP12B64.isNullOrEmpty()) { + loadClientKeyManager(clientP12B64, clientP12Pass) + } else { + null + } + + var prevSnapshot: SessionSnapshot? = null + var lastResponseCode = -1 + + if (type == "okhttp3") { + Log.d("NetworkWorker", "Configuring OkHttp") + val capturedSession = AtomicReference(null) + val client = helper.configureOkHttp( + builder = OkHttpClient.Builder(), + trustAnchors = newTrustAnchors(), + keyManager = clientKeyManager + ).hostnameVerifier { hostname, session -> + Log.d("NetworkWorker", "Verifying hostname: $hostname") + helper.checkHostname(hostname, session) + capturedSession.set(session) + true + }.build() + Log.d("NetworkWorker", "OkHttp configured") + + for (i in 1..repeat) { + capturedSession.set(null) + val request = Request.Builder() + .url(urlString) + .header("Connection", "close") + .build() + + Log.d("NetworkWorker", "Executing OkHttp call $i/$repeat") + client.newCall(request).execute().use { response -> + lastResponseCode = response.code + // Drain body so TLS 1.3 post-handshake NewSessionTicket records are processed. + response.body?.bytes() + prevSnapshot = logRequestResult( + index = i, + total = repeat, + responseCode = lastResponseCode, + session = capturedSession.get(), + prevSnapshot = prevSnapshot + ) + } + client.connectionPool.evictAll() + } + Log.d("NetworkWorker", "OkHttp Response Code: $lastResponseCode") + return Result.success() + } else { + val url = URL(urlString) + for (i in 1..repeat) { + var capturedSession: SSLSession? = null + val connection = helper.openConnection( + url = url, + trustAnchors = newTrustAnchors(), + keyManager = clientKeyManager + ) + connection.hostnameVerifier = HostnameVerifier { hostname, session -> + Log.d("NetworkWorker", "Verifying hostname: $hostname") + helper.checkHostname(hostname, session) + capturedSession = session + true + } + connection.setRequestProperty("Connection", "close") + connection.connectTimeout = 5000 + connection.readTimeout = 5000 + + try { + connection.connect() + lastResponseCode = connection.responseCode + // Drain response stream so TLS 1.3 post-handshake NewSessionTicket records are processed. + val stream = if (lastResponseCode < 400) { + connection.inputStream + } else { + connection.errorStream + } + try { + stream?.use { it.readBytes() } + } catch (_: Exception) { + // Ignore body read errors once status code is obtained. + } + prevSnapshot = logRequestResult( + index = i, + total = repeat, + responseCode = lastResponseCode, + session = capturedSession, + prevSnapshot = prevSnapshot + ) + } finally { + connection.disconnect() + } + } + Log.d("NetworkWorker", "Response Code: $lastResponseCode") + return Result.success() + } + } catch (e: Exception) { + Log.e("NetworkWorker", "Connection failed", e) + val output = Data.Builder() + .putString("error", e.message) + .build() + return Result.failure(output) + } + } + + private fun loadClientKeyManager(p12B64: String, password: String): X509KeyManager { + val p12Bytes = Base64.decode(p12B64, Base64.DEFAULT) + val passChars = password.toCharArray() + val keyStore = KeyStore.getInstance("PKCS12") + ByteArrayInputStream(p12Bytes).use { input -> + keyStore.load(input, passChars) + } + val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()) + kmf.init(keyStore, passChars) + val keyManager = kmf.keyManagers.filterIsInstance().firstOrNull() + ?: throw IllegalStateException("No X509KeyManager found in PKCS#12 keystore") + + val subjects = keyStore.aliases().toList() + .filter { keyStore.isKeyEntry(it) } + .mapNotNull { alias -> (keyStore.getCertificate(alias) as? X509Certificate)?.subjectX500Principal?.name } + val subjectInfo = if (subjects.isNotEmpty()) subjects.joinToString("; ") else "unknown" + Log.d("NetworkWorker", "Loaded client certificate from PKCS#12: subject=$subjectInfo") + return keyManager + } + + private fun logRequestResult( + index: Int, + total: Int, + responseCode: Int, + session: SSLSession?, + prevSnapshot: SessionSnapshot? + ): SessionSnapshot { + val snapshot = captureSessionSnapshot(session) + val resumed = prevSnapshot != null && + snapshot.sessionIdHex.isNotEmpty() && + snapshot.sessionIdHex == prevSnapshot.sessionIdHex && + snapshot.creationTime == prevSnapshot.creationTime + Log.d( + "NetworkWorker", + "Request $index/$total: Response Code: $responseCode " + + "protocol=${snapshot.protocol} cipher=${snapshot.cipher} " + + "sessionId=${snapshot.sessionIdHex} created=${snapshot.creationTime} resumed=$resumed" + ) + return snapshot + } + + private fun captureSessionSnapshot(session: SSLSession?): SessionSnapshot { + if (session == null) { + return SessionSnapshot("unknown", "unknown", "", 0L) + } + val idHex = session.id?.joinToString("") { "%02x".format(it) } ?: "" + return SessionSnapshot( + protocol = session.protocol ?: "unknown", + cipher = session.cipherSuite ?: "unknown", + sessionIdHex = idHex, + creationTime = session.creationTime + ) + } + + companion object { + private const val DEFAULT_P12_PASSWORD = "changeit" + } +} diff --git a/niap-cc/niap-android-cert-ext/validator-test-app/src/main/res/xml/niap_security_config.xml b/niap-cc/niap-android-cert-ext/validator-test-app/src/main/res/xml/niap_security_config.xml new file mode 100644 index 0000000..aa5739c --- /dev/null +++ b/niap-cc/niap-android-cert-ext/validator-test-app/src/main/res/xml/niap_security_config.xml @@ -0,0 +1,64 @@ + + + + + true + + + + *.COM + *.NET + *.ORG + *.GOV + *.EDU + + + + + TLS_AES_128_GCM_SHA256 + TLS_AES_256_GCM_SHA384 + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + + + + BOTH_CA + + + + + false + + + true + + + true + + + true + + + serverAuth + + + true + diff --git a/niap-cc/niap-android-cert-ext/validator-test-app/src/relaxed/res/xml/niap_security_config.xml b/niap-cc/niap-android-cert-ext/validator-test-app/src/relaxed/res/xml/niap_security_config.xml new file mode 100644 index 0000000..9ff7c7e --- /dev/null +++ b/niap-cc/niap-android-cert-ext/validator-test-app/src/relaxed/res/xml/niap_security_config.xml @@ -0,0 +1,42 @@ + + + + + false + + + + + + + TLS_AES_128_GCM_SHA256 + TLS_AES_256_GCM_SHA384 + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + + + BOTH_CA + + false + false + true + true + serverAuth + true + diff --git a/niap-cc/sdp-file-encrypt/.gitignore b/niap-cc/sdp-file-encrypt/.gitignore new file mode 100644 index 0000000..bb06653 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/.gitignore @@ -0,0 +1,29 @@ +*.iml +.gradle +/.idea +/.vscode +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +/locked-device-demo/build +/encryption-lib/build +/real-world-demo/build +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties +AGENTS.md +.log +build_error_*.txt +build_error.txt +firebase-debug.log +*.hprof +*.img +/.kotlin +.agent/ \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/LICENSE b/niap-cc/sdp-file-encrypt/LICENSE new file mode 100644 index 0000000..d51936f --- /dev/null +++ b/niap-cc/sdp-file-encrypt/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 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. diff --git a/niap-cc/sdp-file-encrypt/README.md b/niap-cc/sdp-file-encrypt/README.md new file mode 100644 index 0000000..2c15883 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/README.md @@ -0,0 +1,193 @@ +# Android SDP File Encryption Demo + +## 1. Project Overview + +This project provides an Android file encryption core library (`encryption-lib`) alongside a demonstration application (`locked-device-demo`). It is designed to demonstrate and compare different file encryption strategies, focusing on compliance with the **NIAP Mobile Device Fundamentals Protection Profile (MDF PP) Version 3.3**. Note that while the project is structured as a generic library, implementations of manual or unsafe patterns (such as `RawKeyProvider`) are kept for demonstration and educational purposes. + +The primary goal is to compare distinct `EncryptionProvider` implementations: +- **`RawHybridKeyProvider`**: The **NIAP-compliant** reference implementation. It uses raw JCA primitives to strictly control key memory lifecycles (zeroization) and supports secure lock-state operations. +- **`HybridKeyProvider`**: A standard implementation using **Google Tink's Hybrid Encryption** (ECIES). While it is theoretically capable of meeting most requirements, strict memory zeroization (`FCS_CKM_EXT.4`) depends entirely on the Tink library's internals. Therefore, a completely compliant implementation is not provided. +- **`RawKeyProvider`**: A manual implementation using raw Android JCA APIs. It was an earlier candidate, but due to the difficulty of satisfying the strict NIAP requirements, a complete implementation is not provided. + +## 2. Security Architecture & Compliance + +This library is designed to meet the strict security requirements of the **NIAP Mobile Device Fundamentals Protection Profile (MDF PP) Version 3.3**. + +### Key Implementation: `RawHybridKeyProvider` +Unlike standard high-level wrappers, our `RawHybridKeyProvider` uses raw JCA primitives to ensure full control over the key lifecycle, specifically addressing memory zeroization requirements. + +* **Algorithm**: Hybrid Encryption Scheme (ECDH P-521 + HKDF-SHA512 + AES-256-GCM). +* **Compliance Features**: + * **FCS_CKM_EXT.4 (Key Destruction)**: Explicitly zeroes out (overwrites) plain-text DEKs and shared secrets in volatile memory immediately after use via `finally` blocks, and flushes residual Keystore Binder IPC buffers. Standard high-level libraries often rely on Garbage Collection, which is insufficient for PP compliance. + * **FDP_DAR_EXT.2 (Locked State Operation / Data at Rest)**: Fully and correctly implemented. Supports encryption even when the device is locked (AFU/BFU) by leveraging a cached public key configuration, while keeping the private key securely hardware-backed in the TEE. It also includes an automatic `FDP_DAR_EXT.2.4` sweep-and-rewrap mechanism that transitions files encrypted via asymmetric keys back to a more efficient symmetric encryption as soon as the device is unlocked. + * **FCS_CKM_EXT.2 (Key Generation)**: Uses `SecureRandom` for generating ephemeral Data Encryption Keys (DEKs). + * **FCS_STG_EXT.2 (Key Storage)**: Implements Envelope Encryption where DEKs are wrapped by a TEE-backed Key Encryption Key (KEK). + +## 3. Key Components + +### `EncryptionProvider` Implementations + +#### `RawHybridKeyProvider` (Compliant) +- **Strategy**: A robust two-tier envelope encryption designed for Common Criteria evaluation. +- **KEK (Key-Encrypting Key)**: An `EC` (Elliptic Curve) key pair stored securely in the `AndroidKeyStore` with `unlockedDeviceRequired`. +- **DEK (Data-Encapsulating Key)**: An ephemeral `AES-256-GCM` key generated via `SecureRandom` for each file. +- **Lock-State Behavior**: + - **Encryption**: Supported in locked state. Uses a pre-shared/cached Public Key to wrap the ephemeral DEK without accessing the Keystore. + - **Decryption**: Fails securely when locked. Requires user authentication to access the Private Key in the TEE for unwrapping. +- **Memory Safety**: Implements explicit zeroization of sensitive byte arrays immediately after use. + +#### `HybridKeyProvider` (Tink Standard) +- **Strategy**: Two-tier envelope encryption using the **Google Tink** library. +- **KEK**: An `AES` key stored in the `AndroidKeyStore`. +- **DEK**: A Tink-managed ECIES keyset. +- **Note**: This implementation demonstrates the standard usage of Tink's Hybrid primitives. While secure for general use, it abstracts memory management, making it difficult to prove strict compliance with NIAP's volatile memory zeroization requirements (`FCS_CKM_EXT.4`). Since explicit zeroization would require modifying Tink itself, a fully compliant implementation is not provided. + +#### `RawKeyProvider` (JCA Adapter) +- **Strategy**: A manual implementation wrapping standard Android JCA APIs (`Cipher`, `AndroidKeyStore`) into the Tink `Aead` interface. +- **Algorithm**: `AES/GCM/NoPadding`. +- **Behavior**: Generates software-backed keys and imports them into the Keystore. +- **Purpose**: Demonstrates how to adapt raw platform APIs to a common interface without using the full Tink library features. It was an earlier candidate for the final implementation, but structural challenges in meeting strict compliance requirements mean a complete, NIAP-compliant version is not provided. + +### Core Library (`encryption-lib`) +- Contains all core encryption logic, including the `EncryptionManager` (the facade API) and the various `EncryptionProvider` implementations. +- Some providers, like `RawKeyProvider`, represent specific historic or anti-pattern strategies and are deliberately retained to serve as test cases and comparative examples. + +### Demo Application (`locked-device-demo`) +- Contains a `MainActivity` that provides a UI to run encryption/decryption tests for each provider, both in unlocked and locked states, and to display the results. +- Includes a `DeviceAdminReceiver` required to programmatically lock the screen for the "Lock & Test" feature. The user must grant Device Administrator permissions to the app for this functionality to work. + +## 4. How to Build and Run + +1. Clone the repository. +2. Open the project in a recent version of Android Studio. +3. Build and run the app on an emulator or a physical device. +4. Use the buttons on the screen to test each encryption provider. +5. To use the "Lock & Test" feature, you may need to grant Device Administrator permissions to the app via the device's settings. + +## 5. Security Verification Procedure (Direct Boot & Authentication) + +This section describes how to verify the application's compliance with **FDP_DAR_EXT.2** (Encryption in Locked State) and **FIA_UAU_EXT.1** (Authentication for Decryption) using the included Test Harness. + +### Prerequisites +* Android Device running Android 8.0+ (Pixel device recommended). +* Screen Lock (PIN/Pattern/Password) **MUST** be set up. +* ADB tool installed and authorized. + +### Verification Steps + +**Step 1: Install and Initialize** +1. Install the application (`app-debug.apk`) on the target device. +2. Launch the app once and ensure the screen is unlocked to allow initial key generation. +3. Force stop the app to clear memory state: + ```bash + adb shell am force-stop com.android.niapsec + ``` + +**Step 2: Reboot into "Before First Unlock" (BFU) State** +1. Reboot the device using ADB or the power button. + ```bash + adb reboot + ``` +2. **CRITICAL:** When the device boots up, **DO NOT enter your PIN/Password**. + * The device must remain in the "Locked" state. + * Verify the state using: + ```bash + adb shell dumpsys activity | grep "mUserUnlocked" + ``` + *Expected Output:* `mUserUnlocked=false` + +**Step 3: Execute the Test Harness** +Trigger the diagnostic receiver via ADB. This component is marked as `directBootAware` and will run even when the user is locked. + +1. Start log monitoring in a terminal: + ```bash + adb logcat -c + adb logcat -s DirectBootTest + ``` + +2. In a separate terminal, send the test broadcast: + ```bash + adb shell am broadcast -a com.android.niapsec.ACTION_TEST_CRYPTO -n com.android.niapsec/.demo.DirectBootTestReceiver + ``` + +**Step 4: Verify Pass/Fail Criteria (Log Analysis)** + +Check the log output for the following verification points: + +#### A. Environment Validation +* `User State: LOCKED (BFU State)` -> **MUST** be Locked. +* `Storage Context: Device Protected (DE)` -> **MUST** use DE storage. + +#### B. RawHybridKeyProvider (JCA Implementation) +* `[RawHybrid_JCA] Attempting Encryption...` +* `[RawHybrid_JCA] SUCCESS: Encryption completed.` -> **PASS (FDP_DAR_EXT.2 Satisfied)** + * *Rationale:* Public Key was successfully retrieved from DE storage and used for encryption. +* `[RawHybrid_JCA] Attempting Decryption...` +* `[RawHybrid_JCA] SUCCESS: Decryption failed as expected during lock.` -> **PASS (FIA_UAU_EXT.1 Satisfied)** + * *Rationale:* Access to the Private Key (Android Keystore) was correctly blocked by the OS because the user is not authenticated. + +#### C. HybridKeyProvider (Tink Implementation) +* `[Hybrid_Tink] Attempting Encryption...` +* `[Hybrid_Tink] SUCCESS: Encryption completed.` -> **PASS (FDP_DAR_EXT.2 Satisfied)** +* `[Hybrid_Tink] Attempting Decryption...` +* `[Hybrid_Tink] SUCCESS: Decryption failed as expected during lock.` -> **PASS (FIA_UAU_EXT.1 Satisfied)** + +--- + +### Step 5: Verify "After First Unlock" (AFU) Behavior (Optional) +1. Unlock the screen (enter PIN). +2. Run the broadcast command again: + ```bash + adb shell am broadcast -a com.android.niapsec.ACTION_TEST_CRYPTO -n com.android.niapsec/.demo.DirectBootTestReceiver + ``` +3. Verify logs: + * `User State: UNLOCKED (AFU State)` + * `SUCCESS: Decryption succeeded and data matches.` -> **PASS** (Normal operation restored). + + +## 6. Testing Guide + +### 1. Symmetric Encrypt โ†’ Symmetric Decrypt + +Verifies normal encryption and decryption when the device is unlocked. + +1. Tap **Test File** +2. Tap **Check Status** โ€” file should show `Symmetric 0x02` +3. Tap the file entry to decrypt and verify the plaintext + +### 2. Asymmetric Encrypt โ†’ Sweep โ†’ Symmetric Decrypt + +Verifies that files encrypted while locked are re-wrapped to symmetric after unlock. + +1. Tap **Lock & Test** (device will lock and encrypt with asymmetric key) +2. Unlock the device and return to the app +3. Tap **Check Status** โ€” file should show `Symmetric 0x02` (sweep ran automatically on unlock) +4. Tap the file entry to decrypt and verify the plaintext + +### 3. Asymmetric Encrypt โ†’ Asymmetric Decrypt (Sweep Disabled) + +Verifies that asymmetric-encrypted files remain unchanged and can still be decrypted without sweep. + +1. Open the 3-dot menu in the top bar +2. Uncheck **Enable DAR_EXT.2.4 sweep** +3. Tap **Lock & Test** (device will lock and encrypt with asymmetric key) +4. Unlock the device and return to the app +5. Tap **Check Status** โ€” file should show `Asymmetric 0x01` (sweep is disabled) +6. Tap the file entry to decrypt and verify the plaintext + + +## 7. License + +Copyright 2026 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. \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/build.gradle.kts b/niap-cc/sdp-file-encrypt/build.gradle.kts new file mode 100644 index 0000000..963bc56 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/build.gradle.kts @@ -0,0 +1,7 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + alias(libs.plugins.android.application) apply false + alias(libs.plugins.kotlin.android) apply false + alias(libs.plugins.kotlin.compose) apply false + alias(libs.plugins.ksp) apply false +} \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/build.gradle.kts b/niap-cc/sdp-file-encrypt/encryption-lib/build.gradle.kts new file mode 100644 index 0000000..375edc2 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/build.gradle.kts @@ -0,0 +1,73 @@ +/* +* Copyright (C) 2026 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. +*/ +import java.text.SimpleDateFormat +import java.util.Date + +plugins { + id("com.android.library") + alias(libs.plugins.kotlin.android) +} + +android { + namespace = "com.android.niapsec.encryption" + compileSdk = 36 + + defaultConfig { + minSdk = 28 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildFeatures.buildConfig = true + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = "11" + } + defaultConfig { + val dateFormat = SimpleDateFormat("yyMMdd") + val buildTime = dateFormat.format(Date()) + buildConfigField("String", "BUILD_DATE", "\"${buildTime}\"") + } +} + +configurations.all { + resolutionStrategy { + force("com.google.crypto.tink:tink-android:1.20.0") + force("com.google.crypto.tink:tink-core:1.20.0") + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation("com.google.crypto.tink:tink-android:1.20.0") + implementation("org.bouncycastle:bcprov-jdk18on:1.77") + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/androidTest/java/com/android/niapsec/demo/EncryptionProviderTest.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/androidTest/java/com/android/niapsec/demo/EncryptionProviderTest.kt new file mode 100644 index 0000000..6ee8029 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/androidTest/java/com/android/niapsec/demo/EncryptionProviderTest.kt @@ -0,0 +1,142 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.demo + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.android.niapsec.encryption.api.EncryptionManager +import com.android.niapsec.encryption.api.KeyProviderType +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +@RunWith(AndroidJUnit4::class) +class EncryptionProviderTest { + + private val context = InstrumentationRegistry.getInstrumentation().targetContext + private val filesToClean = mutableListOf() + + @Before + fun setup() { + // Ensure we start from a clean state before each test + clearAllData() + } + + @After + fun teardown() { + // Clean up all generated keys and files after each test + clearAllData() + filesToClean.forEach { it.delete() } + filesToClean.clear() + } + + @Test + fun testHybridProvider_EncryptDecrypt_Succeeds() { + val manager = createManager(KeyProviderType.HYBRID) + val testFile = createTestFile("hybrid_test.txt") + val originalText = "This is a hybrid message." + + // Encrypt + manager.encryptToFile(testFile).use { it.write(originalText.toByteArray()) } + + // Decrypt + val decryptedText = manager.decryptFromFile(testFile).use { it.reader().readText() } + assertEquals("Decrypted content should match original", originalText, decryptedText) + } + + @Test + fun testRawProvider_EncryptDecrypt_Succeeds() { + val manager = createManager(KeyProviderType.RAW) + val testFile = createTestFile("raw_test.txt") + val originalText = "This is a raw message." + + // Encrypt + manager.encryptToFile(testFile).use { it.write(originalText.toByteArray()) } + + // Decrypt + val decryptedText = manager.decryptFromFile(testFile).use { it.reader().readText() } + assertEquals("Decrypted content should match original", originalText, decryptedText) + } + + @Test + fun testHybridProvider_EncryptDecrypt_TwoFiles_Succeeds() { + val manager = createManager(KeyProviderType.HYBRID) + + val testFile1 = createTestFile("hybrid_test_1.txt") + val originalText1 = "This is the first hybrid message." + manager.encryptToFile(testFile1).use { it.write(originalText1.toByteArray()) } + + val testFile2 = createTestFile("hybrid_test_2.txt") + val originalText2 = "This is the second hybrid message." + manager.encryptToFile(testFile2).use { it.write(originalText2.toByteArray()) } + + val decryptedText1 = manager.decryptFromFile(testFile1).use { it.reader().readText() } + assertEquals("Decrypted content for file 1 should match original", originalText1, decryptedText1) + + val decryptedText2 = manager.decryptFromFile(testFile2).use { it.reader().readText() } + assertEquals("Decrypted content for file 2 should match original", originalText2, decryptedText2) + } + + @Test + fun testRawProvider_EncryptDecrypt_TwoFiles_Succeeds() { + val manager = createManager(KeyProviderType.RAW) + + val testFile1 = createTestFile("raw_test_1.txt") + val originalText1 = "This is the first raw message." + manager.encryptToFile(testFile1).use { it.write(originalText1.toByteArray()) } + + val testFile2 = createTestFile("raw_test_2.txt") + val originalText2 = "This is the second raw message." + manager.encryptToFile(testFile2).use { it.write(originalText2.toByteArray()) } + + val decryptedText1 = manager.decryptFromFile(testFile1).use { it.reader().readText() } + assertEquals("Decrypted content for file 1 should match original", originalText1, decryptedText1) + + val decryptedText2 = manager.decryptFromFile(testFile2).use { it.reader().readText() } + assertEquals("Decrypted content for file 2 should match original", originalText2, decryptedText2) + } + + private fun createManager(providerType: KeyProviderType): EncryptionManager { + val keyUri = "android-keystore://test_key_for_${providerType.name}" + return EncryptionManager( + context = context, + masterKeyUri = keyUri, + providerType = providerType, + unlockedDeviceRequired = false // Use false for automated tests + ) + } + + private fun createTestFile(filename: String): File { + val file = File(context.filesDir, filename) + filesToClean.add(file) + return file + } + + private fun clearAllData() { + // A simple way to clear all provider keys and files + for (providerType in KeyProviderType.values()) { + try { + val manager = createManager(providerType) + manager.destroy() + } catch (e: Exception) { + // Ignore errors during cleanup + } + } + } +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/androidTest/java/com/android/niapsec/encryption/EncryptionManagerTest.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/androidTest/java/com/android/niapsec/encryption/EncryptionManagerTest.kt new file mode 100644 index 0000000..564c3f1 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/androidTest/java/com/android/niapsec/encryption/EncryptionManagerTest.kt @@ -0,0 +1,193 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.encryption + +import android.app.KeyguardManager +import android.content.Context +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.android.niapsec.encryption.api.EncryptionManager +import com.android.niapsec.encryption.api.KeyProviderType +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.nio.charset.StandardCharsets +import java.security.GeneralSecurityException +import java.util.UUID + +@RunWith(AndroidJUnit4::class) +class EncryptionManagerTest { + + private lateinit var context: Context + private lateinit var keyguardManager: KeyguardManager + private val managersToDestroy = mutableListOf() + private val filesToClean = mutableListOf() + + @Before + fun setup() { + context = InstrumentationRegistry.getInstrumentation().targetContext + keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager + } + + @After + fun tearDown() { + managersToDestroy.forEach { it.destroy() } + managersToDestroy.clear() + + filesToClean.forEach { if (it.exists()) it.delete() } + filesToClean.clear() + } + + private fun createManager(providerType: KeyProviderType, unlockedDeviceRequired: Boolean = false): EncryptionManager { + val masterKeyUri = "android-keystore://test_key_${UUID.randomUUID()}" + val manager = EncryptionManager(context, masterKeyUri, providerType, unlockedDeviceRequired) + managersToDestroy.add(manager) + return manager + } + + private fun getTestFile(fileName: String): File { + val file = File(context.cacheDir, fileName) + filesToClean.add(file) + return file + } + + /** + * Helper to generate a large string of approximately specific size (in bytes). + */ + private fun generateLargeString(sizeInBytes: Int): String { + val sb = StringBuilder(sizeInBytes) + val chunk = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // 62 chars + + while (sb.length < sizeInBytes) { + sb.append(chunk) + } + return sb.substring(0, sizeInBytes) + } + + // --- Stream API Tests (StreamingAead) --- + + @Test + fun testRawHybridProvider_encryptAndDecryptStream_1MB_works() { + // Test StreamingAead with ~1MB of data + val encryptionManager = createManager(KeyProviderType.RAW_HYBRID) + val testFile = getTestFile("stream_1mb_test.dat") + + // Generate 1MB String (1024 * 1024 bytes) + val targetSize = 1024 * 1024 + val originalContent = generateLargeString(targetSize) + + // Encrypt using Stream API + encryptionManager.encryptToFileStream(testFile).use { outputStream -> + // Convert to bytes explicitly to ensure size match + outputStream.write(originalContent.toByteArray(StandardCharsets.UTF_8)) + } + + // Verify file was created and has some size (overhead + content) + assertTrue("File should exist", testFile.exists()) + assertTrue("File should be larger than plain content due to IV/AuthTag", testFile.length() > targetSize) + + // Decrypt using Stream API + val decryptedContent = encryptionManager.decryptFromFileStream(testFile).use { inputStream -> + inputStream.reader(StandardCharsets.UTF_8).readText() + } + + assertEquals("Decrypted content length should match", originalContent.length, decryptedContent.length) + assertEquals("Decrypted content should match original", originalContent, decryptedContent) + } + + @Test + fun testRawHybridProvider_encryptFile_deletesOriginalByDefault() { + val encryptionManager = createManager(KeyProviderType.RAW_HYBRID) + val sourceFile = getTestFile("source_to_delete.txt") + val destFile = getTestFile("dest_encrypted.enc") + + val randomText = "Some random text for encryptFile. " + generateLargeString(1000) + sourceFile.writeText(randomText) + + // Use the new encryptFile API (default deleteOriginal = true) + encryptionManager.encryptFile(sourceFile, destFile) + + assertTrue("Destination file should exist", destFile.exists()) + assertTrue("Source file should be deleted", !sourceFile.exists()) + + val decryptedText = encryptionManager.decryptFromFileStream(destFile).use { it.reader().readText() } + assertEquals("Decrypted text should match", randomText, decryptedText) + } + + @Test + fun testRawHybridProvider_encryptFile_preservesOriginalWhenRequested() { + val encryptionManager = createManager(KeyProviderType.RAW_HYBRID) + val sourceFile = getTestFile("source_to_keep.txt") + val destFile = getTestFile("dest_encrypted_keep.enc") + + val randomText = "Some random text that must be kept. " + generateLargeString(1000) + sourceFile.writeText(randomText) + + // Use the new encryptFile API with deleteOriginal = false + encryptionManager.encryptFile(sourceFile, destFile, deleteOriginal = false) + + assertTrue("Destination file should exist", destFile.exists()) + assertTrue("Source file should still exist", sourceFile.exists()) + + val decryptedText = encryptionManager.decryptFromFileStream(destFile).use { it.reader().readText() } + assertEquals(randomText, decryptedText) + } + + @Test + fun testRawProvider_encryptStream_throwsUnsupportedOperation() { + // RAW provider (and others not updated) should NOT support streaming + val encryptionManager = createManager(KeyProviderType.RAW) + val testFile = getTestFile("raw_stream_fail_test.dat") + + assertThrows(UnsupportedOperationException::class.java) { + encryptionManager.encryptToFileStream(testFile) + } + } + + // --- Legacy File API Tests (Aead / In-Memory) --- + + // --- String Encryption Tests --- + + @Test + fun testStringEncryption_works_rawHybrid() { + val encryptionManager = createManager(KeyProviderType.RAW_HYBRID) + val originalText = "Hello World! String encryption test with RawHybrid." + + val ciphertext = encryptionManager.encryptToString(originalText) + val decryptedText = encryptionManager.decryptFromString(ciphertext) + + assertEquals(originalText, decryptedText) + } + + @Test + fun testRawHybridProvider_encryptUsesSymmetricWhenUnlocked() { + val encryptionManager = createManager(KeyProviderType.RAW_HYBRID) + val originalText = "Asserting symmetric magic byte (Solution 1)" + val ciphertextBase64 = encryptionManager.encryptToString(originalText) + + val ciphertextBytes = android.util.Base64.decode(ciphertextBase64, android.util.Base64.DEFAULT) + + // Assert first byte is 0x02 (MAGIC_BYTE_SYMMETRIC) after skipping the 4-byte provider header ("EHBR") + assertEquals("Ciphertext should start with 0x02 representing symmetric encryption (no fallback)", 0x02.toByte(), ciphertextBytes[4]) + } +} \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/androidTest/res/raw/sample_text.txt b/niap-cc/sdp-file-encrypt/encryption-lib/src/androidTest/res/raw/sample_text.txt new file mode 100644 index 0000000..d64f222 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/androidTest/res/raw/sample_text.txt @@ -0,0 +1 @@ +This is a sample file from the app's resources. \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/AndroidManifest.xml b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9a40236 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/api/EncryptionManager.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/api/EncryptionManager.kt new file mode 100644 index 0000000..0489f74 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/api/EncryptionManager.kt @@ -0,0 +1,185 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.encryption.api + +import android.content.Context +import android.util.Base64 +import android.util.Log +import com.android.niapsec.encryption.internal.EncryptionProvider +import com.android.niapsec.encryption.internal.TinkEncryptionProvider +import com.android.niapsec.encryption.internal.keymanagement.HybridKeyProvider +import com.android.niapsec.encryption.internal.keymanagement.NoOpKeyProvider +import com.android.niapsec.encryption.internal.keymanagement.RawHybridKeyProvider +import com.android.niapsec.encryption.internal.keymanagement.RawKeyProvider +import java.io.File +import java.io.InputStream +import java.io.OutputStream + +/** + * Manages encryption and decryption operations for files and strings using a configurable KeyProvider. + */ +class EncryptionManager( + context: Context, + masterKeyUri: String, + val providerType: KeyProviderType = KeyProviderType.HYBRID, + unlockedDeviceRequired: Boolean = false, + lockStatePollCount: Int = 5, + lockStatePollIntervalMs: Long = 100, + private val encryptionProvider: EncryptionProvider = TinkEncryptionProvider(context, + when (providerType) { + KeyProviderType.RAW -> + RawKeyProvider(context, masterKeyUri.replace("android-keystore://", ""), unlockedDeviceRequired) + KeyProviderType.HYBRID -> + HybridKeyProvider(context, masterKeyUri, unlockedDeviceRequired, "tink_keyset_${masterKeyUri.replace("android-keystore://", "")}") + KeyProviderType.RAW_HYBRID -> + RawHybridKeyProvider(context, masterKeyUri, unlockedDeviceRequired, "tink_keyset_${masterKeyUri.replace("android-keystore://", "")}", lockStatePollCount, lockStatePollIntervalMs) + KeyProviderType.NONE -> + NoOpKeyProvider() + }, + when (providerType) { + KeyProviderType.RAW -> "ERAW".toByteArray() + KeyProviderType.HYBRID -> "EHBT".toByteArray() + KeyProviderType.RAW_HYBRID -> "EHBR".toByteArray() + KeyProviderType.NONE -> "NONE".toByteArray() + } + ) +) { + + fun destroy() { + encryptionProvider.destroy() + } + + fun getUnlockDeviceRequired(): Boolean { + return (encryptionProvider as TinkEncryptionProvider).keyProvider.getUnlockDeviceRequired() + } + + /** + * Encrypts a file using in-memory processing. + * Suitable for small files. + */ + fun encryptToFile(file: File): OutputStream { + val encryptedContent = encryptionProvider.encrypt(file); + return encryptedContent + } + + /** + * Decrypts a file using in-memory processing. + */ + fun decryptFromFile(file: File): InputStream { + return encryptionProvider.decrypt(file) + } + + /** + * Encrypts a file using streaming processing. + * Suitable for large files. Throws UnsupportedOperationException if the provider doesn't support streaming. + */ + fun encryptToFileStream(file: File): OutputStream { + return encryptionProvider.encryptStream(file) + } + + /** + * Encrypts a source file to a destination file using streaming processing. + * Uses a temporary `.tmp` file during encryption to prevent corruption if interrupted, + * and atomically renames it to the destination file upon successful completion. + * + * @param sourceFile The plaintext input file. + * @param destFile The target encrypted output file (e.g., `.enc`). + * @param deleteOriginal If true, safely deletes the source file upon success. + */ + fun encryptFile(sourceFile: File, destFile: File, deleteOriginal: Boolean = true) { + val tmpFile = File(destFile.absolutePath + ".tmp") + try { + sourceFile.inputStream().use { input -> + try { + encryptToFileStream(tmpFile).use { output -> + input.copyTo(output) + } + } catch (e: java.lang.UnsupportedOperationException) { + // Fallback to in-memory encryption if streaming is not supported + encryptToFile(tmpFile).use { output -> + input.copyTo(output) + } + } + } + // Stream writing completed and closed successfully. Atomic rename: + if (!tmpFile.renameTo(destFile)) { + throw java.io.IOException("Failed to rename temporary encrypted file to target destination.") + } + // If successful and requested, delete original + if (deleteOriginal) { + if (!sourceFile.delete()) { + throw java.io.IOException("Failed to delete original plaintext file after encryption.") + } + } + } catch (e: Exception) { + // Clean up temporary file on failure + if (tmpFile.exists()) { + tmpFile.delete() + } + throw e + } + } + + /** + * Decrypts a file using streaming processing. + */ + fun decryptFromFileStream(file: File): InputStream { + return encryptionProvider.decryptStream(file) + } + + /** + * Encrypts a string and returns it as a Base64-encoded ciphertext. + */ + fun encryptToString(plaintext: String): String { + val ciphertext = encryptionProvider.encrypt(plaintext) + return Base64.encodeToString(ciphertext, Base64.DEFAULT) + } + + /** + * Decrypts a Base64-encoded ciphertext string and returns the plaintext. + */ + fun decryptFromString(ciphertext: String): String { + val ciphertextBytes = Base64.decode(ciphertext, Base64.DEFAULT) + return encryptionProvider.decrypt(ciphertextBytes) + } + + /** + * Re-wraps the file key from asymmetric to symmetric scheme. + * This is useful for transitioning data received while locked to a more permanent + * symmetric protection after the device is unlocked (FDP_DAR_EXT.2.4 compliance). + */ + fun rewrapFileKey(file: File): Boolean { + return encryptionProvider.rewrapFileKey(android.net.Uri.fromFile(file)) + } + + /** + * Sweeps the app's files directory and re-wraps all pending encrypted files + * to the symmetric scheme. + */ + fun sweepAndRewrapPendingFiles() { + encryptionProvider.sweepAndRewrapPendingFiles() + } + + /** + * Sweeps a specific directory (such as a messages folder or Device Protected storage + * directory) and re-wraps pending asymmetrically encrypted files to the symmetric scheme. + * + * @return Number of files transitioned from asymmetric to symmetric wrapping. + */ + fun sweepAndRewrapDirectory(targetDir: File): Int { + return encryptionProvider.sweepAndRewrapDirectory(targetDir) + } +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/api/KeyProviderType.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/api/KeyProviderType.kt new file mode 100644 index 0000000..07146cf --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/api/KeyProviderType.kt @@ -0,0 +1,47 @@ +/* +* Copyright (C) 2026 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. +*/ + +package com.android.niapsec.encryption.api + +/** + * Defines the available KeyProvider implementations that can be used by the EncryptionManager. + */ +enum class KeyProviderType { + /** + * Uses the HybridKeyProvider, which uses a P-521 elliptic curve key pair as the KEK + * and AES256-GCM as the DEK for hybrid encryption. + */ + HYBRID, + + /** + * Uses the RawEncryptionProvider, which uses the standard Android Keystore and JCA + * without the Tink library. + */ + RAW, + + /** + * Uses the RawHybridKeyProvider, which implements a hybrid encryption scheme using raw JCA. + */ + RAW_HYBRID, + + /** + * INSECURE / DEMO COMPARISON ONLY: + * Uses NoOpKeyProvider, which stores data in plaintext without any cryptographic protection + * or lock-state enforcement. Retained strictly to contrast unencrypted storage against + * SDP-protected providers in demonstrations. + */ + NONE +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/EncryptionProvider.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/EncryptionProvider.kt new file mode 100644 index 0000000..f1d1ea0 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/EncryptionProvider.kt @@ -0,0 +1,77 @@ +/* +* Copyright (C) 2026 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. +*/ + +package com.android.niapsec.encryption.internal + +import android.net.Uri +import java.io.File +import java.io.InputStream +import java.io.OutputStream + +/** + * An interface for providing encryption and decryption operations. + */ +interface EncryptionProvider { + + /** + * Encrypts a file using in-memory processing (Aead). + * Best for small files. + */ + fun encrypt(file: File): OutputStream + + /** + * Encrypts a file using streaming processing (StreamingAead). + * Best for large files. Throws exception if not supported by the provider. + */ + fun encryptStream(file: File): OutputStream + + /** + * Encrypts a plaintext string into a ciphertext byte array. + */ + fun encrypt(plaintext: String): ByteArray + + /** + * Decrypts a file using in-memory processing (Aead). + */ + fun decrypt(file: File): InputStream + + /** + * Decrypts a file using streaming processing (StreamingAead). + * Throws exception if not supported by the provider. + */ + fun decryptStream(file: File): InputStream + + /** + * Decrypts a ciphertext byte array into a plaintext string. + */ + fun decrypt(ciphertext: ByteArray): String + + //new methods for rewrap with symmetric keys + fun rewrapFileKey(fileUri: Uri): Boolean + + fun sweepAndRewrapPendingFiles() + + /** + * Sweeps [targetDir] and re-wraps pending asymmetrically encrypted files to the symmetric + * UDR scheme, returning the count of files transitioned during this sweep. + */ + fun sweepAndRewrapDirectory(targetDir: File): Int + + /** + * Destroys any cryptographic material associated with this provider. + */ + fun destroy() +} \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/TinkEncryptionProvider.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/TinkEncryptionProvider.kt new file mode 100644 index 0000000..323ca84 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/TinkEncryptionProvider.kt @@ -0,0 +1,215 @@ +/* +* Copyright (C) 2026 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. +*/ + +package com.android.niapsec.encryption.internal + +import android.content.Context +import android.net.Uri +import android.util.Log +import com.android.niapsec.encryption.internal.keymanagement.KeyProvider +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.InputStream +import java.io.OutputStream +import java.security.GeneralSecurityException + +class TinkEncryptionProvider( + private val context: Context, + val keyProvider: KeyProvider, + private val providerHeader: ByteArray // [MDFPP] 4-byte Magic Header: ERAW, EHBT, or EHBR +) : EncryptionProvider { + + // --- File Operations (In-Memory, Zeroizing) --- + + override fun encrypt(file: File): OutputStream { + val aead = keyProvider.getAead() + val fileOutputStream = FileOutputStream(file) + fileOutputStream.write(providerHeader) + + return object : OutputStream() { + private val buffer = ZeroizingByteArrayOutputStream(256) + private var closed = false + + override fun write(b: Int) { + buffer.write(b) + } + + override fun write(b: ByteArray, off: Int, len: Int) { + buffer.write(b, off, len) + } + + override fun close() { + if (closed) return + closed = true + var plainCopy: ByteArray? = null + try { + plainCopy = buffer.toByteArrayCopy() + val ciphertext = aead.encrypt(plainCopy, providerHeader) + fileOutputStream.write(ciphertext) + } finally { + plainCopy?.fill(0) + buffer.zeroize() + fileOutputStream.close() + } + } + } + } + + override fun decrypt(file: File): InputStream { + val fileInputStream = FileInputStream(file) + try { + val header = ByteArray(providerHeader.size) + if (fileInputStream.read(header) != header.size || !header.contentEquals(providerHeader)) { + throw GeneralSecurityException("Invalid provider header.") + } + val ciphertext = fileInputStream.readBytes() + val aead = keyProvider.getAead() + val plaintext = aead.decrypt(ciphertext, providerHeader) + return ZeroizingByteArrayInputStream(plaintext) + } finally { + fileInputStream.close() + } + } + + // --- Stream Operations (StreamingAead) --- + + override fun encryptStream(file: File): OutputStream { + val streamingAead = keyProvider.getStreamingAead() ?: throw UnsupportedOperationException("Streaming not supported") + val fileOutputStream = FileOutputStream(file) + try { + fileOutputStream.write(providerHeader) + return streamingAead.newEncryptingStream(fileOutputStream, providerHeader) + } catch (e: Exception) { + fileOutputStream.close() + throw e + } + } + + override fun decryptStream(file: File): InputStream { + val streamingAead = keyProvider.getStreamingAead() ?: throw UnsupportedOperationException("Streaming not supported") + val fileInputStream = FileInputStream(file) + try { + val header = ByteArray(providerHeader.size) + if (fileInputStream.read(header) != header.size || !header.contentEquals(providerHeader)) { + throw GeneralSecurityException("Invalid provider header.") + } + return streamingAead.newDecryptingStream(fileInputStream, providerHeader) + } catch (e: Exception) { + fileInputStream.close() + throw e + } + } + + // --- String / Misc Operations --- + + override fun encrypt(plaintext: String): ByteArray { + val aead = keyProvider.getAead() + val ciphertext = aead.encrypt(plaintext.toByteArray(), providerHeader) + return providerHeader + ciphertext + } + + override fun decrypt(ciphertext: ByteArray): String { + if (ciphertext.size < providerHeader.size) { + throw GeneralSecurityException("Invalid ciphertext size.") + } + + val header = ciphertext.copyOfRange(0, providerHeader.size) + val actualCiphertext = ciphertext.copyOfRange(providerHeader.size, ciphertext.size) + + if (!header.contentEquals(providerHeader)) { + throw GeneralSecurityException("Invalid provider header.") + } + + val aead = keyProvider.getAead() + val plaintext = aead.decrypt(actualCiphertext, providerHeader) + return String(plaintext) + } + + override fun rewrapFileKey(fileUri: Uri): Boolean { + val path = fileUri.path ?: return false + val file = File(path) + if (!file.exists() || !file.isFile) return false + + return try { + val fileBytes = file.readBytes() + if (fileBytes.size <= providerHeader.size) return false + + val header = fileBytes.copyOfRange(0, providerHeader.size) + val actualCiphertext = fileBytes.copyOfRange(providerHeader.size, fileBytes.size) + + if (!header.contentEquals(providerHeader)) return false + + if (keyProvider.isSymmetricallyWrapped(actualCiphertext)) { + return true + } + + val newCiphertext = keyProvider.rewrapKeyToSymmetricUdr(actualCiphertext) + val tmpFile = File(file.parentFile, "${file.name}.rewrap.tmp") + try { + tmpFile.writeBytes(providerHeader + newCiphertext) + if (!tmpFile.renameTo(file)) { + file.writeBytes(providerHeader + newCiphertext) + } + } finally { + if (tmpFile.exists()) { + tmpFile.delete() + } + } + true + } catch (e: NotImplementedError) { + Log.d("TinkEncryptionProvider", "Rewrap not supported by current KeyProvider") + false + } catch (e: Exception) { + Log.e("TinkEncryptionProvider", "Failed to rewrap file: $path", e) + false + } + } + + override fun sweepAndRewrapPendingFiles() { + sweepAndRewrapDirectory(context.filesDir) + } + + override fun sweepAndRewrapDirectory(targetDir: File): Int { + if (!targetDir.exists() || !targetDir.isDirectory) return 0 + var rewrappedCount = 0 + targetDir.listFiles()?.forEach { file -> + if (file.isFile && !file.name.endsWith(".tmp")) { + try { + val fileBytes = file.readBytes() + if (fileBytes.size > providerHeader.size) { + val header = fileBytes.copyOfRange(0, providerHeader.size) + val actualCiphertext = fileBytes.copyOfRange(providerHeader.size, fileBytes.size) + if (header.contentEquals(providerHeader) && !keyProvider.isSymmetricallyWrapped(actualCiphertext)) { + if (rewrapFileKey(Uri.fromFile(file))) { + rewrappedCount++ + } + } + } + } catch (e: NotImplementedError) { + return 0 + } catch (e: Exception) { + Log.w("TinkEncryptionProvider", "Sweep skipped file: ${file.name}", e) + } + } + } + return rewrappedCount + } + + override fun destroy() { + keyProvider.destroy() + } +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/ZeroizingStreams.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/ZeroizingStreams.kt new file mode 100644 index 0000000..289e5ee --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/ZeroizingStreams.kt @@ -0,0 +1,272 @@ +/* + * Copyright (C) 2026 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. + */ +package com.android.niapsec.encryption.internal + +import com.android.niapsec.encryption.tools.CleanSecretKeySpec +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.security.SecureRandom +import javax.crypto.Cipher +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** + * Memory-zeroizing [OutputStream] replacement for [java.io.ByteArrayOutputStream]. + * + * Standard [java.io.ByteArrayOutputStream] leaves both its internal backing array and every + * intermediate array allocated during capacity growth unzeroed on the ART heap until GC. + * This class zeroes old backing arrays immediately on resize and zeroes the active backing + * array on [zeroize] / [close]. + */ +internal class ZeroizingByteArrayOutputStream(initialCapacity: Int = 256) : OutputStream() { + private var buf: ByteArray = ByteArray(initialCapacity.coerceAtLeast(32)) + private var count: Int = 0 + + val size: Int get() = count + + private fun ensureCapacity(minCapacity: Int) { + if (minCapacity <= buf.size) return + var newCap = buf.size shl 1 + if (newCap < minCapacity) newCap = minCapacity + val next = ByteArray(newCap) + buf.copyInto(next, destinationOffset = 0, startIndex = 0, endIndex = count) + buf.fill(0) + buf = next + } + + override fun write(b: Int) { + ensureCapacity(count + 1) + buf[count++] = b.toByte() + } + + override fun write(b: ByteArray, off: Int, len: Int) { + if (off < 0 || len < 0 || off + len > b.size) { + throw IndexOutOfBoundsException("off=$off, len=$len, size=${b.size}") + } + if (len == 0) return + ensureCapacity(count + len) + b.copyInto(buf, destinationOffset = count, startIndex = off, endIndex = off + len) + count += len + } + + /** Returns the internal backing buffer (valid range `0 until size`) without copying. */ + fun backingBuffer(): ByteArray = buf + + /** Returns an exact-length copy (caller is responsible for zeroizing the returned array). */ + fun toByteArrayCopy(): ByteArray = buf.copyOf(count) + + fun zeroize() { + buf.fill(0) + count = 0 + } + + override fun close() { + zeroize() + } +} + +/** + * Memory-zeroizing [InputStream] replacement for [java.io.ByteArrayInputStream]. + * + * Progressively overwrites consumed bytes with zeros as [read] advances and unconditionally + * zeroes the entire backing array on [close]. + */ +internal class ZeroizingByteArrayInputStream( + private val buf: ByteArray, + private val length: Int = buf.size +) : InputStream() { + private var pos: Int = 0 + private var closed: Boolean = false + + override fun read(): Int { + if (closed || pos >= length) return -1 + val value = buf[pos].toInt() and 0xFF + buf[pos] = 0 + pos++ + return value + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (off < 0 || len < 0 || off + len > b.size) { + throw IndexOutOfBoundsException("off=$off, len=$len, size=${b.size}") + } + if (len == 0) return 0 + if (closed || pos >= length) return -1 + val toCopy = minOf(len, length - pos) + buf.copyInto(b, destinationOffset = off, startIndex = pos, endIndex = pos + toCopy) + buf.fill(0, pos, pos + toCopy) + pos += toCopy + return toCopy + } + + override fun available(): Int = if (closed) 0 else (length - pos).coerceAtLeast(0) + + override fun close() { + if (!closed) { + closed = true + buf.fill(0) + pos = length + } + } +} + +/** + * Zeroizing AEAD encrypting [OutputStream] that avoids [javax.crypto.CipherOutputStream] and + * Conscrypt's unzeroed `OpenSSLAeadCipher.buf` (which is allocated whenever `cipher.update()` + * is called before `doFinal()`). + * + * Buffers plaintext into a [ZeroizingByteArrayOutputStream], calls `cipher.doFinal(buf, 0, len)` + * directly on [close] (keeping 100% wire compatibility with AES-256-GCM), wipes all plaintext + * buffers, destroys [keySpec], and overwrites internal cipher key state in `finally`. + */ +internal class ZeroizingCipherEncryptOutputStream( + private val downstream: OutputStream, + private val dataCipher: Cipher, + private val keySpec: CleanSecretKeySpec? +) : OutputStream() { + private val plainBuffer = ZeroizingByteArrayOutputStream(256) + private var closed = false + + override fun write(b: Int) { + if (closed) throw IOException("Stream already closed") + plainBuffer.write(b) + } + + override fun write(b: ByteArray, off: Int, len: Int) { + if (closed) throw IOException("Stream already closed") + plainBuffer.write(b, off, len) + } + + override fun close() { + if (closed) return + closed = true + try { + val plaintext = plainBuffer.backingBuffer() + val plainLen = plainBuffer.size + val ciphertext = dataCipher.doFinal(plaintext, 0, plainLen) + downstream.write(ciphertext) + downstream.flush() + } finally { + plainBuffer.zeroize() + keySpec?.let { if (!it.isDestroyed) it.destroy() } + clearCipherState(dataCipher) + downstream.close() + } + } +} + +/** + * Zeroizing AEAD decrypting [InputStream] that replaces [javax.crypto.CipherInputStream]. + * + * Standard [javax.crypto.CipherInputStream] allocates an internal 512-byte `ibuffer` and an + * unzeroed `obuffer` on the ART heap that persists after `close()`. This stream reads the + * ciphertext into memory, calls `cipher.doFinal(ct, 0, ctLen, plainBuf, 0)` directly into an + * owned `plainBuf`, immediately destroys [keySpec] and clears cipher state, zeroes consumed + * slices as [read] advances, and unconditionally zeroes `plainBuf` on [close]. + */ +internal class ZeroizingCipherDecryptInputStream( + private val upstream: InputStream, + private val dataCipher: Cipher, + private val keySpec: CleanSecretKeySpec? +) : InputStream() { + private var plainBuf: ByteArray? = null + private var plainLen: Int = 0 + private var pos: Int = 0 + private var decrypted: Boolean = false + private var closed: Boolean = false + + private fun ensureDecrypted() { + if (decrypted) return + decrypted = true + var outBuf: ByteArray? = null + try { + val ctBytes = upstream.readBytes() + val maxOut = dataCipher.getOutputSize(ctBytes.size).coerceAtLeast(0) + outBuf = ByteArray(maxOut) + val actualLen = dataCipher.doFinal(ctBytes, 0, ctBytes.size, outBuf, 0) + plainBuf = outBuf + plainLen = actualLen + pos = 0 + } catch (e: Exception) { + outBuf?.fill(0) + plainBuf = null + plainLen = 0 + if (e is IOException) throw e + throw IOException("Decryption failed: ${e.message}", e) + } finally { + keySpec?.let { if (!it.isDestroyed) it.destroy() } + clearCipherState(dataCipher) + } + } + + override fun read(): Int { + if (closed) return -1 + ensureDecrypted() + val buf = plainBuf ?: return -1 + if (pos >= plainLen) return -1 + val v = buf[pos].toInt() and 0xFF + buf[pos] = 0 + pos++ + return v + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (off < 0 || len < 0 || off + len > b.size) { + throw IndexOutOfBoundsException("off=$off, len=$len, size=${b.size}") + } + if (len == 0) return 0 + if (closed) return -1 + ensureDecrypted() + val buf = plainBuf ?: return -1 + if (pos >= plainLen) return -1 + val toCopy = minOf(len, plainLen - pos) + buf.copyInto(b, destinationOffset = off, startIndex = pos, endIndex = pos + toCopy) + buf.fill(0, pos, pos + toCopy) + pos += toCopy + return toCopy + } + + override fun available(): Int { + if (closed || !decrypted) return 0 + return (plainLen - pos).coerceAtLeast(0) + } + + override fun close() { + if (closed) return + closed = true + try { + plainBuf?.fill(0) + plainBuf = null + plainLen = 0 + pos = 0 + keySpec?.let { if (!it.isDestroyed) it.destroy() } + clearCipherState(dataCipher) + } finally { + upstream.close() + } + } +} + +internal fun clearCipherState(cipher: Cipher) { + try { + val dummyKey = SecretKeySpec(ByteArray(32), "AES") + val dummyIv = ByteArray(12).also { SecureRandom().nextBytes(it) } + cipher.init(Cipher.ENCRYPT_MODE, dummyKey, GCMParameterSpec(128, dummyIv)) + } catch (_: Exception) { + // Best-effort internal cipher state overwrite + } +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/HybridKeyProvider.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/HybridKeyProvider.kt new file mode 100644 index 0000000..9b662ea --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/HybridKeyProvider.kt @@ -0,0 +1,284 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.encryption.internal.keymanagement + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Log +import androidx.core.content.edit +import com.google.crypto.tink.Aead +import com.google.crypto.tink.CleartextKeysetHandle +import com.google.crypto.tink.HybridDecrypt +import com.google.crypto.tink.HybridEncrypt +import com.google.crypto.tink.JsonKeysetReader +import com.google.crypto.tink.JsonKeysetWriter +import com.google.crypto.tink.KeyTemplate +import com.google.crypto.tink.KeysetHandle +import com.google.crypto.tink.aead.AeadConfig +import com.google.crypto.tink.hybrid.HybridConfig +import com.google.crypto.tink.integration.android.AndroidKeysetManager +import com.google.crypto.tink.proto.AesGcmKeyFormat +import com.google.crypto.tink.proto.EcPointFormat +import com.google.crypto.tink.proto.EciesAeadDemParams +import com.google.crypto.tink.proto.EciesAeadHkdfKeyFormat +import com.google.crypto.tink.proto.EciesAeadHkdfParams +import com.google.crypto.tink.proto.EciesHkdfKemParams +import com.google.crypto.tink.proto.EllipticCurveType +import com.google.crypto.tink.proto.HashType +import java.io.ByteArrayOutputStream +import java.security.GeneralSecurityException +import java.security.KeyStore +import javax.crypto.KeyGenerator + +/** + * [Security Component: Tink-based Hybrid Encryption] + * * Implementation relies on Google Tink's `AndroidKeysetManager` and `KeysetHandle`. + * * This class leverages validated library implementations for cryptographic schemes. + * + * [Compliance Note] + * * **FCS_CKM.2/LOCKED (Cryptographic Key Establishment):** + * - SATISFIED: Uses Tink's ECIES-AEAD-HKDF implementation to establish keys for encryption + * even while the device is in a Locked State. + * + * * **FCS_STG_EXT.2 (Encrypted Key Storage):** + * - SATISFIED: Private keysets are stored in SharedPreferences wrapped (encrypted) by a Master Key + * held in the Android Keystore. The keyset is never stored in plaintext on the filesystem. + * + * * **FDP_DAR_EXT.2 (Sensitive Data Encryption):** + * - SATISFIED: Implements public key encryption (ECIES-AEAD-HKDF) allowing data ingestion and protection + * while the device is in a Locked State (B/F/U states). + * + * * **FIA_UAU_EXT.1 (Authentication for Cryptographic Operation):** + * - SATISFIED: The Master Key (wrapping key) is configured with `.setUnlockedDeviceRequired(true)`. + * Tink cannot unwrap (decrypt) the Keyset containing the private key unless the user has authenticated. + * + * * **FCS_CKM_EXT.4 (Key Destruction):** + * - PARTIALLY SATISFIED (Storage Only): `destroy()` removes the encrypted keyset and the Master Key alias. + * - NOTE: Volatile memory zeroization relies on the underlying Tink library implementation and JVM + * Garbage Collection. (For explicit memory zeroization requirements, see `RawHybridKeyProvider`). + */ +class HybridKeyProvider( + private val context: Context, + private val masterKeyUri: String, + _unlockedDeviceRequired: Boolean, + private val keysetPrefName: String +) : KeyProvider { + + private val deviceProtectedContext = context.createDeviceProtectedStorageContext() + companion object { + val P521_AES256_GCM_TEMPLATE: KeyTemplate by lazy { + val demAeadKeyFormat = AesGcmKeyFormat.newBuilder().setKeySize(32).build() + val demKeyTemplate = com.google.crypto.tink.proto.KeyTemplate.newBuilder() + .setValue(demAeadKeyFormat.toByteString()) + .setTypeUrl("type.googleapis.com/google.crypto.tink.AesGcmKey") + .setOutputPrefixType(com.google.crypto.tink.proto.OutputPrefixType.TINK) + .build() + val demParams = EciesAeadDemParams.newBuilder().setAeadDem(demKeyTemplate).build() + val kemParams = EciesHkdfKemParams.newBuilder() + .setCurveType(EllipticCurveType.NIST_P521) + .setHkdfHashType(HashType.SHA512) + .build() + val eciesParams = EciesAeadHkdfParams.newBuilder() + .setKemParams(kemParams) + .setDemParams(demParams) + .setEcPointFormat(EcPointFormat.UNCOMPRESSED) + .build() + val keyFormat = EciesAeadHkdfKeyFormat.newBuilder() + .setParams(eciesParams) + .build() + KeyTemplate.create( + "type.googleapis.com/google.crypto.tink.EciesAeadHkdfPrivateKey", + keyFormat.toByteString().toByteArray(), + KeyTemplate.OutputPrefixType.TINK + ) + } + } + + private val PRIVATE_KEYSET_NAME = "hybrid_private_keyset" + private val PUBLIC_KEYSET_PREF_NAME = "hybrid_public_keyset_pref" + private val PUBLIC_KEYSET_KEY = "public_keyset" + val unlockedDeviceRequired: Boolean = _unlockedDeviceRequired + + init { + AeadConfig.register() + HybridConfig.register() + try { + createMasterKeyIfNeeded() + synchronizePublicKeyset() + } catch (e: Exception) { + Log.w("HybridKeyProvider", "Initialization sync failed, will retry later: ${e.message}") + } + } + + private fun getPublicKeysetHandle(): KeysetHandle { + val prefs = deviceProtectedContext.getSharedPreferences(PUBLIC_KEYSET_PREF_NAME, Context.MODE_PRIVATE) + var serializedPublicKeyset = prefs.getString(PUBLIC_KEYSET_KEY, null) + + if (serializedPublicKeyset == null) { + // Public keyset is not found, so we need to generate and save it now. + // This might fail if the device is locked. + synchronizePublicKeyset() + serializedPublicKeyset = prefs.getString(PUBLIC_KEYSET_KEY, null) + } + + return serializedPublicKeyset?.let { + CleartextKeysetHandle.read(JsonKeysetReader.withString(it)) + } ?: throw GeneralSecurityException( + "Could not get or create public keyset. Device might be locked." + ) + } + + private fun synchronizePublicKeyset() { + try { + // Get the private keyset, which may trigger key generation if it doesn't exist + val privateKeysetManager: AndroidKeysetManager by lazy { + AndroidKeysetManager.Builder() + .withSharedPref( deviceProtectedContext, PRIVATE_KEYSET_NAME, keysetPrefName) + .withKeyTemplate(P521_AES256_GCM_TEMPLATE) + .withMasterKeyUri(masterKeyUri) + .build() + } + //Extract the public keyset + val publicKeysetHandle = privateKeysetManager.keysetHandle.publicKeysetHandle + + // Serialize the public keyset to a string + val outputStream = ByteArrayOutputStream() + CleartextKeysetHandle.write( + publicKeysetHandle, JsonKeysetWriter.withOutputStream(outputStream) + ) + val serializedPublicKeyset = outputStream.toString() + + // Manually write the serialized public keyset to a separate shared preference. + deviceProtectedContext.getSharedPreferences(PUBLIC_KEYSET_PREF_NAME, Context.MODE_PRIVATE) + .edit(commit = true) { + putString(PUBLIC_KEYSET_KEY, serializedPublicKeyset) + } + } catch (e: GeneralSecurityException) { + // This can happen if the device is locked and the private key is not in memory. + Log.w( + "HybridKeyProvider", + "Could not synchronize public keyset, device might be locked.", + e + ) + // Re-throw the exception to notify the caller that the operation failed. + throw e + } + } + + override fun getUnlockDeviceRequired(): Boolean { + return unlockedDeviceRequired + } + + override fun rewrapKeyToSymmetricUdr(encryptedDek: ByteArray): ByteArray { + TODO("Not yet implemented") + } + + override fun isSymmetricallyWrapped(encryptedDek: ByteArray): Boolean { + TODO("Not yet implemented") + } + + private fun createMasterKeyIfNeeded() { + val keyAlias = masterKeyUri.removePrefix("android-keystore://") + val keyStore = KeyStore.getInstance("AndroidKeyStore") + keyStore.load(null) + if (!keyStore.containsAlias(keyAlias)) { + val keyGenerator = + KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + val specBuilder = KeyGenParameterSpec.Builder( + keyAlias, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + + // [FIA_UAU_EXT.1] Authentication for Cryptographic Operation + // * REQUIREMENT: The TSF shall require the user to be authenticated before performing specific cryptographic operations. + // * IMPLEMENTATION: By invoking `setUnlockedDeviceRequired(true)`, we mandate that the Android Keystore system + // blocks any access to this key material unless the device is in an unlocked state (user authenticated). + if (unlockedDeviceRequired) { + specBuilder.setUnlockedDeviceRequired(true) + } + keyGenerator.init(specBuilder.build()) + keyGenerator.generateKey() + } + } + + override fun getAead(): Aead { + + // [FCS_CKM.2/LOCKED] & [FDP_DAR_EXT.2] + // Public key from Keyset allows key establishment and encryption in Locked State. + // This does not require the device to be unlocked as the public key is stored in cleartext. + val publicKeysetHandle = getPublicKeysetHandle() + val hybridEncrypt = publicKeysetHandle.getPrimitive(HybridEncrypt::class.java) + + return object : Aead { + override fun encrypt(plaintext: ByteArray, associatedData: ByteArray): ByteArray { + // [FDP_DAR_EXT.2] Public key encryption allows operation in Locked State + return hybridEncrypt.encrypt(plaintext, associatedData) + } + + override fun decrypt(ciphertext: ByteArray, associatedData: ByteArray): ByteArray { + // [FCS_STG_EXT.2] Private key is wrapped by Android Keystore (Master Key) + //Don't hold the private key and Manager in memory. + AndroidKeysetManager.Builder() + .withSharedPref( deviceProtectedContext, PRIVATE_KEYSET_NAME, keysetPrefName) + .withKeyTemplate(P521_AES256_GCM_TEMPLATE) + .withMasterKeyUri(masterKeyUri) + .build().let { privateKeysetManager -> + val privateKeysetHandle = privateKeysetManager.keysetHandle + val hybridDecrypt = privateKeysetHandle.getPrimitive(HybridDecrypt::class.java) + return hybridDecrypt.decrypt(ciphertext, associatedData) + } + + } + } + } + + override fun destroy() { + // Clear the private keyset preference file. + // NOTE: Tink's SharedPrefKeysetReader/Writer internally call Context.getApplicationContext(), + // so the private keyset is actually stored in credential-encrypted (CE) storage even though + // a device-protected context is passed to AndroidKeysetManager. Clear both locations so that + // no stale keyset (encrypted under a deleted master key) survives. + context.applicationContext.getSharedPreferences(keysetPrefName, Context.MODE_PRIVATE).edit(commit = true) { + clear() + } + deviceProtectedContext.getSharedPreferences(keysetPrefName, Context.MODE_PRIVATE).edit(commit = true) { + clear() + } + // Clear the public keyset preference file + deviceProtectedContext.getSharedPreferences(PUBLIC_KEYSET_PREF_NAME, Context.MODE_PRIVATE) + .edit(commit = true) { + clear() + } + + try { + val keyStore = KeyStore.getInstance("AndroidKeyStore") + keyStore.load(null) + val keyAlias = masterKeyUri.removePrefix("android-keystore://") + if (keyStore.containsAlias(keyAlias)) { + keyStore.deleteEntry(keyAlias) + } + } catch (e: Exception) { + Log.e("HybridKeyProvider", "Failed to destroy master key", e) + } + } +} + + + diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/KeyProvider.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/KeyProvider.kt new file mode 100644 index 0000000..1ee2bd7 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/KeyProvider.kt @@ -0,0 +1,49 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.encryption.internal.keymanagement + +import com.google.crypto.tink.Aead +import com.google.crypto.tink.StreamingAead + +/** + * A common interface for key providers, allowing different underlying key management + * strategies (hardware-backed, software-only, etc.) to be used interchangeably. + */ +interface KeyProvider { + /** + * Retrieves the AEAD primitive for performing cryptographic operations. + */ + fun getAead(): Aead + + /** + * Retrieves the StreamingAead primitive for performing streaming cryptographic operations. + * Returns null if streaming is not supported by this provider. + */ + fun getStreamingAead(): StreamingAead? = null + + fun getUnlockDeviceRequired(): Boolean + + //new methods for rewrapping with UDR symmetric keys + fun rewrapKeyToSymmetricUdr(encryptedDek: ByteArray): ByteArray + + fun isSymmetricallyWrapped(encryptedDek: ByteArray): Boolean + + /** + * Destroys all cryptographic material associated with this provider. + */ + fun destroy() +} + diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/NoOpKeyProvider.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/NoOpKeyProvider.kt new file mode 100644 index 0000000..90f5b20 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/NoOpKeyProvider.kt @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2026 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. + */ + +package com.android.niapsec.encryption.internal.keymanagement + +import com.google.crypto.tink.Aead +import com.google.crypto.tink.StreamingAead +import java.io.FilterInputStream +import java.io.FilterOutputStream +import java.io.InputStream +import java.io.OutputStream +import java.nio.channels.ReadableByteChannel +import java.nio.channels.SeekableByteChannel +import java.nio.channels.WritableByteChannel + +/** + * INSECURE / DEMO COMPARISON ONLY. + * + * A pass-through [KeyProvider] that performs NO encryption and enforces NO device lock + * requirement. Exists strictly to visually contrast unencrypted storage against SDP-compliant + * providers (such as [RawHybridKeyProvider]) when switching implementations inside + * `encryption-lib`. + * + * TODO(security): Do NOT use in production builds; intended strictly for side-by-side security + * demonstrations illustrating the exposure of unencrypted locked-state data at rest. + */ +class NoOpKeyProvider : KeyProvider { + + private val passthroughAead: Aead = object : Aead { + override fun encrypt(plaintext: ByteArray, associatedData: ByteArray): ByteArray { + return plaintext.copyOf() + } + + override fun decrypt(ciphertext: ByteArray, associatedData: ByteArray): ByteArray { + return ciphertext.copyOf() + } + } + + private val passthroughStreamingAead: StreamingAead = object : StreamingAead { + override fun newEncryptingChannel( + ciphertextDestination: WritableByteChannel, + associatedData: ByteArray + ): WritableByteChannel = ciphertextDestination + + override fun newSeekableDecryptingChannel( + ciphertextSource: SeekableByteChannel, + associatedData: ByteArray + ): SeekableByteChannel = ciphertextSource + + override fun newDecryptingChannel( + ciphertextSource: ReadableByteChannel, + associatedData: ByteArray + ): ReadableByteChannel = ciphertextSource + + override fun newEncryptingStream( + ciphertextDestination: OutputStream, + associatedData: ByteArray + ): OutputStream = object : FilterOutputStream(ciphertextDestination) { + override fun write(b: ByteArray, off: Int, len: Int) { + out.write(b, off, len) + } + } + + override fun newDecryptingStream( + ciphertextSource: InputStream, + associatedData: ByteArray + ): InputStream = object : FilterInputStream(ciphertextSource) {} + } + + override fun getAead(): Aead = passthroughAead + + override fun getStreamingAead(): StreamingAead = passthroughStreamingAead + + override fun getUnlockDeviceRequired(): Boolean = false + + override fun rewrapKeyToSymmetricUdr(encryptedDek: ByteArray): ByteArray = encryptedDek + + override fun isSymmetricallyWrapped(encryptedDek: ByteArray): Boolean = true + + override fun destroy() { + // No cryptographic keys are allocated in Keystore or preferences. + } +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/RawHybridKeyProvider.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/RawHybridKeyProvider.kt new file mode 100644 index 0000000..6aba54f --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/RawHybridKeyProvider.kt @@ -0,0 +1,1144 @@ +/* + * Copyright (C) 2026 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. + */ + +package com.android.niapsec.encryption.internal.keymanagement + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import android.util.Log +import androidx.core.content.edit +import com.android.niapsec.encryption.tools.CleanSecretKeySpec +import com.android.niapsec.encryption.tools.SafeHkdf +import com.android.niapsec.encryption.internal.ZeroizingCipherDecryptInputStream +import com.android.niapsec.encryption.internal.ZeroizingCipherEncryptOutputStream +import com.android.niapsec.encryption.internal.clearCipherState +import com.android.niapsec.encryption.tools.SecurityAuditLogger +import com.google.crypto.tink.Aead +import com.google.crypto.tink.StreamingAead +import java.io.ByteArrayOutputStream +import java.io.DataInputStream +import java.io.DataOutputStream +import java.io.InputStream +import java.io.OutputStream +import java.nio.ByteBuffer +import java.nio.channels.ReadableByteChannel +import java.nio.channels.SeekableByteChannel +import java.nio.channels.WritableByteChannel +import java.security.GeneralSecurityException +import java.security.Key +import java.security.KeyFactory +import java.security.KeyPair +import java.security.KeyPairGenerator +import java.security.KeyStore +import java.security.PrivateKey +import java.security.PublicKey +import java.security.SecureRandom +import java.security.spec.ECGenParameterSpec +import java.security.spec.X509EncodedKeySpec +import javax.crypto.Cipher +import javax.crypto.KeyAgreement +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** + * [Security Component: Raw JCA Hybrid Encryption] + * * Custom implementation using Java Cryptography Architecture (JCA) primitives. + * * This class provides direct control over key material life-cycle and memory management. + * + * [Compliance Note] + * * **FCS_STG_EXT.2 (Encrypted Key Storage):** + * - SATISFIED: Private keys are generated and stored directly within the Android Keystore + * (`AndroidKeyStore` provider), ensuring they are never exposed in plaintext to the application layer. + * + * * **FCS_CKM_EXT.4 (Key Destruction):** + * - SATISFIED: This implementation explicitly overwrites sensitive key material (DEK, Shared Secret) + * with zeros in `finally` blocks immediately after use. This provides deterministic destruction + * of keys in volatile memory, independent of Garbage Collection timing. + * - SATISFIED: Persistent keys are destroyed via `KeyStore.deleteEntry()` and `SharedPreferences.Editor.clear()`. + * + * * **FDP_DAR_EXT.2 (Sensitive Data Encryption):** + * - SATISFIED: Uses an asymmetric key scheme to allow data encryption even when the device is locked + * and the private key is unavailable. + * + * * **FIA_UAU_EXT.1 (Authentication for Cryptographic Operation):** + * - SATISFIED: Enforces user authentication policies at the OS level by configuring + * `KeyGenParameterSpec.Builder.setUnlockedDeviceRequired(true)`. This ensures that decryption + * operations fail if the device is not unlocked. + */ +class RawHybridKeyProvider( + private val context: Context, + private val masterKeyUri: String, + _unlockedDeviceRequired: Boolean, + private val keysetPrefName: String, + private val lockStatePollCount: Int = 5, + private val lockStatePollIntervalMs: Long = 100 +) : KeyProvider { + + private val masterKeyAlias = masterKeyUri.removePrefix("android-keystore://") + private val symmetricMasterKeyAlias = "${masterKeyAlias}_symmetric" + private val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) } + val unlockedDeviceRequired: Boolean = _unlockedDeviceRequired + + private val storageContext: Context = context.createDeviceProtectedStorageContext() + + private val prefs = storageContext.getSharedPreferences(keysetPrefName, Context.MODE_PRIVATE) + + companion object { + private const val ANDROID_KEYSTORE = "AndroidKeyStore" + private const val KEY_PUBLIC_KEY_PREF = "master_public_key" + private const val EC_KEY_ALGORITHM = KeyProperties.KEY_ALGORITHM_EC + private const val KEY_AGREEMENT_ALGORITHM = "ECDH" + private const val DEK_ALGORITHM = "AES" + private const val DEK_WRAPPING_CIPHER = "AES/GCM/NoPadding" + private const val DEK_SIZE_BITS = 256 + private const val DATA_CIPHER = "AES/GCM/NoPadding" + private const val GCM_TAG_LENGTH_BITS = 128 + const val MAGIC_BYTE_ASYMMETRIC: Byte = 0x01 // Temporary storage while locked (current Hybrid scheme) + const val MAGIC_BYTE_SYMMETRIC: Byte = 0x02 // Re-encrypted after unlock (symmetric UDR scheme) + val dummyPubKey: PublicKey by lazy { + val kpg = KeyPairGenerator.getInstance("EC") + kpg.initialize(java.security.spec.ECGenParameterSpec("secp521r1")) + kpg.generateKeyPair().public + } + } + + init { + generateAndStoreKeyPairIfNeeded() + generateSymmetricEcKeyPairIfNeeded() + generateSymmetricMasterKeyIfNeeded() + generateWrappingKeyIfNeeded() + } + + private fun getFlushIterations(): Int { + return context.getSharedPreferences("niap_sec_prefs", Context.MODE_PRIVATE) + .getInt("keystore_flush_iterations", 0) + } + + private fun flushKeystoreIpcBuffers() { + val iterations = getFlushIterations() + if (iterations <= 0) { + return // Skip flush processing if the setting is 0 or less + } + + val startTime = System.currentTimeMillis() + try { + val dummyDek = ByteArray(DEK_SIZE_BITS / 8) + val masterKey = keyStore.getKey(symmetricMasterKeyAlias, null) ?: return + val flushCipher = Cipher.getInstance(DEK_WRAPPING_CIPHER) + + for (i in 0 until iterations) { + flushCipher.init(Cipher.ENCRYPT_MODE, masterKey) + flushCipher.doFinal(dummyDek) + } + val elapsed = System.currentTimeMillis() - startTime + Log.d("RawHybridKeyProvider", "Keystore IPC flush completed: $iterations iterations took ${elapsed}ms") + SecurityAuditLogger.logLine("Keystore IPC flush ($iterations runs) took ${elapsed}ms") + } catch (e: Exception) { + val elapsed = System.currentTimeMillis() - startTime + Log.w("RawHybridKeyProvider", "Keystore IPC flush failed after ${elapsed}ms: ${e.message}") + } + } + + private fun generateSymmetricMasterKeyIfNeeded() { + if (!keyStore.containsAlias(symmetricMasterKeyAlias)) { + val keyGenerator = javax.crypto.KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE) + val specBuilder = KeyGenParameterSpec.Builder( + symmetricMasterKeyAlias, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + + // MDFPP Requirement: Enforce user authentication for symmetric protection + specBuilder.setUnlockedDeviceRequired(unlockedDeviceRequired) + + keyGenerator.init(specBuilder.build()) + keyGenerator.generateKey() + } + } + + private fun generateWrappingKeyIfNeeded() { + val wrappingKeyAlias = "${masterKeyAlias}_wrapping" + if (!keyStore.containsAlias(wrappingKeyAlias)) { + val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEYSTORE) + val spec = KeyGenParameterSpec.Builder( + wrappingKeyAlias, + KeyProperties.PURPOSE_WRAP_KEY + ) + .setKeySize(2048) + .setDigests(KeyProperties.DIGEST_SHA256) // Specify SHA-256 only to align with CTS + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) + .setUnlockedDeviceRequired(unlockedDeviceRequired) + .build() + kpg.initialize(spec) + kpg.generateKeyPair() + } + } + + private fun generateAndStoreKeyPairIfNeeded() { + + if (keyStore.containsAlias(masterKeyAlias)) { + if (!prefs.contains(KEY_PUBLIC_KEY_PREF)) { + try { + val entry = keyStore.getEntry(masterKeyAlias, null) as? KeyStore.PrivateKeyEntry + entry?.certificate?.publicKey?.let { publicKey -> + savePublicKey(publicKey) + } + } catch (e: Exception) { + // Key might be broken!, only record the log in this time. + } + } + } else { + // New key generation + val kpg = KeyPairGenerator.getInstance(EC_KEY_ALGORITHM, ANDROID_KEYSTORE) + val spec = KeyGenParameterSpec.Builder( + masterKeyAlias, + KeyProperties.PURPOSE_AGREE_KEY + ) + .setAlgorithmParameterSpec(ECGenParameterSpec("secp521r1")) + .setDigests(KeyProperties.DIGEST_SHA512) + // [FIA_UAU_EXT.1] Authentication for Cryptographic Operation + // * ENFORCEMENT: Configures the TSF (Android Keystore) to reject key agreement operations + // if the user has not authenticated (device locked). + .setUnlockedDeviceRequired(unlockedDeviceRequired) + .build() + + kpg.initialize(spec) + val keyPair = kpg.generateKeyPair() + + savePublicKey(keyPair.public) + } + } + + /** + * WORKAROUND [FCS_CKM_EXT.4]: Generates a dedicated hardware-backed EC key pair for Symmetric mode + * to perform ECDH key agreement. This is a workaround for residual plaintext key material observed + * in IPC buffers when passing raw DEKs directly to Keystore2 for symmetric wrapping (caused by a + * Keystore2 issue and missing zeroization at the KeyMint / Binder boundary). + * By using ECDH, the raw DEK never leaves the application process during wrapping. + */ + private fun generateSymmetricEcKeyPairIfNeeded() { + val symmetricEcAlias = "${masterKeyAlias}_symmetric_ec" + if (keyStore.containsAlias(symmetricEcAlias)) { + val prefsKey = "${KEY_PUBLIC_KEY_PREF}_symmetric" + if (!prefs.contains(prefsKey)) { + try { + val entry = keyStore.getEntry(symmetricEcAlias, null) as? KeyStore.PrivateKeyEntry + entry?.certificate?.publicKey?.let { publicKey -> + saveSymmetricPublicKey(publicKey) + } + } catch (e: Exception) { + // Key might be broken + } + } + } else { + val kpg = KeyPairGenerator.getInstance(EC_KEY_ALGORITHM, ANDROID_KEYSTORE) + val spec = KeyGenParameterSpec.Builder( + symmetricEcAlias, + KeyProperties.PURPOSE_AGREE_KEY + ) + .setAlgorithmParameterSpec(ECGenParameterSpec("secp521r1")) + .setDigests(KeyProperties.DIGEST_SHA512) + .setUnlockedDeviceRequired(true) // ALWAYS UDR + .build() + + kpg.initialize(spec) + val keyPair = kpg.generateKeyPair() + + saveSymmetricPublicKey(keyPair.public) + } + } + + private fun saveSymmetricPublicKey(publicKey: PublicKey) { + val prefsKey = "${KEY_PUBLIC_KEY_PREF}_symmetric" + val encodedKey = Base64.encodeToString(publicKey.encoded, Base64.NO_WRAP) + prefs.edit().putString(prefsKey, encodedKey).apply() + } + + private fun savePublicKey(publicKey: PublicKey) { + val encodedKey = Base64.encodeToString(publicKey.encoded, Base64.NO_WRAP) + prefs.edit().putString(KEY_PUBLIC_KEY_PREF, encodedKey).apply() + } + + private fun loadRecipientPublicKey(): PublicKey { + val encodedKey = prefs.getString(KEY_PUBLIC_KEY_PREF, null) + ?: throw GeneralSecurityException("Master public key not found in SharedPreferences.") + val bytes = Base64.decode(encodedKey, Base64.NO_WRAP) + val spec = X509EncodedKeySpec(bytes) + return KeyFactory.getInstance(EC_KEY_ALGORITHM).generatePublic(spec) + } + + private fun loadSymmetricPublicKey(): PublicKey { + val prefsKey = "${KEY_PUBLIC_KEY_PREF}_symmetric" + val encodedKey = prefs.getString(prefsKey, null) + ?: throw GeneralSecurityException("Symmetric UDR public key not found in SharedPreferences.") + val bytes = Base64.decode(encodedKey, Base64.NO_WRAP) + val spec = X509EncodedKeySpec(bytes) + return KeyFactory.getInstance(EC_KEY_ALGORITHM).generatePublic(spec) + } + + private fun loadRecipientPrivateKey(): PrivateKey { + val entry = keyStore.getEntry(masterKeyAlias, null) + ?: throw GeneralSecurityException("Master key alias not found in Keystore: $masterKeyAlias") + if (entry !is KeyStore.PrivateKeyEntry) { + throw GeneralSecurityException("Keystore entry is not a private key: $masterKeyAlias") + } + return entry.privateKey + } + + private fun loadSymmetricRecipientPrivateKey(): PrivateKey { + val symmetricEcAlias = "${masterKeyAlias}_symmetric_ec" + val entry = keyStore.getEntry(symmetricEcAlias, null) + ?: throw GeneralSecurityException("Symmetric UDR key alias not found in Keystore: $symmetricEcAlias") + if (entry !is KeyStore.PrivateKeyEntry) { + throw GeneralSecurityException("Keystore entry is not a private key: $symmetricEcAlias") + } + return entry.privateKey + } + + private fun hkdfDerive(ikm: ByteArray, salt: ByteArray, info: ByteArray): ByteArray { + return SafeHkdf.computeHkdf(ikm, salt, info, 32) + } + + + /** + * Intentionally overwrites (poisons) the residual CBOR (66-byte remnants) + * left in the Keystore2 / Binder IPC shared buffer with dummy data. + * Executes concurrently across multiple threads so that the kernel Binder driver + * dispatches dummy ECDH operations to all active Binder worker threads and their + * per-thread Scudo TSD size-class caches in KeyMint HAL and Keystore2. + */ + private fun flushKeystoreBinderBuffer(keystorePrivateKey: PrivateKey) { + try { + // Dispatch concurrent dummy ECDH agreements across parallel threads + // to force Binder thread-pool fan-out across all KeyMint / Keystore2 worker threads. + val parallelThreads = 6 + val roundsPerThread = 2 + val startLatch = java.util.concurrent.CountDownLatch(1) + val doneLatch = java.util.concurrent.CountDownLatch(parallelThreads) + + for (t in 0 until parallelThreads) { + Thread { + try { + val dummyAgreement = KeyAgreement.getInstance("ECDH", "AndroidKeyStore") + startLatch.await() + for (r in 0 until roundsPerThread) { + dummyAgreement.init(keystorePrivateKey) + dummyAgreement.doPhase(dummyPubKey, true) + val dummySecret = dummyAgreement.generateSecret() + dummySecret?.fill(0) + } + } catch (_: Exception) { + } finally { + doneLatch.countDown() + } + }.start() + } + startLatch.countDown() + doneLatch.await(5, java.util.concurrent.TimeUnit.SECONDS) + + Log.d("KMD", "Binder buffer successfully poisoned (${parallelThreads}x${roundsPerThread} concurrent).") + } catch (e: Exception) { + // Flush failures are only logged and do not impact the main decryption process + Log.w("KMD", "Binder buffer flush failed (ignored)", e) + } + } + + /** + * Polls the device lock state multiple times to ensure accuracy. + */ + private fun isDeviceLockedReliably(): Boolean { + val km = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager + for (i in 1..lockStatePollCount) { + if (km.isDeviceLocked) return true + if (i < lockStatePollCount) { + try { Thread.sleep(lockStatePollIntervalMs) } catch (e: Exception) {} + } + } + return false + } + + private val rawHybridAead: Aead = object : Aead { + override fun encrypt(plaintext: ByteArray, associatedData: ByteArray): ByteArray { + // [FDP_DAR_EXT.2.4] If device is unlocked, prefer symmetric encryption (0x02) + if (!isDeviceLockedReliably()) { + try { + return encryptSymmetric(plaintext, associatedData) + } catch (e: Exception) { + Log.w("RawHybridKeyProvider", "Symmetric encryption failed, falling back to asymmetric", e) + } + } + return encryptAsymmetric(plaintext, associatedData) + } + + private fun encryptSymmetric(plaintext: ByteArray, associatedData: ByteArray): ByteArray { + val recipientPubKey = loadSymmetricPublicKey() + val dekBytes = ByteArray(DEK_SIZE_BITS / 8) + var sharedSecret: ByteArray? = null + var kekBytes: ByteArray? = null + var ephemeralKeyPair: KeyPair? = null + + var dekSpec: CleanSecretKeySpec? = null + var kekSpec: CleanSecretKeySpec? = null + var dataCipher: Cipher? = null + var wrapCipher: Cipher? = null + + try { + SecureRandom().nextBytes(dekBytes) + dekSpec = CleanSecretKeySpec(dekBytes, DEK_ALGORITHM) + dataCipher = Cipher.getInstance(DATA_CIPHER) + dataCipher.init(Cipher.ENCRYPT_MODE, dekSpec) + dataCipher.updateAAD(associatedData) + val encryptedContent = dataCipher.doFinal(plaintext) + val dataIv = dataCipher.iv + val ephemeralKpg = KeyPairGenerator.getInstance(EC_KEY_ALGORITHM).apply { initialize(ECGenParameterSpec("secp521r1")) } + val keyPair = ephemeralKpg.generateKeyPair() + ephemeralKeyPair = keyPair + + + val keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM) + keyAgreement.init(keyPair.private) + + keyAgreement.doPhase(recipientPubKey, true) + sharedSecret = keyAgreement.generateSecret() + + // Use masterKeyAlias + "_symmetric" for context to distinguish from asymmetric HKDF context + val contextString = "${masterKeyAlias}_symmetric_ec" + kekBytes = + hkdfDerive( + sharedSecret!!, + contextString.toByteArray(Charsets.UTF_8), + keyPair.public.encoded + ) + + kekSpec = CleanSecretKeySpec(kekBytes, DEK_ALGORITHM) + + wrapCipher = Cipher.getInstance(DEK_WRAPPING_CIPHER) + wrapCipher.init(Cipher.ENCRYPT_MODE, kekSpec) + val wrappedDek = wrapCipher.doFinal(dekBytes) + val wrapIv = wrapCipher.iv + + return serializeEncryptedPackage( + MAGIC_BYTE_SYMMETRIC, + keyPair.public.encoded, + wrappedDek, + wrapIv, + encryptedContent, + dataIv + ) + + } finally { + SecurityAuditLogger.logLine("===== Encrypt symmetric (Solution 2 - ECDH) =====") + SecurityAuditLogger.logKeyMaterial("Ephemeral Key Pair Public Key", ephemeralKeyPair?.public?.encoded) + val ephPrivBytes = ephemeralKeyPair?.private?.encoded + SecurityAuditLogger.logKeyMaterial("Ephemeral Key Pair Private Key", ephPrivBytes) + ephPrivBytes?.fill(0)//Have to clear just for this logging + SecurityAuditLogger.logKeyMaterial("Recipient UDR Key Pair (Public Key)", recipientPubKey.encoded) + SecurityAuditLogger.logKeyMaterial("Shared Secret", sharedSecret) + SecurityAuditLogger.logKeyMaterial("Symmetric KEK", kekBytes) + SecurityAuditLogger.logKeyMaterial("Data Encryption Key (DEK)", dekBytes) + + dekBytes.fill(0) + sharedSecret?.fill(0) + kekBytes?.fill(0) + + dekSpec?.let { if (!it.isDestroyed) it.destroy() } + kekSpec?.let { if (!it.isDestroyed) it.destroy() } + dataCipher?.let { clearCipherState(it) } + wrapCipher?.let { clearCipherState(it) } + } + } + + private fun encryptAsymmetric(plaintext: ByteArray, associatedData: ByteArray): ByteArray { + val recipientPubKey = loadRecipientPublicKey() + val dekBytes = ByteArray(DEK_SIZE_BITS / 8) + var sharedSecret: ByteArray? = null + var kekBytes: ByteArray? = null + var ephemeralKeyPair: KeyPair? = null + + var dekSpec: CleanSecretKeySpec? = null + var kekSpec: CleanSecretKeySpec? = null + var dataCipher: Cipher? = null + var wrapCipher: Cipher? = null + + try { + SecureRandom().nextBytes(dekBytes) + dekSpec = CleanSecretKeySpec(dekBytes, DEK_ALGORITHM) + dataCipher = Cipher.getInstance(DATA_CIPHER) + dataCipher.init(Cipher.ENCRYPT_MODE, dekSpec) + dataCipher.updateAAD(associatedData) + val encryptedContent = dataCipher.doFinal(plaintext) + val dataIv = dataCipher.iv + val ephemeralKpg = KeyPairGenerator.getInstance(EC_KEY_ALGORITHM).apply { initialize(ECGenParameterSpec("secp521r1")) } + //TSF does not store the ephemeral private key and relies on JVM object scope for transient cleanup + val keyPair = ephemeralKpg.generateKeyPair() + + ephemeralKeyPair = keyPair + + val keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM) + keyAgreement.init(keyPair.private) + + keyAgreement.doPhase(recipientPubKey, true) + sharedSecret = keyAgreement.generateSecret() + kekBytes = + hkdfDerive( + sharedSecret!!, + masterKeyAlias.toByteArray(Charsets.UTF_8), + keyPair.public.encoded + ) + + kekSpec = CleanSecretKeySpec(kekBytes!!, DEK_ALGORITHM) + + wrapCipher = Cipher.getInstance(DEK_WRAPPING_CIPHER) + wrapCipher.init(Cipher.ENCRYPT_MODE, kekSpec) + val wrappedDek = wrapCipher.doFinal(dekBytes) + val wrapIv = wrapCipher.iv + + return serializeEncryptedPackage( + MAGIC_BYTE_ASYMMETRIC, + keyPair.public.encoded, + wrappedDek, + wrapIv, + encryptedContent, + dataIv + ) + + } finally { + SecurityAuditLogger.logLine( "===== Encrypt asymmetric =====") + SecurityAuditLogger.logKeyMaterial("Ephemeral Key Pair Public Key", ephemeralKeyPair?.public?.encoded) + val ephPrivBytes = ephemeralKeyPair?.private?.encoded + SecurityAuditLogger.logKeyMaterial("Ephemeral Key Pair Private Key", ephPrivBytes) + ephPrivBytes?.fill(0) + SecurityAuditLogger.logKeyMaterial("Recipient UDR Key Pair (Public Key)", recipientPubKey.encoded) + + SecurityAuditLogger.logKeyMaterial("Shared Secret", sharedSecret) + SecurityAuditLogger.logKeyMaterial("Asymmetric KEK", kekBytes) + SecurityAuditLogger.logKeyMaterial("Data Encryption Key (DEK)", dekBytes) + + // [FCS_CKM_EXT.4] Explicit zeroization: Prevent key remanence in memory + dekBytes.fill(0); sharedSecret?.fill(0); kekBytes?.fill(0) + + dekSpec?.let { + if (!it.isDestroyed) { + it.destroy() + } + } + kekSpec?.let { + if (!it.isDestroyed) { + it.destroy() + } + } + dataCipher?.let { clearCipherState(it) } + wrapCipher?.let { clearCipherState(it) } + } + } + + override fun decrypt(ciphertext: ByteArray, associatedData: ByteArray): ByteArray { + val pkg = deserializeEncryptedPackage(ciphertext) + var dekBytes: ByteArray? = null + var sharedSecret: ByteArray? = null + var kekBytes: ByteArray? = null + var recipientPrivateKey:Key? = null + + var dekSpec: CleanSecretKeySpec? = null + var kekSpec: CleanSecretKeySpec? = null + + val dataCipher = Cipher.getInstance(DATA_CIPHER) + val unwrapCipher = Cipher.getInstance(DEK_WRAPPING_CIPHER) + try { + if (pkg.magicByte == MAGIC_BYTE_ASYMMETRIC) { + recipientPrivateKey = loadRecipientPrivateKey() + val ephemeralPubKeySpec = X509EncodedKeySpec(pkg.ephemeralPublicKeyBytes!!) + val ephemeralPublicKey = KeyFactory.getInstance(EC_KEY_ALGORITHM).generatePublic(ephemeralPubKeySpec) + + val keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM) + keyAgreement.init(recipientPrivateKey!!) + keyAgreement.doPhase(ephemeralPublicKey, true) + sharedSecret = keyAgreement.generateSecret() + flushKeystoreBinderBuffer(recipientPrivateKey) + + kekBytes = hkdfDerive(sharedSecret!!, masterKeyAlias.toByteArray(Charsets.UTF_8), pkg.ephemeralPublicKeyBytes!!) + kekSpec = CleanSecretKeySpec(kekBytes!!, DEK_ALGORITHM) + + unwrapCipher.init(Cipher.DECRYPT_MODE, kekSpec, GCMParameterSpec(GCM_TAG_LENGTH_BITS, pkg.wrapIv)) + dekBytes = unwrapCipher.doFinal(pkg.wrappedDek) + + } else if (pkg.magicByte == MAGIC_BYTE_SYMMETRIC) { + recipientPrivateKey = loadSymmetricRecipientPrivateKey() + val ephemeralPubKeySpec = X509EncodedKeySpec(pkg.ephemeralPublicKeyBytes!!) + val ephemeralPublicKey = KeyFactory.getInstance(EC_KEY_ALGORITHM).generatePublic(ephemeralPubKeySpec) + + val keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM) + keyAgreement.init(recipientPrivateKey!!) + keyAgreement.doPhase(ephemeralPublicKey, true) + sharedSecret = keyAgreement.generateSecret() + flushKeystoreBinderBuffer(recipientPrivateKey) + + val contextString = "${masterKeyAlias}_symmetric_ec" + kekBytes = hkdfDerive(sharedSecret!!, contextString.toByteArray(Charsets.UTF_8), pkg.ephemeralPublicKeyBytes!!) + kekSpec = CleanSecretKeySpec(kekBytes!!, DEK_ALGORITHM) + + unwrapCipher.init(Cipher.DECRYPT_MODE, kekSpec, GCMParameterSpec(GCM_TAG_LENGTH_BITS, pkg.wrapIv)) + dekBytes = unwrapCipher.doFinal(pkg.wrappedDek) + } else { + throw IllegalArgumentException("Unsupported magic byte") + } + + dekSpec = CleanSecretKeySpec(dekBytes, DEK_ALGORITHM) + dataCipher.init(Cipher.DECRYPT_MODE, dekSpec, GCMParameterSpec(GCM_TAG_LENGTH_BITS, pkg.dataIv)) + dataCipher.updateAAD(associatedData) + + return dataCipher.doFinal(pkg.encryptedContent) + } finally { + // [FCS_CKM_EXT.4] Explicit zeroization: Prevent key remanence in memory + if(pkg.magicByte == MAGIC_BYTE_ASYMMETRIC) { + //Basically this line would not be passed. + SecurityAuditLogger.logLine( "===== Decrypt asymmetric =====") + //Private Key should be null + SecurityAuditLogger.logKeyMaterial("Recipient UDR Key Pair (Private Key)", + recipientPrivateKey?.encoded); + SecurityAuditLogger.logKeyMaterial("Shared Secret", sharedSecret) + SecurityAuditLogger.logKeyMaterial("Asymmetric KEK", kekBytes) + SecurityAuditLogger.logKeyMaterial("Data Encryption Key (DEK)", dekBytes) + pkg.ephemeralPublicKeyBytes?.fill(0) + } else { + SecurityAuditLogger.logLine( "===== Decrypt symmetric =====") + SecurityAuditLogger.logKeyMaterial("Recipient UDR Key Pair (Private Key)", recipientPrivateKey?.encoded) + SecurityAuditLogger.logKeyMaterial("DEK", dekBytes) + SecurityAuditLogger.logKeyMaterial("KEK", kekBytes) + SecurityAuditLogger.logKeyMaterial("Shared Secret", sharedSecret) + pkg.ephemeralPublicKeyBytes?.fill(0) + } + + dekBytes?.fill(0) + kekBytes?.fill(0) + sharedSecret?.fill(0) + + dekSpec?.let { + if (!it.isDestroyed) { + it.destroy() + } + } + kekSpec?.let { + if (!it.isDestroyed) { + it.destroy() + } + } + + try { + // Use 'trackbreadcrumbs' or all-zeros as preferred! + val dummyZeroKey = SecretKeySpec(ByteArray(32), "AES") + + // Random IV generation to completely avoid 'IV reuse error' in GCM mode + val dummyIv = ByteArray(12) + java.security.SecureRandom().nextBytes(dummyIv) + val dummyParams = GCMParameterSpec(128, dummyIv) + + // Wipe the internal cache (DEK) of dataCipher + dataCipher.init(Cipher.ENCRYPT_MODE, dummyZeroKey, dummyParams) + + // Also wipe the internal cache (KEK) of unwrapCipher! + unwrapCipher?.init(Cipher.ENCRYPT_MODE, dummyZeroKey, dummyParams) + + } catch (e: Exception) { + android.util.Log.w("NiapSecAudit", "Wipe hack failed (ignored): ${e.message}") + } + //flushKeystoreIpcBuffers() + + } + } + } + + // --- StreamingAead Implementation --- + private val rawHybridStreamingAead: StreamingAead = object : StreamingAead { + override fun newEncryptingChannel( + ciphertextDestination: WritableByteChannel?, + associatedData: ByteArray? + ): WritableByteChannel? { + TODO("Not yet implemented") + } + + override fun newSeekableDecryptingChannel( + ciphertextSource: SeekableByteChannel?, + associatedData: ByteArray? + ): SeekableByteChannel? { + TODO("Not yet implemented") + } + + override fun newDecryptingChannel( + ciphertextSource: ReadableByteChannel?, + associatedData: ByteArray? + ): ReadableByteChannel? { + TODO("Not yet implemented") + } + + override fun newEncryptingStream(ciphertext: OutputStream, associatedData: ByteArray): OutputStream { + // [FDP_DAR_EXT.2.4] If device is unlocked, prefer symmetric encryption (0x02) + if (!isDeviceLockedReliably()) { + try { + return newEncryptingStreamSymmetric(ciphertext, associatedData) + } catch (e: Exception) { + Log.w("RawHybridKeyProvider", "Symmetric stream encryption failed, falling back to asymmetric", e) + } + } + return newEncryptingStreamAsymmetric(ciphertext, associatedData) + } + + /** + * [FCS_CKM_EXT.4] Solution 2 (ECDH `symmetric_ec`) symmetric stream encryption. + * + * Wraps the 32-byte DEK in-process using a KEK derived from an ephemeral P-521 ECDH + * exchange with the hardware-backed UDR `symmetric_ec` key pair, so the raw plaintext + * DEK never crosses Binder IPC into `keystore2` or `keymint-trusty` (matching the wire + * format of [encryptSymmetric] and [rewrapKeyToSymmetricUdr]). + */ + private fun newEncryptingStreamSymmetric(ciphertext: OutputStream, associatedData: ByteArray): OutputStream { + val recipientPubKey = loadSymmetricPublicKey() + val dekBytes = ByteArray(DEK_SIZE_BITS / 8) + var sharedSecret: ByteArray? = null + var kekBytes: ByteArray? = null + var ephemeralKeyPair: KeyPair? = null + + var dekSpec: CleanSecretKeySpec? = null + var kekSpec: CleanSecretKeySpec? = null + var wrapCipher: Cipher? = null + var dataCipher: Cipher? = null + var streamReturned = false + + try { + SecureRandom().nextBytes(dekBytes) + dekSpec = CleanSecretKeySpec(dekBytes, DEK_ALGORITHM) + + val ephemeralKpg = KeyPairGenerator.getInstance(EC_KEY_ALGORITHM) + .apply { initialize(ECGenParameterSpec("secp521r1")) } + val keyPair = ephemeralKpg.generateKeyPair() + ephemeralKeyPair = keyPair + + val keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM) + keyAgreement.init(keyPair.private) + keyAgreement.doPhase(recipientPubKey, true) + sharedSecret = keyAgreement.generateSecret() + + val contextString = "${masterKeyAlias}_symmetric_ec" + kekBytes = hkdfDerive( + sharedSecret!!, + contextString.toByteArray(Charsets.UTF_8), + keyPair.public.encoded + ) + kekSpec = CleanSecretKeySpec(kekBytes!!, DEK_ALGORITHM) + + wrapCipher = Cipher.getInstance(DEK_WRAPPING_CIPHER) + wrapCipher.init(Cipher.ENCRYPT_MODE, kekSpec) + val wrappedDek = wrapCipher.doFinal(dekBytes) + val wrapIv = wrapCipher.iv + + dataCipher = Cipher.getInstance(DATA_CIPHER) + dataCipher.init(Cipher.ENCRYPT_MODE, dekSpec) + dataCipher.updateAAD(associatedData) + val dataIv = dataCipher.iv + + val dos = DataOutputStream(ciphertext) + dos.writeByte(MAGIC_BYTE_SYMMETRIC.toInt()) + val ephKeyBytes = keyPair.public.encoded + dos.writeInt(ephKeyBytes.size) + dos.write(ephKeyBytes) + dos.writeInt(wrappedDek.size) + dos.write(wrappedDek) + dos.writeInt(wrapIv.size) + dos.write(wrapIv) + dos.writeInt(dataIv.size) + dos.write(dataIv) + dos.flush() + + val keySpecForClose = dekSpec + streamReturned = true + return ZeroizingCipherEncryptOutputStream(ciphertext, dataCipher, keySpecForClose) + } finally { + SecurityAuditLogger.logLine("===== Stream Encrypt symmetric (Solution 2 - ECDH) =====") + SecurityAuditLogger.logKeyMaterial("Ephemeral Key Pair Public Key", ephemeralKeyPair?.public?.encoded) + val ephPrivBytes = ephemeralKeyPair?.private?.encoded + SecurityAuditLogger.logKeyMaterial("Ephemeral Key Pair Private Key", ephPrivBytes) + ephPrivBytes?.fill(0) + SecurityAuditLogger.logKeyMaterial("Recipient UDR Key Pair (Public Key)", recipientPubKey.encoded) + SecurityAuditLogger.logKeyMaterial("Shared Secret", sharedSecret) + SecurityAuditLogger.logKeyMaterial("Symmetric KEK", kekBytes) + SecurityAuditLogger.logKeyMaterial("Data Encryption Key (DEK)", dekBytes) + + dekBytes.fill(0) + sharedSecret?.fill(0) + kekBytes?.fill(0) + kekSpec?.let { if (!it.isDestroyed) it.destroy() } + wrapCipher?.let { clearCipherState(it) } + if (!streamReturned) { + dekSpec?.let { if (!it.isDestroyed) it.destroy() } + dataCipher?.let { clearCipherState(it) } + } + } + } + + private fun newEncryptingStreamAsymmetric(ciphertext: OutputStream, associatedData: ByteArray): OutputStream { + val recipientPubKey = loadRecipientPublicKey() + val dekBytes = ByteArray(DEK_SIZE_BITS / 8) + var sharedSecret: ByteArray? = null + var kekBytes: ByteArray? = null + var ephemeralKeyPair: KeyPair? = null + + var dekSpec: CleanSecretKeySpec? = null + var kekSpec: CleanSecretKeySpec? = null + var wrapCipher: Cipher? = null + var dataCipher: Cipher? = null + var streamReturned = false + + try { + SecureRandom().nextBytes(dekBytes) + dekSpec = CleanSecretKeySpec(dekBytes, DEK_ALGORITHM) + + val ephemeralKpg = KeyPairGenerator.getInstance(EC_KEY_ALGORITHM).apply { initialize(ECGenParameterSpec("secp521r1")) } + val keyPair = ephemeralKpg.generateKeyPair() + ephemeralKeyPair = keyPair + + val keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM) + keyAgreement.init(keyPair.private) + + keyAgreement.doPhase(recipientPubKey, true) + sharedSecret = keyAgreement.generateSecret() + + kekBytes = + hkdfDerive( + sharedSecret!!, + masterKeyAlias.toByteArray(Charsets.UTF_8), + keyPair.public.encoded + ) + + kekSpec = CleanSecretKeySpec(kekBytes, DEK_ALGORITHM) + + wrapCipher = Cipher.getInstance(DEK_WRAPPING_CIPHER) + wrapCipher.init(Cipher.ENCRYPT_MODE, kekSpec) + val wrappedDek = wrapCipher.doFinal(dekBytes) + val wrapIv = wrapCipher.iv + + dataCipher = Cipher.getInstance(DATA_CIPHER) + dataCipher.init(Cipher.ENCRYPT_MODE, dekSpec) + dataCipher.updateAAD(associatedData) + val dataIv = dataCipher.iv + + // Write Header directly to the output stream + val dos = DataOutputStream(ciphertext) + dos.writeByte(MAGIC_BYTE_ASYMMETRIC.toInt()) + val ephKeyBytes = keyPair.public.encoded + + dos.writeInt(ephKeyBytes.size) + dos.write(ephKeyBytes) + dos.writeInt(wrappedDek.size) + dos.write(wrappedDek) + dos.writeInt(wrapIv.size) + dos.write(wrapIv) + dos.writeInt(dataIv.size) + dos.write(dataIv) + dos.flush() + + // [FCS_CKM_EXT.4] Defer DEK zeroization until stream close() so lazy JCA/Conscrypt + // AEAD context initialization does not read a zeroed key buffer. + val keySpecForClose = dekSpec + streamReturned = true + return ZeroizingCipherEncryptOutputStream(ciphertext, dataCipher, keySpecForClose) + } finally { + SecurityAuditLogger.logLine("===== Stream Encrypt asymmetric =====") + SecurityAuditLogger.logKeyMaterial("Ephemeral Key Pair Public Key", ephemeralKeyPair?.public?.encoded) + val ephPrivBytes = ephemeralKeyPair?.private?.encoded + + SecurityAuditLogger.logKeyMaterial("Ephemeral Key Pair Private Key", ephPrivBytes) + + ephPrivBytes?.fill(0) + + SecurityAuditLogger.logKeyMaterial("Recipient UDR Key Pair (Public Key)", recipientPubKey.encoded) + SecurityAuditLogger.logKeyMaterial("Shared Secret", sharedSecret) + SecurityAuditLogger.logKeyMaterial("Asymmetric KEK", kekBytes) + SecurityAuditLogger.logKeyMaterial("Data Encryption Key (DEK)", dekBytes) + dekBytes.fill(0); sharedSecret?.fill(0); kekBytes?.fill(0) + + wrapCipher?.let { clearCipherState(it) } + if (!streamReturned) { + dekSpec?.let { if (!it.isDestroyed) it.destroy() } + dataCipher?.let { clearCipherState(it) } + } + + kekSpec?.let { if (!it.isDestroyed) it.destroy() } + } + } + + override fun newDecryptingStream(ciphertext: InputStream, associatedData: ByteArray): InputStream { + val dis = DataInputStream(ciphertext) + val magicByte = dis.readByte() + val isSymmetric = when (magicByte) { + MAGIC_BYTE_ASYMMETRIC -> false + MAGIC_BYTE_SYMMETRIC -> true + else -> throw IllegalArgumentException("Unsupported magic byte: $magicByte") + } + + val recipientPrivateKey = if (isSymmetric) { + loadSymmetricRecipientPrivateKey() + } else { + loadRecipientPrivateKey() + } + val ephKeyLen = dis.readInt() + val ephKeyBytes = ByteArray(ephKeyLen).apply { dis.readFully(this) } + val ephemeralPublicKey = KeyFactory.getInstance(EC_KEY_ALGORITHM) + .generatePublic(X509EncodedKeySpec(ephKeyBytes)) + + val wrapDekLen = dis.readInt() + val wrappedDek = ByteArray(wrapDekLen).apply { dis.readFully(this) } + + val wrapIvLen = dis.readInt() + val wrapIv = ByteArray(wrapIvLen).apply { dis.readFully(this) } + + val dataIvLen = dis.readInt() + val dataIv = ByteArray(dataIvLen).apply { dis.readFully(this) } + + var dekBytes: ByteArray? = null + var sharedSecret: ByteArray? = null + var kekBytes: ByteArray? = null + var dekSpec: CleanSecretKeySpec? = null + var kekSpec: CleanSecretKeySpec? = null + var unwrapCipher: Cipher? = null + var dataCipher: Cipher? = null + var streamReturned = false + + try { + val keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM) + keyAgreement.init(recipientPrivateKey) + keyAgreement.doPhase(ephemeralPublicKey, true) + sharedSecret = keyAgreement.generateSecret() + flushKeystoreBinderBuffer(recipientPrivateKey) + + val hkdfContext = if (isSymmetric) "${masterKeyAlias}_symmetric_ec" else masterKeyAlias + kekBytes = hkdfDerive(sharedSecret!!, hkdfContext.toByteArray(Charsets.UTF_8), ephKeyBytes) + kekSpec = CleanSecretKeySpec(kekBytes!!, DEK_ALGORITHM) + + unwrapCipher = Cipher.getInstance(DEK_WRAPPING_CIPHER) + unwrapCipher.init(Cipher.DECRYPT_MODE, kekSpec, GCMParameterSpec(GCM_TAG_LENGTH_BITS, wrapIv)) + dekBytes = unwrapCipher.doFinal(wrappedDek) + + dataCipher = Cipher.getInstance(DATA_CIPHER) + dekSpec = CleanSecretKeySpec(dekBytes, DEK_ALGORITHM) + dataCipher.init(Cipher.DECRYPT_MODE, dekSpec, GCMParameterSpec(GCM_TAG_LENGTH_BITS, dataIv)) + dataCipher.updateAAD(associatedData) + + val keySpecForClose = dekSpec + streamReturned = true + return ZeroizingCipherDecryptInputStream(ciphertext, dataCipher, keySpecForClose) + } finally { + SecurityAuditLogger.logLine( + if (isSymmetric) "===== Stream Decrypt symmetric (Solution 2 - ECDH) =====" + else "===== Stream Decrypt asymmetric =====" + ) + SecurityAuditLogger.logKeyMaterial("Recipient UDR Key Pair (Private Key)", recipientPrivateKey.encoded) + SecurityAuditLogger.logKeyMaterial("Shared Secret", sharedSecret) + SecurityAuditLogger.logKeyMaterial(if (isSymmetric) "Symmetric KEK" else "Asymmetric KEK", kekBytes) + SecurityAuditLogger.logKeyMaterial("Data Encryption Key (DEK)", dekBytes) + ephKeyBytes.fill(0) + sharedSecret?.fill(0) + kekBytes?.fill(0) + dekBytes?.fill(0) + + unwrapCipher?.let { clearCipherState(it) } + kekSpec?.let { if (!it.isDestroyed) it.destroy() } + if (!streamReturned) { + dekSpec?.let { if (!it.isDestroyed) it.destroy() } + dataCipher?.let { clearCipherState(it) } + } + } + } + } + + override fun getAead(): Aead = rawHybridAead + override fun getStreamingAead(): StreamingAead = rawHybridStreamingAead + override fun getUnlockDeviceRequired(): Boolean = unlockedDeviceRequired + override fun rewrapKeyToSymmetricUdr(encryptedDek: ByteArray): ByteArray { + + val pkg = deserializeEncryptedPackage(encryptedDek) + if (pkg.magicByte == MAGIC_BYTE_SYMMETRIC) return encryptedDek + + var dekBytes: ByteArray? = null + var newWrappedDek: ByteArray? = null + var newWrapIv: ByteArray? = null + var symmetricSharedSecret: ByteArray? = null + var symmetricKekBytes: ByteArray? = null + var symmetricKekSpec: CleanSecretKeySpec? = null + var ephemeralPublicKeyBytes: ByteArray? = null + var wrapCipher: Cipher? = null + + try { + // 1. Decrypt existing asymmetric wrapper to get DEK + val recipientPrivateKey = loadRecipientPrivateKey() + val ephemeralPubKeySpec = X509EncodedKeySpec(pkg.ephemeralPublicKeyBytes!!) + val ephemeralPublicKey = KeyFactory.getInstance(EC_KEY_ALGORITHM).generatePublic(ephemeralPubKeySpec) + var sharedSecret: ByteArray? = null + var kekBytes: ByteArray? = null + var kekSpec: CleanSecretKeySpec? = null + var unwrapCipher: Cipher? = null + try { + val keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM) + keyAgreement.init(recipientPrivateKey!!) + keyAgreement.doPhase(ephemeralPublicKey, true) + sharedSecret = keyAgreement.generateSecret() + flushKeystoreBinderBuffer(recipientPrivateKey) + kekBytes = hkdfDerive(sharedSecret!!, masterKeyAlias.toByteArray(Charsets.UTF_8), pkg.ephemeralPublicKeyBytes!!) + kekSpec = CleanSecretKeySpec(kekBytes, DEK_ALGORITHM) + unwrapCipher = Cipher.getInstance(DEK_WRAPPING_CIPHER) + unwrapCipher.init(Cipher.DECRYPT_MODE, kekSpec, GCMParameterSpec(GCM_TAG_LENGTH_BITS, pkg.wrapIv)) + dekBytes = unwrapCipher.doFinal(pkg.wrappedDek) + } finally { + SecurityAuditLogger.logLine("===== Rewrap: Decrypt asymmetric phase =====") + SecurityAuditLogger.logKeyMaterial("Recipient UDR Key Pair (Private Key)", recipientPrivateKey.encoded) + SecurityAuditLogger.logKeyMaterial("Shared Secret", sharedSecret) + SecurityAuditLogger.logKeyMaterial("Asymmetric KEK", kekBytes) + sharedSecret?.fill(0) + kekBytes?.fill(0) + + kekSpec?.let { if (!it.isDestroyed) it.destroy() } + unwrapCipher?.let { clearCipherState(it) } + } + + // 2. Re-wrap DEK with symmetric master key (using ECDH as per new Solution 2) + val symmetricRecipientPubKey = loadSymmetricPublicKey() + val ephemeralKpg = KeyPairGenerator.getInstance(EC_KEY_ALGORITHM).apply { initialize(ECGenParameterSpec("secp521r1")) } + val keyPair = ephemeralKpg.generateKeyPair() + + val keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM) + keyAgreement.init(keyPair.private) + keyAgreement.doPhase(symmetricRecipientPubKey, true) + symmetricSharedSecret = keyAgreement.generateSecret() + + val contextString = "${masterKeyAlias}_symmetric_ec" + symmetricKekBytes = hkdfDerive(symmetricSharedSecret!!, contextString.toByteArray(Charsets.UTF_8), keyPair.public.encoded) + symmetricKekSpec = CleanSecretKeySpec(symmetricKekBytes!!, DEK_ALGORITHM) + + wrapCipher = Cipher.getInstance(DEK_WRAPPING_CIPHER) + wrapCipher.init(Cipher.ENCRYPT_MODE, symmetricKekSpec) + newWrappedDek = wrapCipher.doFinal(dekBytes) + newWrapIv = wrapCipher.iv + ephemeralPublicKeyBytes = keyPair.public.encoded + + // 3. Return new package with symmetric magic byte and ephemeral public key + return serializeEncryptedPackage( + MAGIC_BYTE_SYMMETRIC, + ephemeralPublicKeyBytes, + newWrappedDek, + newWrapIv, + pkg.encryptedContent, + pkg.dataIv + ) + } finally { + SecurityAuditLogger.logLine("===== Rewrap: Re-encrypt symmetric phase =====") + SecurityAuditLogger.logKeyMaterial("Symmetric Ephemeral Public Key", ephemeralPublicKeyBytes) + SecurityAuditLogger.logKeyMaterial("Symmetric Shared Secret", symmetricSharedSecret) + SecurityAuditLogger.logKeyMaterial("Symmetric KEK", symmetricKekBytes) + SecurityAuditLogger.logKeyMaterial("Data Encryption Key (DEK)", dekBytes) + + dekBytes?.fill(0) + newWrappedDek?.fill(0) + newWrapIv?.fill(0) + symmetricSharedSecret?.fill(0) + symmetricKekBytes?.fill(0) + + symmetricKekSpec?.let { if (!it.isDestroyed) it.destroy() } + wrapCipher?.let { clearCipherState(it) } + } + } + + override fun isSymmetricallyWrapped(encryptedDek: ByteArray): Boolean { + if (encryptedDek.isEmpty()) return false + return encryptedDek[0] == MAGIC_BYTE_SYMMETRIC + } + + override fun destroy() { + // [FCS_CKM_EXT.4] & [FCS_STG_EXT.2] Secure deletion from persistent storage + try { + val aliasesToDelete = listOf( + masterKeyAlias, + "${masterKeyAlias}_symmetric_ec", + symmetricMasterKeyAlias, + "${masterKeyAlias}_wrapping" + ) + for (alias in aliasesToDelete) { + if (keyStore.containsAlias(alias)) { + keyStore.deleteEntry(alias) + } + } + prefs.edit().clear().apply() + } catch (e: Exception) { } + } +} + +private data class EncryptedPackage( + val magicByte: Byte, + val ephemeralPublicKeyBytes: ByteArray?, + val wrappedDek: ByteArray, + val wrapIv: ByteArray, + val encryptedContent: ByteArray, + val dataIv: ByteArray +) + +private fun serializeEncryptedPackage(magicByte: Byte, ephemeralPublicKeyBytes: ByteArray?, wrappedDek: ByteArray, wrapIv: ByteArray, encryptedContent: ByteArray, dataIv: ByteArray): ByteArray { + val bos = ByteArrayOutputStream() + DataOutputStream(bos).use { + it.writeByte(magicByte.toInt()) + // WORKAROUND [FCS_CKM_EXT.4] Residual key material mitigation: Both Asymmetric AND Symmetric modes now use ECDH + // (Hybrid Envelope Encryption) to avoid raw DEK exposure in Binder IPC. + if (magicByte == RawHybridKeyProvider.MAGIC_BYTE_ASYMMETRIC || magicByte == RawHybridKeyProvider.MAGIC_BYTE_SYMMETRIC) { + val ephKey = ephemeralPublicKeyBytes ?: throw IllegalArgumentException("Ephemeral public key required for ECDH mode") + it.writeInt(ephKey.size) + it.write(ephKey) + } + it.writeInt(wrappedDek.size) + it.write(wrappedDek) + it.writeInt(wrapIv.size) + it.write(wrapIv) + it.writeInt(dataIv.size) + it.write(dataIv) + it.write(encryptedContent) + } + return bos.toByteArray() +} + +private fun deserializeEncryptedPackage(ciphertext: ByteArray): EncryptedPackage { + val buffer = ByteBuffer.wrap(ciphertext) + + val magicByte = buffer.get() + var ephKey: ByteArray? = null + + // WORKAROUND [FCS_CKM_EXT.4] Residual key material mitigation: Both Asymmetric AND Symmetric modes now use ECDH + // (Hybrid Envelope Encryption) to avoid raw DEK exposure in Binder IPC. + if (magicByte == RawHybridKeyProvider.MAGIC_BYTE_ASYMMETRIC || magicByte == RawHybridKeyProvider.MAGIC_BYTE_SYMMETRIC) { + val ephKeySize = buffer.int + ephKey = ByteArray(ephKeySize).apply { buffer.get(this) } + } else { + throw IllegalArgumentException("Invalid magic byte or unsupported format: $magicByte") + } + + val wrapDekSize = buffer.int + val wrapDek = ByteArray(wrapDekSize).apply { buffer.get(this) } + val wrapIvSize = buffer.int + val wrapIv = ByteArray(wrapIvSize).apply { buffer.get(this) } + val dataIvSize = buffer.int + val dataIv = ByteArray(dataIvSize).apply { buffer.get(this) } + val content = ByteArray(buffer.remaining()).apply { buffer.get(this) } + return EncryptedPackage(magicByte, ephKey, wrapDek, wrapIv, content, dataIv) +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/RawKeyProvider.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/RawKeyProvider.kt new file mode 100644 index 0000000..3b66c7c --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/internal/keymanagement/RawKeyProvider.kt @@ -0,0 +1,184 @@ +/* +* Copyright (C) 2026 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. +*/ + +package com.android.niapsec.encryption.internal.keymanagement + +import android.content.Context +import android.security.keystore.KeyProperties +import android.security.keystore.KeyProtection +import android.util.Log +import com.google.crypto.tink.Aead +import java.nio.ByteBuffer +import java.security.GeneralSecurityException +import java.security.KeyStore +import java.util.UUID +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.IvParameterSpec + +/** + * A KeyProvider that wraps the raw JCA Cipher API into a Tink-compatible Aead. + * This allows using the standard Android Keystore without the Tink library for key management. + */ +class RawKeyProvider( + private val context: Context, + private val keyAliasPrefix: String, + private val unlockedDeviceRequired: Boolean +) : KeyProvider { + private val KEY_ALIAS_PREFIX = "raw_provider_key_${keyAliasPrefix}_" + private val ANDROID_KEYSTORE = "AndroidKeyStore" + private val KEY_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES + private val BLOCK_MODE = KeyProperties.BLOCK_MODE_CBC + private val PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7 + private val TRANSFORMATION = "$KEY_ALGORITHM/$BLOCK_MODE/$PADDING" + + private val keyStore: KeyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) } + + private val rawAead: Aead = object : Aead { + override fun encrypt(plaintext: ByteArray, associatedData: ByteArray): ByteArray { + val keyAlias = KEY_ALIAS_PREFIX + UUID.randomUUID().toString() + val cipher = Cipher.getInstance(TRANSFORMATION) + var secretKey: SecretKey? = null + try { + secretKey = generateEphemeralSoftwareKey(keyAlias) + cipher.init(Cipher.ENCRYPT_MODE, secretKey) + + val spec = cipher.parameters.getParameterSpec(IvParameterSpec::class.java) + val iv = spec.iv + val aliasBytes = keyAlias.toByteArray(Charsets.UTF_8) + + val header = ByteBuffer.allocate(4 + aliasBytes.size + 4 + iv.size) + .putInt(aliasBytes.size) + .put(aliasBytes) + .putInt(iv.size) + .put(iv) + .array() + + val ciphertext = cipher.doFinal(plaintext) + return header + ciphertext + } finally { + // Step 4: Explicitly zeroize the original software key material in memory + zeroizeSecretKey(secretKey) + } + } + + override fun decrypt(ciphertext: ByteArray, associatedData: ByteArray): ByteArray { + val buffer = ByteBuffer.wrap(ciphertext) + + val aliasLength = buffer.int + if (aliasLength <= 0 || aliasLength > buffer.remaining()) throw GeneralSecurityException("Invalid alias length") + val aliasBytes = ByteArray(aliasLength) + buffer.get(aliasBytes) + val keyAlias = String(aliasBytes, Charsets.UTF_8) + + val ivLength = buffer.int + if (ivLength <= 0 || ivLength > buffer.remaining()) throw GeneralSecurityException("Invalid IV length") + val iv = ByteArray(ivLength) + buffer.get(iv) + + val cipher = Cipher.getInstance(TRANSFORMATION) + + val actualCiphertext = ByteArray(buffer.remaining()) + buffer.get(actualCiphertext) + + val secretKey = getSecretKey(keyAlias) + val spec = IvParameterSpec(iv) + cipher.init(Cipher.DECRYPT_MODE, secretKey, spec) + + return cipher.doFinal(actualCiphertext) + } + } + + private fun generateEphemeralSoftwareKey(keyAlias: String): SecretKey { + val keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM, "AndroidOpenSSL") + keyGenerator.init(256) + val secretKey = keyGenerator.generateKey() + val secretKeyEntry = KeyStore.SecretKeyEntry(secretKey) + + keyStore.setEntry( + keyAlias, secretKeyEntry, + KeyProtection.Builder((KeyProperties.PURPOSE_DECRYPT or KeyProperties.PURPOSE_ENCRYPT)) + .setEncryptionPaddings(PADDING) + .setBlockModes(BLOCK_MODE) + .setUnlockedDeviceRequired(unlockedDeviceRequired) + .build() + ) + return secretKey + } + + private fun getSecretKey(keyAlias: String): SecretKey { + return keyStore.getKey(keyAlias, null) as SecretKey + } + + /** + * Deterministically zeroizes the internal byte[] backing a software SecretKey (e.g. SecretKeySpec). + */ + private fun zeroizeSecretKey(secretKey: SecretKey?) { + if (secretKey == null) return + try { + var clazz: Class<*>? = secretKey.javaClass + while (clazz != null) { + for (field in clazz.declaredFields) { + if (field.type == ByteArray::class.java) { + field.isAccessible = true + val bytes = field.get(secretKey) as? ByteArray + bytes?.fill(0) + } + } + clazz = clazz.superclass + } + } catch (e: Exception) { + Log.w("RawKeyProvider", "Failed to zeroize SecretKey internal bytes", e) + } + try { + if (secretKey is javax.security.auth.Destroyable && !secretKey.isDestroyed) { + secretKey.destroy() + } + } catch (_: Exception) { + } + } + + override fun getUnlockDeviceRequired(): Boolean { + return unlockedDeviceRequired + } + + override fun getAead(): Aead { + return rawAead + } + + override fun rewrapKeyToSymmetricUdr(encryptedDek: ByteArray): ByteArray { + TODO("Not yet implemented") + } + + override fun isSymmetricallyWrapped(encryptedDek: ByteArray): Boolean { + TODO("Not yet implemented") + } + + override fun destroy() { + try { + val aliases = keyStore.aliases() + while (aliases.hasMoreElements()) { + val alias = aliases.nextElement() + if (alias.startsWith(KEY_ALIAS_PREFIX)) { + keyStore.deleteEntry(alias) + } + } + } catch (e: Exception) { + Log.e("RawKeyProvider", "Failed to destroy keys", e) + } + } +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/Asn1Helper.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/Asn1Helper.kt new file mode 100644 index 0000000..6731b03 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/Asn1Helper.kt @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2026 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. + */ + +package com.android.niapsec.encryption.tools + +import java.io.ByteArrayOutputStream + +/** + * Lightweight helper to construct DER-encoded ASN.1 structures. + * Supports only basic types required for `WrappedKeyEntry` (SEQUENCE, OCTET_STRING, INTEGER). + */ +object Asn1Helper { + + private const val TAG_INTEGER = 0x02.toByte() + private const val TAG_OCTET_STRING = 0x04.toByte() + private const val TAG_SEQUENCE = 0x30.toByte() + + fun explicitTag(tagNum: Int, content: ByteArray): ByteArray { + val tagByte = (0xA0 or (tagNum and 0x1F)).toByte() + return encode(tagByte, content) + } + + fun set(vararg elements: ByteArray): ByteArray { + val bos = ByteArrayOutputStream() + for (element in elements) { + bos.write(element) + } + return encode(0x31.toByte(), bos.toByteArray()) + } + + fun sequence(vararg elements: ByteArray): ByteArray { + val bos = ByteArrayOutputStream() + for (element in elements) { + bos.write(element) + } + return encode(TAG_SEQUENCE, bos.toByteArray()) + } + + fun octetString(content: ByteArray): ByteArray { + return encode(TAG_OCTET_STRING, content) + } + + fun integer(value: Int): ByteArray { + val bos = ByteArrayOutputStream() + bos.write((value shr 24) and 0xFF) + bos.write((value shr 16) and 0xFF) + bos.write((value shr 8) and 0xFF) + bos.write(value and 0xFF) + var bytes = bos.toByteArray() + + // Trim leading zeros if it's signed (0 padding needs to be careful if it's negative, but for simple use cases it's fine) + var start = 0 + while (start < bytes.size - 1 && bytes[start] == 0.toByte()) { + start++ + } + if (start > 0) { + bytes = bytes.copyOfRange(start, bytes.size) + } + return encode(TAG_INTEGER, bytes) + } + + private fun encode(tag: Byte, content: ByteArray): ByteArray { + val bos = ByteArrayOutputStream() + bos.write(tag.toInt()) + writeLength(bos, content.size) + bos.write(content) + return bos.toByteArray() + } + + private fun writeLength(bos: ByteArrayOutputStream, length: Int) { + if (length < 128) { + bos.write(length) + } else { + val lengthBos = ByteArrayOutputStream() + var temp = length + while (temp > 0) { + lengthBos.write(temp and 0xFF) + temp = temp ushr 8 + } + val lengthBytes = lengthBos.toByteArray().reversedArray() + bos.write(0x80 or lengthBytes.size) + bos.write(lengthBytes) + } + } +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/CleanSecretKeySpec.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/CleanSecretKeySpec.kt new file mode 100644 index 0000000..6698dcc --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/CleanSecretKeySpec.kt @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2026 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. + */ + +package com.android.niapsec.encryption.tools + +import java.security.spec.KeySpec +import javax.crypto.SecretKey + +/** + * Custom SecretKeySpec class that implements the Destroyable interface. + * Default SecretKeySpec has destroy() interface derived from SecretKey, but not implemented. + */ +class CleanSecretKeySpec( + key: ByteArray, + private val algorithm: String +) : KeySpec, SecretKey{ + + private val keyMaterial: ByteArray = key.clone() + private var isDestroyedFlag: Boolean = false + + override fun getAlgorithm(): String = algorithm + + override fun getFormat(): String = "RAW" + + override fun getEncoded(): ByteArray? { + if (isDestroyedFlag) { + throw IllegalStateException("This key has already been destroyed.") + } + return keyMaterial + } + + override fun destroy() { + if (!isDestroyedFlag) { + keyMaterial.fill(0) + isDestroyedFlag = true + } + } + + override fun isDestroyed(): Boolean = isDestroyedFlag +} \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/SafeHkdf.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/SafeHkdf.kt new file mode 100644 index 0000000..45104f8 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/SafeHkdf.kt @@ -0,0 +1,128 @@ +/* +* Copyright (C) 2026 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. +*/ + +package com.android.niapsec.encryption.tools + +import java.security.MessageDigest + +object SafeHkdf { + // FIPS 180-4 / FIPS 198-1: SHA-512 uses a 1024-bit (128-byte) block and a 512-bit (64-byte) output. + private const val SHA512_BLOCK_SIZE = 128 + private const val SHA512_HASH_SIZE = 64 + + /** + * Computes HMAC-SHA512 using MessageDigest directly, without relying on JNI Mac. + * Deterministically zeroizes all intermediate key-derived buffers in `finally`. + */ + private fun hmacSha512(key: ByteArray, data: ByteArray): ByteArray { + val md = MessageDigest.getInstance("SHA-512") + val paddedKey = ByteArray(SHA512_BLOCK_SIZE) + val oPad = ByteArray(SHA512_BLOCK_SIZE) + val iPad = ByteArray(SHA512_BLOCK_SIZE) + var innerHash: ByteArray? = null + + try { + // Key padding based on HMAC specification + if (key.size > SHA512_BLOCK_SIZE) { + val hashedKey = md.digest(key) + try { + System.arraycopy(hashedKey, 0, paddedKey, 0, hashedKey.size) + } finally { + hashedKey.fill(0) // Immediately clear the intermediate buffer + } + } else { + System.arraycopy(key, 0, paddedKey, 0, key.size) + } + + for (i in 0 until SHA512_BLOCK_SIZE) { + oPad[i] = (paddedKey[i].toInt() xor 0x5c).toByte() + iPad[i] = (paddedKey[i].toInt() xor 0x36).toByte() + } + + // Inner hash: H(iPad || data) + md.reset() + md.update(iPad) + md.update(data) + innerHash = md.digest() + + // Outer hash: H(oPad || innerHash) + md.reset() + md.update(oPad) + md.update(innerHash) + return md.digest() + } finally { + // [CRITICAL] Ensure all used buffers are zero-cleared + paddedKey.fill(0) + oPad.fill(0) + iPad.fill(0) + innerHash?.fill(0) + md.reset() + } + } + + /** + * A function completely compatible with Tink's Hkdf.computeHkdf (using HMAC-SHA512). + * + * The PRK from HKDF-Extract is the full, untruncated 64-byte HMAC-SHA512 output. + * Only the final output keying material is truncated to [length] bytes (e.g., 32 bytes for AES-256). + * + * Writes directly into the exact-sized output array (avoiding `ByteArrayOutputStream` and + * `toByteArray().copyOf(length)`, which previously left two unzeroed 64-byte KEK copies on + * the ART heap on every invocation). + */ + fun computeHkdf(ikm: ByteArray, salt: ByteArray?, info: ByteArray, length: Int): ByteArray { + require(length >= 0) { "Requested length must be non-negative" } + val actualSalt = if (salt == null || salt.isEmpty()) ByteArray(SHA512_HASH_SIZE) else salt + + // 1. HKDF-Extract + val prk = hmacSha512(actualSalt, ikm) + val finalResult = ByteArray(length) + var t = ByteArray(0) + + try { + // 2. HKDF-Expand + val iterations = if (length == 0) 0 else (length + SHA512_HASH_SIZE - 1) / SHA512_HASH_SIZE + require(iterations <= 255) { "Requested length is too large" } + + var offset = 0 + for (i in 1..iterations) { + val input = ByteArray(t.size + info.size + 1) + try { + System.arraycopy(t, 0, input, 0, t.size) + System.arraycopy(info, 0, input, t.size, info.size) + input[input.size - 1] = i.toByte() + + if (t.isNotEmpty()) t.fill(0) // Clear previous T + t = hmacSha512(prk, input) + + val toCopy = minOf(t.size, length - offset) + System.arraycopy(t, 0, finalResult, offset, toCopy) + offset += toCopy + } finally { + input.fill(0) // Clear temporary loop buffer + } + } + return finalResult + } catch (e: Exception) { + finalResult.fill(0) + throw e + } finally { + // [CRITICAL] Zero out PRK and the final T + prk.fill(0) + if (t.isNotEmpty()) t.fill(0) + } + } +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/SecurityAuditLogger.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/SecurityAuditLogger.kt new file mode 100644 index 0000000..6a7c63e --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/main/java/com/android/niapsec/encryption/tools/SecurityAuditLogger.kt @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2026 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. + */ + +package com.android.niapsec.encryption.tools +import com.android.niapsec.encryption.BuildConfig +import android.util.Log + +/** + * [Security Component: Audit Logger] + * + * [isAuditLogEnabled] should be false when the app is released. + */ +object SecurityAuditLogger { + // toggle switch for audit + var isAuditLogEnabled = true + + /** + * Optional forensic/test observer invoked with transient key bytes immediately before + * zeroization. Always null in production; callers must never retain plaintext copies. + */ + @Volatile + var keyMaterialObserver: ((name: String, bytes: ByteArray) -> Unit)? = null + + private const val TAG = "AUDIT_LOGGER KMD" + + fun logMaterial(tag: String = TAG, name: String, bytes: ByteArray?) { + if (!isAuditLogEnabled || bytes == null) return + Log.d(tag, bytes.toHexDumpString()) + } + + fun logKeyMaterial(name: String, bytes: ByteArray?) { + return logKeyMaterial(tag = TAG, name = name, bytes = bytes); + } + fun logKeyMaterial(tag: String= TAG, name: String, bytes: ByteArray?) { + if (!isAuditLogEnabled || bytes== null) { + Log.d("${name} KMD", "returns null (error or hardware backend)") + return + } + keyMaterialObserver?.invoke(name, bytes) +Log.d("${name} KMD", "[MASKED - Use bytes.toHExString() here to dump key]") + + bytes.fill(0) + } + + fun logLine(msg: String) { + logLine(tag = TAG+BuildConfig.BUILD_DATE, msg = msg) + } + fun logLine(tag:String,msg: String) { + Log.d(tag,msg) + } +} + +fun ByteArray.toHexString(): String { + return joinToString("") { "%02x".format(it) } +} +fun ByteArray.toHexDumpString(): String = buildString { + for (rowAddr in this@toHexDumpString.indices step 16) { + val rowEnd = minOf(rowAddr + 16, this@toHexDumpString.size) + val rowBytes = this@toHexDumpString.sliceArray(rowAddr until rowEnd) + + append("%08x ".format(rowAddr)) + + val hexPart = rowBytes.joinToString(" ") { "%02x".format(it) } + append(hexPart.padEnd(47)) // Fixed width for 16 bytes + + append(" |") + rowBytes.forEach { + val char = it.toInt().toChar() + append(if (it in 32..126) char else '.') + } + append("|\n") + } +}.trimEnd() \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/test/java/com/android/niapsec/ExampleUnitTest.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/test/java/com/android/niapsec/ExampleUnitTest.kt new file mode 100644 index 0000000..3ce3416 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/test/java/com/android/niapsec/ExampleUnitTest.kt @@ -0,0 +1,32 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/test/java/com/android/niapsec/encryption/internal/ZeroizingStreamsTest.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/test/java/com/android/niapsec/encryption/internal/ZeroizingStreamsTest.kt new file mode 100644 index 0000000..c7155b3 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/test/java/com/android/niapsec/encryption/internal/ZeroizingStreamsTest.kt @@ -0,0 +1,88 @@ +package com.android.niapsec.encryption.internal + +import com.android.niapsec.encryption.tools.CleanSecretKeySpec +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.security.SecureRandom +import javax.crypto.Cipher +import javax.crypto.spec.GCMParameterSpec + +class ZeroizingStreamsTest { + + @Test + fun zeroizingByteArrayOutputStreamWipesOldBuffersOnGrowthAndClose() { + val out = ZeroizingByteArrayOutputStream(initialCapacity = 32) + val firstBuf = out.backingBuffer() + val payload = ByteArray(100) { (0x41 + (it % 26)).toByte() } + out.write(payload) + + // Old 32-byte buffer must be zeroed immediately when grown + assertTrue(firstBuf.all { it == 0.toByte() }) + val grownBuf = out.backingBuffer() + assertArrayEquals(payload, out.toByteArrayCopy()) + + out.close() + assertEquals(0, out.size) + assertTrue(grownBuf.all { it == 0.toByte() }) + } + + @Test + fun zeroizingByteArrayInputStreamProgressivelyZeroesAndWipesOnClose() { + val raw = "SENSITIVE_SECRET_PAYLOAD_1234567890".toByteArray(Charsets.UTF_8) + val expected = raw.copyOf() + val input = ZeroizingByteArrayInputStream(raw) + + val chunk = ByteArray(10) + val read1 = input.read(chunk) + assertEquals(10, read1) + assertArrayEquals(expected.copyOfRange(0, 10), chunk) + // First 10 bytes must already be zeroed in backing array + assertTrue((0 until 10).all { raw[it] == 0.toByte() }) + + // Close before EOF must still wipe all remaining unread bytes + input.close() + assertTrue(raw.all { it == 0.toByte() }) + assertEquals(-1, input.read()) + } + + @Test + fun zeroizingCipherStreamsRoundTripMultiChunkAndDestroyKey() { + val keyBytes = ByteArray(32).also { SecureRandom().nextBytes(it) } + val encKey = CleanSecretKeySpec(keyBytes, "AES") + val decKey = CleanSecretKeySpec(keyBytes, "AES") + val aad = "EHBR".toByteArray(Charsets.US_ASCII) + val plaintext = ByteArray(4096) { (it and 0xFF).toByte() } + + val encCipher = Cipher.getInstance("AES/GCM/NoPadding") + encCipher.init(Cipher.ENCRYPT_MODE, encKey) + encCipher.updateAAD(aad) + val iv = encCipher.iv + + val wire = ByteArrayOutputStream() + ZeroizingCipherEncryptOutputStream(wire, encCipher, encKey).use { out -> + out.write(plaintext, 0, 1000) + out.write(plaintext, 1000, 3096) + } + assertTrue(encKey.isDestroyed) + + val decCipher = Cipher.getInstance("AES/GCM/NoPadding") + decCipher.init(Cipher.DECRYPT_MODE, decKey, GCMParameterSpec(128, iv)) + decCipher.updateAAD(aad) + + val recovered = ByteArrayOutputStream() + ZeroizingCipherDecryptInputStream(ByteArrayInputStream(wire.toByteArray()), decCipher, decKey).use { input -> + val buf = ByteArray(512) + while (true) { + val n = input.read(buf) + if (n <= 0) break + recovered.write(buf, 0, n) + } + } + assertTrue(decKey.isDestroyed) + assertArrayEquals(plaintext, recovered.toByteArray()) + } +} diff --git a/niap-cc/sdp-file-encrypt/encryption-lib/src/test/java/com/android/niapsec/encryption/tools/SafeHkdfTest.kt b/niap-cc/sdp-file-encrypt/encryption-lib/src/test/java/com/android/niapsec/encryption/tools/SafeHkdfTest.kt new file mode 100644 index 0000000..03238f9 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/encryption-lib/src/test/java/com/android/niapsec/encryption/tools/SafeHkdfTest.kt @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2026 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. + */ +package com.android.niapsec.encryption.tools + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Test +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +class SafeHkdfTest { + + private fun referenceHkdfSha512(ikm: ByteArray, salt: ByteArray?, info: ByteArray, length: Int): ByteArray { + val mac = Mac.getInstance("HmacSHA512") + val actualSalt = if (salt == null || salt.isEmpty()) ByteArray(64) else salt + mac.init(SecretKeySpec(actualSalt, "HmacSHA512")) + val prk = mac.doFinal(ikm) + + val out = ByteArray(length) + var t = ByteArray(0) + var offset = 0 + var counter = 1 + while (offset < length) { + mac.init(SecretKeySpec(prk, "HmacSHA512")) + mac.update(t) + mac.update(info) + mac.update(counter.toByte()) + t = mac.doFinal() + val n = minOf(t.size, length - offset) + System.arraycopy(t, 0, out, offset, n) + offset += n + counter++ + } + return out + } + + @Test + fun matchesReferenceHmacSha512For32ByteAesKek() { + val ikm = ByteArray(66) { (it * 7 + 3).toByte() } + val salt = "mail_raw_hybrid_key_symmetric_ec".toByteArray(Charsets.UTF_8) + val info = ByteArray(158) { (it xor 0x3C).toByte() } + + val actual = SafeHkdf.computeHkdf(ikm, salt, info, 32) + val expected = referenceHkdfSha512(ikm, salt, info, 32) + + assertEquals(32, actual.size) + assertArrayEquals(expected, actual) + } + + @Test + fun matchesReferenceForMultiBlockAndEmptySalt() { + val ikm = ByteArray(140) { (it + 11).toByte() } // > SHA-512 block size (128B) + val info = "multi-block-info".toByteArray(Charsets.UTF_8) + + val actual = SafeHkdf.computeHkdf(ikm, null, info, 100) // spans 2 SHA-512 iterations + val expected = referenceHkdfSha512(ikm, null, info, 100) + + assertEquals(100, actual.size) + assertArrayEquals(expected, actual) + } + + @Test + fun handlesZeroLengthOutput() { + val actual = SafeHkdf.computeHkdf(byteArrayOf(1, 2, 3), byteArrayOf(4), byteArrayOf(5), 0) + assertEquals(0, actual.size) + } +} diff --git a/niap-cc/sdp-file-encrypt/gradle.properties b/niap-cc/sdp-file-encrypt/gradle.properties new file mode 100644 index 0000000..4a4ab64 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/gradle.properties @@ -0,0 +1,34 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. For more details, visit +# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true +android.suppressUnsupportedCompileSdk=36 +android.defaults.buildfeatures.resvalues=true +android.sdk.defaultTargetSdkToCompileSdkIfUnset=false +android.enableAppCompileTimeRClass=false +android.usesSdkInManifest.disallowed=false +android.uniquePackageNames=false +android.dependency.useConstraints=true +android.r8.strictFullModeForKeepRules=false +android.r8.optimizedResourceShrinking=false +android.builtInKotlin=false +android.newDsl=false \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/gradle/gradle-daemon-jvm.properties b/niap-cc/sdp-file-encrypt/gradle/gradle-daemon-jvm.properties new file mode 100644 index 0000000..87cbae7 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,13 @@ +#This file is generated by updateDaemonJvm +toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/56a19bc915b9ba2eb62ba7554c61b919/redirect +toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/398ffe3949748bfb1d5636f023d228fd/redirect +toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/56a19bc915b9ba2eb62ba7554c61b919/redirect +toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/ecd23fd7707c683afbcd6052998cb6a9/redirect +toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/10fc3bf1ee0001078a473afe6e43cfdb/redirect +toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/658299a896470fbb3103ba3a430ee227/redirect +toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/536afcd1dff540251f85e5d2c80458cf/redirect +toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/ecd23fd7707c683afbcd6052998cb6a9/redirect +toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/248ffb1098f61659502d0c09aa348294/redirect +toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/dbd05c4936d573642f94cd149e1356c8/redirect +toolchainVendor=JETBRAINS +toolchainVersion=21 diff --git a/niap-cc/sdp-file-encrypt/gradle/libs.versions.toml b/niap-cc/sdp-file-encrypt/gradle/libs.versions.toml new file mode 100644 index 0000000..b302600 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/gradle/libs.versions.toml @@ -0,0 +1,36 @@ +[versions] +agp = "9.1.0-rc01" +kotlin = "2.2.10" +ksp = "2.3.4" +coreKtx = "1.17.0" +junit = "4.13.2" +junitVersion = "1.3.0" +espressoCore = "3.7.0" +lifecycleRuntimeKtx = "2.10.0" +activityCompose = "1.12.2" +composeBom = "2025.12.01" +materialIcons = "1.6.8" + +[libraries] +androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } +junit = { group = "junit", name = "junit", version.ref = "junit" } +androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } +androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } +androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" } +androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } +androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" } +androidx-ui = { group = "androidx.compose.ui", name = "ui" } +androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" } +androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" } +androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" } +androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" } +androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" } +androidx-material3 = { group = "androidx.compose.material3", name = "material3" } +androidx-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended", version.ref = "materialIcons" } + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } +kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } +kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } + diff --git a/niap-cc/sdp-file-encrypt/gradle/wrapper/gradle-wrapper.jar b/niap-cc/sdp-file-encrypt/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/niap-cc/sdp-file-encrypt/gradle/wrapper/gradle-wrapper.jar differ diff --git a/niap-cc/sdp-file-encrypt/gradle/wrapper/gradle-wrapper.properties b/niap-cc/sdp-file-encrypt/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2a45d2e --- /dev/null +++ b/niap-cc/sdp-file-encrypt/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Jan 06 16:50:05 JST 2026 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/niap-cc/sdp-file-encrypt/gradlew b/niap-cc/sdp-file-encrypt/gradlew new file mode 100755 index 0000000..4f906e0 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/niap-cc/sdp-file-encrypt/gradlew.bat b/niap-cc/sdp-file-encrypt/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/build.gradle.kts b/niap-cc/sdp-file-encrypt/locked-device-demo/build.gradle.kts new file mode 100644 index 0000000..6562957 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/build.gradle.kts @@ -0,0 +1,62 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) +} + +android { + namespace = "com.android.niapsec.demo" + compileSdk = 36 + + defaultConfig { + applicationId = "com.android.niapsec" + minSdk = 28 + targetSdk = 36 + versionCode = 1 + versionName = "1.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = "11" + } + buildFeatures { + compose = true + } +} + +dependencies { + implementation(project(":encryption-lib")) + + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.activity.compose) + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.ui) + implementation(libs.androidx.ui.graphics) + implementation(libs.androidx.ui.tooling.preview) + implementation(libs.androidx.material3) + implementation(libs.androidx.material.icons.extended) + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.ui.test.junit4) + debugImplementation(libs.androidx.ui.tooling) + debugImplementation(libs.androidx.ui.test.manifest) +} diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/androidTest/java/com/android/niapsec/EncryptedSharedPreferencesTest.kt b/niap-cc/sdp-file-encrypt/locked-device-demo/src/androidTest/java/com/android/niapsec/EncryptedSharedPreferencesTest.kt new file mode 100644 index 0000000..874b30f --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/androidTest/java/com/android/niapsec/EncryptedSharedPreferencesTest.kt @@ -0,0 +1,72 @@ +/* +* Copyright (C) 2026 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. +*/ + +package com.android.niapsec + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.android.niapsec.demo.EncryptedSharedPreferences +import com.android.niapsec.encryption.api.EncryptionManager +import com.android.niapsec.encryption.api.KeyProviderType +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.util.UUID + +@RunWith(AndroidJUnit4::class) +class EncryptedSharedPreferencesTest { + + private val context = InstrumentationRegistry.getInstrumentation().targetContext + private val managersToDestroy = mutableListOf() + + @Before + @After + fun cleanup() { + managersToDestroy.forEach { it.destroy() } + managersToDestroy.clear() + } + + private fun createManager(providerType: KeyProviderType): EncryptionManager { + val masterKeyUri = "android-keystore://test_prefs_key_${UUID.randomUUID()}" + val manager = EncryptionManager(context, masterKeyUri, providerType) + managersToDestroy.add(manager) + return manager + } + + private fun runStandardTests(prefs: EncryptedSharedPreferences) { + // 1. Test basic put and get + val key1 = "myKey1" + val value1 = "my secret value" + prefs.putString(key1, value1) + assertEquals(value1, prefs.getString(key1, null)) + + // 2. Test getting a non-existent key + assertNull(prefs.getString("non_existent_key", null)) + assertEquals("default", prefs.getString("non_existent_key", "default")) + + // 3. Test overwriting a key + val newValue1 = "a new secret" + prefs.putString(key1, newValue1) + assertEquals(newValue1, prefs.getString(key1, null)) + + // 4. Test clearing the preferences + prefs.clear() + assertNull(prefs.getString(key1, null)) + } +} diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/AndroidManifest.xml b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/AndroidManifest.xml new file mode 100644 index 0000000..55c20d9 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/AndroidManifest.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/ic_launcher-playstore.png b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/ic_launcher-playstore.png new file mode 100644 index 0000000..bd4699b Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/ic_launcher-playstore.png differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/DeviceAdminReceiver.kt b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/DeviceAdminReceiver.kt new file mode 100644 index 0000000..abc647e --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/DeviceAdminReceiver.kt @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2026 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. + */ + +package com.android.niapsec.demo + +import android.app.admin.DevicePolicyManager +import android.app.admin.DeviceAdminReceiver +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.util.Log +import android.widget.Toast + +class DeviceAdminReceiver : DeviceAdminReceiver() { + + override fun onEnabled(context: Context, intent: Intent) { + super.onEnabled(context, intent) + Toast.makeText(context, "Device admin enabled", Toast.LENGTH_SHORT).show() + } + + override fun onDisabled(context: Context, intent: Intent) { + super.onDisabled(context, intent) + Toast.makeText(context, "Device admin disabled", Toast.LENGTH_SHORT).show() + } +} + +class RemoveAdminReceiver : BroadcastReceiver() { + companion object { + const val ACTION_REMOVE_ADMIN = "com.android.niapsec.demo.ACTION_REMOVE_ADMIN" + } + + override fun onReceive(context: Context, intent: Intent?) { + if (intent?.action != ACTION_REMOVE_ADMIN) return + val dpm = context.getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager + val component = ComponentName(context, DeviceAdminReceiver::class.java) + if (dpm.isAdminActive(component)) { + dpm.removeActiveAdmin(component) + Log.d("RemoveAdmin", "Device admin removed") + } + } +} \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/DirectBootTestReceiver.kt b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/DirectBootTestReceiver.kt new file mode 100644 index 0000000..4878fa3 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/DirectBootTestReceiver.kt @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2026 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. + */ + +package com.android.niapsec.demo + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.os.UserManager +import android.util.Log +import com.android.niapsec.encryption.api.EncryptionManager +import com.android.niapsec.encryption.api.KeyProviderType + +/** + * Diagnostic Receiver for validating Direct Boot and Lock State behavior. + * This component mimics a background service attempting to access cryptographic keys + * during the "Before First Unlock" (BFU) or "After First Unlock" (AFU) states. + */ +class DirectBootTestReceiver : BroadcastReceiver() { + + companion object { + const val ACTION_TEST_CRYPTO = "com.android.niapsec.ACTION_TEST_CRYPTO" + private const val TAG = "DirectBootTest" + } + + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == ACTION_TEST_CRYPTO) { + Log.i(TAG, "Received test broadcast. Starting Direct Boot verification...") + + // 1. Check System Environment + val userManager = context.getSystemService(Context.USER_SERVICE) as UserManager + val isLocked = !userManager.isUserUnlocked + val isDeviceProtected = context.isDeviceProtectedStorage + + Log.d(TAG, "--- Environment Check ---") + Log.d(TAG, "User State: ${if (isLocked) "LOCKED (BFU State)" else "UNLOCKED (AFU State)"}") + Log.d(TAG, "Storage Context: ${if (isDeviceProtected) "Device Protected (DE)" else "Credential Encrypted (CE)"}") + + // 2. Test RawHybridKeyProvider (JCA Implementation) + runTest(context, KeyProviderType.RAW_HYBRID, "RawHybrid_JCA", isLocked) + + // 3. Test HybridKeyProvider (Tink Implementation) + runTest(context, KeyProviderType.HYBRID, "Hybrid_Tink", isLocked) + } + } + + /** + * Executes the encryption/decryption cycle using EncryptionManager. + * * @param context The application context (automatically handled by EncryptionManager) + * @param type The provider type to test (RAW_HYBRID or HYBRID) + * @param label A label for logging purposes + * @param isLocked Current lock state of the device + */ + private fun runTest(context: Context, type: KeyProviderType, label: String, isLocked: Boolean) { + Log.d(TAG, "--- Starting Test Sequence: $label ---") + try { + // Initialize EncryptionManager with a unique test alias. + // IMPORTANT: We set 'unlockedDeviceRequired = true' to enforce strict authentication binding (FIA_UAU_EXT.1). + val manager = EncryptionManager( + context = context, + masterKeyUri = "android-keystore://diagnostic_test_${label.lowercase()}", + providerType = type, + unlockedDeviceRequired = true + ) + + val testPayload = "Confidential Data Verification for $label - ${System.currentTimeMillis()}" + + // Step A: Encryption Verification (FDP_DAR_EXT.2) + // Requirement: Must SUCCEED even if the device is LOCKED. + // Mechanism: Uses the Public Key stored in Device Protected (DE) storage. + Log.d(TAG, "[$label] Attempting Encryption...") + val ciphertext = manager.encryptToString(testPayload) + Log.i(TAG, "[$label] SUCCESS: Encryption completed. Ciphertext length: ${ciphertext.length}") + + // Step B: Decryption Verification (FIA_UAU_EXT.1) + // Requirement: Must FAIL if LOCKED. Must SUCCEED if UNLOCKED. + // Mechanism: Access to the Private Key in Android Keystore is gated by user authentication. + Log.d(TAG, "[$label] Attempting Decryption...") + try { + val plaintext = manager.decryptFromString(ciphertext) + + if (isLocked) { + // SECURITY VIOLATION: We accessed the key without unlocking! + Log.e(TAG, "[$label] FAILURE: Decryption succeeded but user is LOCKED! This violates FIA_UAU_EXT.1.") + } else { + // Normal Operation + if (plaintext == testPayload) { + Log.i(TAG, "[$label] SUCCESS: Decryption succeeded and data matches.") + } else { + Log.e(TAG, "[$label] FAILURE: Decryption succeeded but data mismatch (Integrity Error).") + } + } + } catch (e: Exception) { + if (isLocked) { + // EXPECTED BEHAVIOR: Access denied during lock + Log.i(TAG, "[$label] SUCCESS: Decryption failed as expected during lock. Exception: ${e.javaClass.simpleName}") + } else { + // UNEXPECTED ERROR: Should have worked + Log.e(TAG, "[$label] FAILURE: Decryption failed but user is UNLOCKED. Error: ${e.message}") + e.printStackTrace() + } + } + + // Clean up test keys + // manager.destroy() // Optional: Keep keys to test across reboots if needed + Log.d(TAG, "--- End Test Sequence: $label ---") + + } catch (e: Exception) { + Log.e(TAG, "[$label] CRITICAL ERROR during initialization or encryption: ${e.message}", e) + } + } +} \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/EncryptedSharedPreferences.kt b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/EncryptedSharedPreferences.kt new file mode 100644 index 0000000..52aff9b --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/EncryptedSharedPreferences.kt @@ -0,0 +1,68 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.demo + +import android.content.Context +import android.content.SharedPreferences +import com.android.niapsec.encryption.api.EncryptionManager + +/** + * A wrapper for SharedPreferences that transparently encrypts and decrypts values. + * + * @param context The application context. + * @param fileName The name of the SharedPreferences file. + * @param encryptionManager The EncryptionManager instance to use for cryptographic operations. + */ +class EncryptedSharedPreferences(context: Context, fileName: String, private val encryptionManager: EncryptionManager) { + + private val sharedPreferences: SharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE) + + /** + * Encrypts and saves a string value. + */ + fun putString(key: String, value: String) { + try { + val encryptedValue = encryptionManager.encryptToString(value) + sharedPreferences.edit().putString(key, encryptedValue).apply() + } catch (e: Exception) { + throw SecurityException("Failed to encrypt and save the value for key: $key", e) + } + } + + /** + * Retrieves and decrypts a string value. + * Returns the defaultValue if decryption fails. + */ + fun getString(key: String, defaultValue: String?): String? { + val encryptedValue = sharedPreferences.getString(key, null) + return if (encryptedValue != null) { + try { + encryptionManager.decryptFromString(encryptedValue) + } catch (e: Exception) { + defaultValue + } + } else { + defaultValue + } + } + + /** + * Clears all values from this SharedPreferences. + */ + fun clear() { + sharedPreferences.edit().clear().apply() + } +} diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/EncryptionTestRunner.kt b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/EncryptionTestRunner.kt new file mode 100644 index 0000000..bee7bb9 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/EncryptionTestRunner.kt @@ -0,0 +1,101 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.demo + +import android.content.Context +import android.util.Log +import com.android.niapsec.encryption.api.EncryptionManager +import java.io.File + +data class TestResult(val testName: String, val passed: Boolean, val message: String, val file: File? = null) + +class EncryptionTestRunner(private val context: Context) { + + companion object { + const val ENCRYPTED_FILE_NAME = "test_file.enc" + const val ORIGINAL_TEXT = "This is a secret message." + } + + fun runFullTest( + encryptionManager: EncryptionManager, + testName: String, + reverseEncryptionResult: Boolean = false, + reverseDecryptionResult: Boolean = false + ): List { + Log.d(testName, "--- STARTING TEST (Reverse Encrypt: $reverseEncryptionResult, Reverse Decrypt: $reverseDecryptionResult) ---") + val file = File(context.filesDir, "$testName-$ENCRYPTED_FILE_NAME") + + // [Phase 1.1] Ensure clean state by deleting any existing file from a previous run. + if (file.exists()) { + val deleted = file.delete() + Log.d(testName, "Deleted stale test file: $deleted") + } + + val results = mutableListOf() + + // Run Encryption Phase + val encryptionResult = testEncryption(encryptionManager, file, testName, reverseEncryptionResult) + results.add(encryptionResult) + + // Run Decryption Phase + val decryptionResult = testDecryption(encryptionManager, file, testName, reverseDecryptionResult) + results.add(decryptionResult) + + Log.d(testName, "--- TEST COMPLETE ---") + return results + } + + private fun testEncryption(encryptionManager: EncryptionManager, file: File, testName: String, reverseResult: Boolean): TestResult { + return try { + Log.d(testName, "Attempting encryption...") + + encryptionManager.encryptToFile(file).use { it.write(ORIGINAL_TEXT.toByteArray()) } + val passed = !reverseResult + val message = if (passed) "Encryption successful" else "Encryption expected to fail but succeeded" + TestResult(testName, passed, message, file) + } catch (e: Exception) { + val passed = reverseResult + val message = if (passed) "Encryption rejected as expected (${e.javaClass.simpleName})" else "Encryption failed unexpectedly: ${e.message}" + Log.e(testName, message, e) + TestResult(testName, passed, message, file) + } + } + + private fun testDecryption(encryptionManager: EncryptionManager, file: File, testName: String, reverseResult: Boolean): TestResult { + return try { + Log.d(testName, "Attempting decryption...") + if (!file.exists()) { + return TestResult(testName, false, "Decryption failed: File not found", file) + } + val decryptedText = encryptionManager.decryptFromFile(file).use { it.reader().readText() } + if (ORIGINAL_TEXT == decryptedText) { + val passed = !reverseResult + val message = if (passed) "Decryption successful and content matches" else "Decryption expected to fail but succeeded" + TestResult(testName, passed, message, file) + } else { + val passed = reverseResult + val message = "Decryption succeeded but content MISMATCH" + Log.e(testName, message) + TestResult(testName, passed, message, file) + } + } catch (e: Exception) { + val passed = reverseResult + val message = if (passed) "Decryption rejected as expected (${e.javaClass.simpleName})" else "Decryption failed unexpectedly: ${e.message}" + Log.e(testName, message, e) + TestResult(testName, passed, message, file) + } + } +} diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/MainActivity.kt b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/MainActivity.kt new file mode 100644 index 0000000..276d32d --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/MainActivity.kt @@ -0,0 +1,638 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.demo + +import android.app.admin.DevicePolicyManager +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.util.Log +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Description +import androidx.compose.material.icons.filled.Lock +import androidx.compose.material.icons.filled.LockOpen +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.VpnKey +import androidx.compose.material.icons.filled.Warning +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.android.niapsec.demo.R +import com.android.niapsec.demo.ui.theme.FileEncryptionLibTheme +import com.android.niapsec.encryption.api.EncryptionManager +import com.android.niapsec.encryption.api.KeyProviderType +import com.android.niapsec.encryption.tools.SecurityAuditLogger +import kotlinx.coroutines.launch +import java.io.File + + +class MainActivity : ComponentActivity() { + + companion object { + private const val PREFS_NAME = "demo_settings" + private const val KEY_SWEEP_ENABLED = "sweep_enabled" + private const val KEY_LOG_ENABLED = "log_enabled" + } + + private val prefs by lazy { getSharedPreferences(PREFS_NAME, MODE_PRIVATE) } + private val niapSecPrefs by lazy { getSharedPreferences("niap_sec_prefs", MODE_PRIVATE) } + private val sweepEnabled = mutableStateOf(true) + private val logEnabled = mutableStateOf(true) + private val flushIterationsCount = mutableStateOf(64) + + private val hybridFileKeyUri = "android-keystore://hybrid_file_key" + private val rawFileKeyUri = "android-keystore://raw_file_key" + private val rawHybridFileKeyUri = "android-keystore://raw_hybrid_file_key" + private lateinit var testRunner: EncryptionTestRunner + + private lateinit var devicePolicyManager: DevicePolicyManager + private lateinit var compName: ComponentName + + private val unlockReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + if (intent?.action == Intent.ACTION_USER_PRESENT) { + Log.d("MainActivity", "Device unlocked. Triggering auto-sweep...") + sweepAndRewrap() + } + } + } + + private var _hybridManager: EncryptionManager? = null + private val hybridManager: EncryptionManager + get() { + if (_hybridManager == null) { + _hybridManager = EncryptionManager(this, hybridFileKeyUri, providerType = KeyProviderType.HYBRID, unlockedDeviceRequired = true) + } + return _hybridManager!! + } + + private var _rawManager: EncryptionManager? = null + private val rawManager: EncryptionManager + get() { + if (_rawManager == null) { + _rawManager = EncryptionManager(this, rawFileKeyUri, providerType = KeyProviderType.RAW, unlockedDeviceRequired = true) + } + return _rawManager!! + } + + private var _rawHybridManager: EncryptionManager? = null + private val rawHybridManager: EncryptionManager + get() { + if (_rawHybridManager == null) { + _rawHybridManager = EncryptionManager(this, rawHybridFileKeyUri, providerType = KeyProviderType.RAW_HYBRID, unlockedDeviceRequired = true) + } + return _rawHybridManager!! + } + + private val testResults = mutableStateOf>(emptyList()) + private val fileStatusResults = mutableStateOf>(emptyList()) + + private val requestAdminLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + if (result.resultCode != RESULT_OK) { + Log.e("DeviceAdmin", "Failed to get device admin permission.") + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + testRunner = EncryptionTestRunner(this) + devicePolicyManager = getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager + compName = ComponentName(this, DeviceAdminReceiver::class.java) + + sweepEnabled.value = prefs.getBoolean(KEY_SWEEP_ENABLED, true) + logEnabled.value = prefs.getBoolean(KEY_LOG_ENABLED, true) + flushIterationsCount.value = niapSecPrefs.getInt("keystore_flush_iterations", 64) + SecurityAuditLogger.isAuditLogEnabled = logEnabled.value + + registerReceiver(unlockReceiver, IntentFilter(Intent.ACTION_USER_PRESENT)) + sweepAndRewrap() + + setContent { + FileEncryptionLibTheme { + TestScreen() + } + } + } + + override fun onResume() { + super.onResume() + sweepAndRewrap() + } + + override fun onDestroy() { + super.onDestroy() + unregisterReceiver(unlockReceiver) + } + + @OptIn(ExperimentalMaterial3Api::class) + @Composable + private fun TestScreen() { + val snackbarHostState = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + val showDeleteConfirmation = remember { mutableStateOf(false) } + var expanded by remember { mutableStateOf(false) } + var sweepChecked by sweepEnabled + var loggingChecked by logEnabled + val showFlushIterationsDialog = remember { mutableStateOf(false) } + var flushIterationsInput by remember(flushIterationsCount.value) { mutableStateOf(flushIterationsCount.value.toString()) } + + if (showDeleteConfirmation.value) { + AlertDialog( + onDismissRequest = { showDeleteConfirmation.value = false }, + title = { Text("Delete All Keys & Data?") }, + text = { Text("This will permanently destroy all cryptographic keys and encrypted files. This action cannot be undone.") }, + confirmButton = { + TextButton( + onClick = { + showDeleteConfirmation.value = false + clearAll() + scope.launch { + snackbarHostState.showSnackbar("All keys and data destroyed") + } + } + ) { + Text("Delete", color = MaterialTheme.colorScheme.error) + } + }, + dismissButton = { + TextButton(onClick = { showDeleteConfirmation.value = false }) { + Text("Cancel") + } + } + ) + } + + if (showFlushIterationsDialog.value) { + AlertDialog( + onDismissRequest = { showFlushIterationsDialog.value = false }, + title = { Text("Set IPC Flush Iterations") }, + text = { + Column { + Text("Configure how many times the Keystore IPC dummy flush request operation is repeated.") + Spacer(modifier = Modifier.height(8.dp)) + androidx.compose.material3.OutlinedTextField( + value = flushIterationsInput, + onValueChange = { flushIterationsInput = it }, + label = { Text("Iterations") }, + keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Number) + ) + } + }, + confirmButton = { + TextButton(onClick = { + val newCount = flushIterationsInput.toIntOrNull() ?: 64 + flushIterationsCount.value = newCount + niapSecPrefs.edit().putInt("keystore_flush_iterations", newCount).apply() + showFlushIterationsDialog.value = false + }) { + Text("Save") + } + }, + dismissButton = { + TextButton(onClick = { showFlushIterationsDialog.value = false }) { + Text("Cancel") + } + } + ) + } + + Scaffold( + snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, + topBar = { + TopAppBar( + title = { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Default.VpnKey, contentDescription = "Encryption Key") + Spacer(modifier = Modifier.width(8.dp)) + Text("File Encryption Demo") + } + }, + actions = { + IconButton(onClick = { expanded = !expanded }) { + Icon( + imageVector = Icons.Default.MoreVert, + contentDescription = "More", + ) + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + DropdownMenuItem(text = { Text( + stringResource(R.string.enable_sweep) + ) }, leadingIcon = { + Checkbox(checked = sweepChecked, onCheckedChange = { toggleSweep(!sweepChecked) }) + }, onClick = { + toggleSweep(!sweepChecked) + }) + DropdownMenuItem(text = { Text( + stringResource(R.string.enable_logging) + )}, leadingIcon = { + Checkbox(checked = loggingChecked, onCheckedChange = { toggleLog(!loggingChecked) }) + },onClick = { + toggleLog(!loggingChecked) + }) + DropdownMenuItem(text = { Text("Set Flush Iterations") }, onClick = { + showFlushIterationsDialog.value = true + expanded = false + }) + } + } + } + ) + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding), + ) { + LazyColumn( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.Top, + horizontalAlignment = Alignment.CenterHorizontally, + contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp) + ) { + item { + /* *** Temporarily removed for readability. *** LLM must not modify here *** + ProviderTestGroup( + title = "Tink HYBRID", + onTestClick = { runHybridFileTest() }, + onLockAndTestClick = { lockAndTest(KeyProviderType.HYBRID) } + ) + Spacer(modifier = Modifier.height(16.dp)) + + ProviderTestGroup( + title = "JCA RAW", + onTestClick = { runRawFileTest() }, + onLockAndTestClick = { lockAndTest(KeyProviderType.RAW) } + ) + Spacer(modifier = Modifier.height(16.dp)) + */ + ProviderTestGroup( + title = "JCA RAW HYBRID", + onTestClick = { runRawHybridFileTest() }, + onLockAndTestClick = { lockAndTest(KeyProviderType.RAW_HYBRID) } + ) + + Spacer(modifier = Modifier.height(16.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Button(onClick = { checkFileStatus() }) { Text("Check Status") } + Button(onClick = { encryptFileManual() }) { Text("Encrypt File") } + } + + Spacer(modifier = Modifier.height(16.dp)) + Button( + onClick = { showDeleteConfirmation.value = true }, + colors = androidx.compose.material3.ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.error + ) + ) { + Text("Clear All Keys & Data") + } + + Spacer(modifier = Modifier.height(16.dp)) + HorizontalDivider(modifier = Modifier.fillMaxWidth()) + } + + if (testResults.value.isNotEmpty()) { + item { + Text( + "Test Results", + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.padding(vertical = 8.dp) + ) + } + items(testResults.value) { result -> + TestResultRow(result, isFile = false) + } + item { HorizontalDivider(modifier = Modifier + .fillMaxWidth() + .padding(vertical = 8.dp)) } + } + + if (fileStatusResults.value.isNotEmpty()) { + item { + Text( + "File Storage Status", + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.padding(vertical = 8.dp) + ) + } + items(fileStatusResults.value) { result -> + TestResultRow(result, isFile = true) { + result.file?.let { file -> + scope.launch { + try { + val header = readHeader(file) + val manager = when (header) { + "ERAW" -> rawManager + "EHBT" -> hybridManager + "EHBR" -> rawHybridManager + else -> rawHybridManager + } + val plaintext = manager.decryptFromFile(file).use { it.reader().readText() } + snackbarHostState.showSnackbar("Decrypted: $plaintext") + } catch (e: Exception) { + snackbarHostState.showSnackbar("Decryption failed: ${e.message}") + } + } + } + } + } + } + } + } + } + } + + private fun readHeader(file: File): String { + return try { + val input = file.inputStream() + val headerBytes = ByteArray(4) + val read = input.read(headerBytes) + input.close() + if (read == 4) String(headerBytes) else "" + } catch (e: Exception) { "" } + } + + private fun sweepAndRewrap() { + if (!sweepEnabled.value) return + try { + rawHybridManager.sweepAndRewrapPendingFiles() + checkFileStatus() + } catch (e: Exception) { + Log.e("MainActivity", "Sweep failed", e) + } + } + + private fun encryptFileManual() { + val file = File(filesDir, "Manual-Encrypt-test_file.enc") + try { + val text = "This is a manual encrypted message." + rawHybridManager.encryptToFile(file).use { it.write(text.toByteArray()) } + checkFileStatus() + } catch (e: Exception) { + Log.e("MainActivity", "Manual encryption failed", e) + } + } + + private fun toggleSweep(enabled: Boolean) { + sweepEnabled.value = enabled + prefs.edit().putBoolean(KEY_SWEEP_ENABLED, enabled).apply() + } + + private fun toggleLog(enabled: Boolean) { + logEnabled.value = enabled + SecurityAuditLogger.isAuditLogEnabled = enabled + prefs.edit().putBoolean(KEY_LOG_ENABLED, enabled).apply() + } + + private fun readHeaderAndMagic(file: File): Pair { + return try { + file.inputStream().use { input -> + val buffer = ByteArray(5) + val read = input.read(buffer) + if (read >= 4) { + val header = String(buffer.sliceArray(0..3)) + val magic = if (read == 5) buffer[4].toInt() else 0 + Pair(header, magic) + } else Pair("", 0) + } + } catch (e: Exception) { Pair("", 0) } + } + private fun checkFileStatus() { + val results = mutableListOf() + val files = filesDir.listFiles()?.filter { it.name.endsWith(".enc") } ?: emptyList() + + files.forEach { file -> + val (header, magic) = readHeaderAndMagic(file) // Completely removed readBytes() + val status = when (header) { + "EHBT" -> "Tink Hybrid" + "ERAW" -> "JCA Raw" + "EHBR" -> when (magic) { + 0x01 -> "JCA RawHybrid (Asymmetric 0x01)" + 0x02 -> "JCA RawHybrid (Symmetric 0x02)" + else -> "JCA RawHybrid (Unknown)" + } + else -> "Unknown Header: $header" + } + results.add(TestResult(file.name, true, status, file)) + } + fileStatusResults.value = results + } + + @Composable + private fun TestResultRow(result: TestResult, isFile: Boolean, onClick: () -> Unit = {}) { + Row( + modifier = Modifier + .padding(8.dp) + .fillMaxWidth() + .clickable(enabled = isFile) { onClick() }, + verticalAlignment = Alignment.CenterVertically + ) { + val icon: ImageVector = if (isFile) { + when { + result.message.contains("0x01") -> Icons.Default.LockOpen + result.message.contains("0x02") -> Icons.Default.Lock + else -> Icons.Default.Description + } + } else { + if (result.passed) Icons.Default.CheckCircle else Icons.Default.Warning + } + + val iconColor = if (isFile) { + if (result.message.contains("0x02")) Color(0xFF4CAF50) else MaterialTheme.colorScheme.primary + } else { + if (result.passed) Color.Green else Color.Red + } + + Icon( + imageVector = icon, + contentDescription = null, + tint = iconColor + ) + Spacer(modifier = Modifier.width(12.dp)) + Column { + Text( + text = result.testName, + style = MaterialTheme.typography.bodyLarge, + color = if (result.passed || isFile) Color.Unspecified else Color.Red + ) + Text( + text = result.message, + style = MaterialTheme.typography.bodySmall, + color = if (result.passed || isFile) Color.Unspecified else Color.Red + ) + if (isFile) { + Text( + text = "Tap to verify decryption", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.secondary + ) + } + } + } + } + + @Composable + private fun ProviderTestGroup(title: String, onTestClick: () -> Unit, onLockAndTestClick: () -> Unit) { + var isProcessing by remember { mutableStateOf(false) } + + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text(text = title, style = MaterialTheme.typography.titleLarge) + Spacer(modifier = Modifier.height(8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Button( + onClick = { + if (!isProcessing) { + isProcessing = true + onTestClick() + Handler(Looper.getMainLooper()).postDelayed({ isProcessing = false }, 1000) + } + }, + enabled = !isProcessing + ) { Text("Test File") } + Button( + onClick = { + if (!isProcessing) { + isProcessing = true + onLockAndTestClick() + Handler(Looper.getMainLooper()).postDelayed({ isProcessing = false }, 1000) + } + }, + enabled = !isProcessing + ) { Text("Lock & Test") } + } + } + } + + private fun runHybridFileTest() { + testResults.value = testRunner.runFullTest(hybridManager, "TinkHybridFileTest") + } + + private fun runRawFileTest() { + testResults.value = testRunner.runFullTest(rawManager, "JcaRawFileTest") + } + + private fun runRawHybridFileTest() { + testResults.value = testRunner.runFullTest(rawHybridManager, "JcaRawHybridFileTest") + } + + private fun lockAndTest(providerType: KeyProviderType) { + if (!devicePolicyManager.isAdminActive(compName)) { + requestDeviceAdmin() + return + } + + val manager = when (providerType) { + KeyProviderType.HYBRID -> hybridManager + KeyProviderType.RAW -> rawManager + KeyProviderType.RAW_HYBRID -> rawHybridManager + else -> throw IllegalArgumentException("Unsupported provider type: $providerType") + } + + val keyguardManager = getSystemService(KEYGUARD_SERVICE) as android.app.KeyguardManager + Log.d("LockAndTest", "Locking screen to test $providerType provider...") + devicePolicyManager.lockNow() + + val handler = Handler(Looper.getMainLooper()) + val startTime = System.currentTimeMillis() + val timeoutMs = 5000L + + val checkStateRunnable = object : Runnable { + override fun run() { + val isLocked = keyguardManager.isDeviceLocked + val elapsed = System.currentTimeMillis() - startTime + + if (isLocked) { + Log.d("LockAndTest", "Device is LOCKED after ${elapsed}ms. Proceeding with test.") + val shouldFail = true + testResults.value = testRunner.runFullTest(manager, "${providerType}AfterLock", reverseDecryptionResult = shouldFail) + } else if (elapsed < timeoutMs) { + handler.postDelayed(this, 200) + } else { + Log.e("LockAndTest", "Timeout waiting for device to lock. Proceeding anyway.") + val shouldFail = true + testResults.value = testRunner.runFullTest(manager, "${providerType}AfterLock", reverseDecryptionResult = shouldFail) + } + } + } + handler.postDelayed(checkStateRunnable, 200) + } + + private fun requestDeviceAdmin() { + val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN).apply { + putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName) + putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "This app needs permission to lock the screen for testing.") + } + requestAdminLauncher.launch(intent) + } + + private fun clearAll() { + hybridManager.destroy() + _hybridManager = null + rawManager.destroy() + _rawManager = null + rawHybridManager.destroy() + _rawHybridManager = null + testResults.value = emptyList() + fileStatusResults.value = emptyList() + Log.d("ClearData", "All keys and data have been destroyed.") + } +} diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/ui/theme/Color.kt b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/ui/theme/Color.kt new file mode 100644 index 0000000..a00f8fa --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/ui/theme/Color.kt @@ -0,0 +1,26 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.demo.ui.theme + +import androidx.compose.ui.graphics.Color + +val Purple80 = Color(0xFFD0BCFF) +val PurpleGrey80 = Color(0xFFCCC2DC) +val Pink80 = Color(0xFFEFB8C8) + +val Purple40 = Color(0xFF6650a4) +val PurpleGrey40 = Color(0xFF625b71) +val Pink40 = Color(0xFF7D5260) \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/ui/theme/Theme.kt b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/ui/theme/Theme.kt new file mode 100644 index 0000000..c4e2ebd --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/ui/theme/Theme.kt @@ -0,0 +1,72 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.demo.ui.theme + +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalContext + +private val DarkColorScheme = darkColorScheme( + primary = Purple80, + secondary = PurpleGrey80, + tertiary = Pink80 +) + +private val LightColorScheme = lightColorScheme( + primary = Purple40, + secondary = PurpleGrey40, + tertiary = Pink40 + + /* Other default colors to override + background = Color(0xFFFFFBFE), + surface = Color(0xFFFFFBFE), + onPrimary = Color.White, + onSecondary = Color.White, + onTertiary = Color.White, + onBackground = Color(0xFF1C1B1F), + onSurface = Color(0xFF1C1B1F), + */ +) + +@Composable +fun FileEncryptionLibTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + // Dynamic color is available on Android 12+ + dynamicColor: Boolean = true, + content: @Composable () -> Unit +) { + val colorScheme = when { + dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + val context = LocalContext.current + if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + + darkTheme -> DarkColorScheme + else -> LightColorScheme + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/ui/theme/Type.kt b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/ui/theme/Type.kt new file mode 100644 index 0000000..0096a78 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/java/com/android/niapsec/demo/ui/theme/Type.kt @@ -0,0 +1,49 @@ +/* +* Copyright (C) 2026 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. +*/ +package com.android.niapsec.demo.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Set of Material typography styles to start with +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) + /* Other default text styles to override + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp + ) + */ +) \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/drawable/ic_launcher_background.xml b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..ca3826a --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/drawable/ic_launcher_foreground.xml b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..c3432a1 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,18 @@ + + + + + diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/menu/mainmenu.xml b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/menu/mainmenu.xml new file mode 100644 index 0000000..357613c --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/menu/mainmenu.xml @@ -0,0 +1,14 @@ + + + > + + + \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..50ec886 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..50ec886 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-hdpi/ic_launcher.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..70f5d86 Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..a1d0969 Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-mdpi/ic_launcher.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..6671bb6 Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..6d37f22 Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xhdpi/ic_launcher.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..4694393 Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..cc6e2ac Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..8ee6440 Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..671df81 Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..50e934e Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..814679f Binary files /dev/null and b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/values/colors.xml b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/values/strings.xml b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/values/strings.xml new file mode 100644 index 0000000..271d410 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/values/strings.xml @@ -0,0 +1,5 @@ + + File Encryption Demo + Enable DAR_EXT.2.4 sweep + Enable logging + \ No newline at end of file diff --git a/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/values/themes.xml b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/values/themes.xml new file mode 100644 index 0000000..bc99766 --- /dev/null +++ b/niap-cc/sdp-file-encrypt/locked-device-demo/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +