diff --git a/.github/scripts/build-signed-android.sh b/.github/scripts/build-signed-android.sh index 859cff6a..fb125c5a 100644 --- a/.github/scripts/build-signed-android.sh +++ b/.github/scripts/build-signed-android.sh @@ -9,9 +9,31 @@ set -euo pipefail : "${RUNNER_TEMP:?RUNNER_TEMP must be set}" umask 077 signing_dir=$(mktemp -d "$RUNNER_TEMP/wheelplay-signing.XXXXXX") -trap 'rm -rf -- "$signing_dir"' EXIT +ca_dir='' +cleanup() { + rm -rf -- "$signing_dir" + [[ -z $ca_dir ]] || rm -rf -- "$ca_dir" +} +trap cleanup EXIT export ANDROID_KEYSTORE_PATH="$signing_dir/wheelplay.jks" printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > "$ANDROID_KEYSTORE_PATH" unset ANDROID_KEYSTORE_BASE64 + +# Optional bundled HTTPS signing CA. A caller may already have provisioned one +# (for example the Debug workflow exports WHEELPLAY_HTTPS_CA_PEM into GITHUB_ENV); +# otherwise this helper validates the secret or the fallback and reports a +# temporary path that the trap above deletes together with the keystore. +want_ca=0 +if [[ -n ${WHEELPLAY_HTTPS_CA_PEM_BASE64:-} ]]; then want_ca=1; fi +if [[ ${WHEELPLAY_HTTPS_CA_REQUIRED:-0} == 1 ]]; then want_ca=1; fi +if [[ ${WHEELPLAY_HTTPS_CA_FALLBACK:-} == mitmproxy ]]; then want_ca=1; fi +if [[ -z ${WHEELPLAY_HTTPS_CA_PEM:-} && $want_ca == 1 ]]; then + ca_dir=$(mktemp -d "$RUNNER_TEMP/wheelplay-https-ca.XXXXXX") + script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) + WHEELPLAY_HTTPS_CA_PEM=$(bash "$script_dir/provision-https-ca.sh" --output-dir "$ca_dir") + export WHEELPLAY_HTTPS_CA_PEM + unset WHEELPLAY_HTTPS_CA_PEM_BASE64 +fi + # Configuration cache can serialize signing passwords; never save it for signed builds. ./gradlew --no-daemon --no-configuration-cache "$@" diff --git a/.github/scripts/provision-https-ca-env.sh b/.github/scripts/provision-https-ca-env.sh new file mode 100755 index 00000000..779bfd3f --- /dev/null +++ b/.github/scripts/provision-https-ca-env.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Provision the bundled HTTPS signing CA for a build step that is not +# build-signed-android.sh (the Debug workflow), and export its path to later steps. +# +# Writes WHEELPLAY_HTTPS_CA_PEM into $GITHUB_ENV and leaves the material in +# $RUNNER_TEMP; the workflow must delete it afterwards (see the cleanup step in +# debug-build.yml). No CA is exported when none was requested. +# +# WHEELPLAY_HTTPS_CA_PEM_BASE64 / _REQUIRED / _FALLBACK behave exactly as in +# provision-https-ca.sh; see docs/HTTPS_SIGNING_CA.md. + +: "${RUNNER_TEMP:?RUNNER_TEMP must be set}" +: "${GITHUB_ENV:?GITHUB_ENV must be set}" + +announce() { + if [[ -n ${GITHUB_ACTIONS:-} ]]; then + printf '::%s::%s\n' "$1" "$2" >&2 + else + printf '%s\n' "$2" >&2 + fi +} + +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) +umask 077 +ca_dir=$(mktemp -d "$RUNNER_TEMP/wheelplay-https-ca.XXXXXX") + +if ! pem=$(bash "$script_dir/provision-https-ca.sh" --output-dir "$ca_dir"); then + rm -rf -- "$ca_dir" + exit 1 +fi + +if [[ -z $pem ]]; then + rm -rf -- "$ca_dir" + announce notice 'No bundled HTTPS CA for this build.' + exit 0 +fi + +# Only the path is exported; the key stays in the runner's temporary directory. +printf 'WHEELPLAY_HTTPS_CA_PEM=%s\n' "$pem" >> "$GITHUB_ENV" diff --git a/.github/scripts/provision-https-ca.sh b/.github/scripts/provision-https-ca.sh new file mode 100755 index 00000000..9ea04efe --- /dev/null +++ b/.github/scripts/provision-https-ca.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Restore the optional bundled HTTPS signing CA for a CI build. +# +# Prints the absolute PEM path on success and nothing when no CA is requested. +# The caller owns --output-dir and must delete it; this helper only writes there. +# Combined format: one unencrypted RSA/EC private key, then the ordered CA path +# (see docs/HTTPS_SIGNING_CA.md). The checks below mirror BundleHttpsCa in +# mobile/build.gradle.kts so bad material fails before Gradle starts instead of +# after a full toolchain setup. +# +# WHEELPLAY_HTTPS_CA_PEM_BASE64 Base64 of the combined PEM (repository secret). +# WHEELPLAY_HTTPS_CA_REQUIRED 1 requires some bundled CA: the secret or the fallback. +# WHEELPLAY_HTTPS_CA_FALLBACK Only the literal "mitmproxy" enables the pinned +# mitmproxy source; the Release workflow sets it by default. + +readonly max_bytes=$((2 * 1024 * 1024)) +readonly usage='usage: provision-https-ca.sh --output-dir DIR' + +# Pinned so the fallback cannot silently follow upstream changes. +readonly fallback_commit=82416906e3ac55b88d215500adf40959e237589d +readonly fallback_url="https://raw.githubusercontent.com/mhils/mitmproxy/$fallback_commit/mitmproxy/certs.py" +readonly fallback_marker='EMUDHRA_CHAIN_PEM = b"""' + +output_dir='' +while (($# > 0)); do + case $1 in + --output-dir) + (($# >= 2)) || { printf '%s\n' "provision-https-ca.sh: --output-dir needs a value" >&2; exit 2; } + output_dir=$2 + shift 2 + ;; + -h|--help) + printf '%s\n' "$usage" + exit 0 + ;; + *) + printf '%s\n' "provision-https-ca.sh: unknown argument: $1" "$usage" >&2 + exit 2 + ;; + esac +done +[[ -n $output_dir ]] || { printf '%s\n' "provision-https-ca.sh: --output-dir is required" "$usage" >&2; exit 2; } + +# Actions annotations when running in Actions, plain diagnostics otherwise. +announce() { + if [[ -n ${GITHUB_ACTIONS:-} ]]; then + printf '::%s::%s\n' "$1" "$2" >&2 + else + printf '%s\n' "$2" >&2 + fi +} +fail() { announce error "$1"; exit 1; } + +# Bundled CA from the fallback is public material, so the log records its source +# without printing any key bytes. +notify_source() { + announce notice 'Bundled HTTPS CA comes from the pinned mitmproxy source (public key material, no identity guarantee).' +} + +encoded=${WHEELPLAY_HTTPS_CA_PEM_BASE64:-} +required=${WHEELPLAY_HTTPS_CA_REQUIRED:-0} +fallback=${WHEELPLAY_HTTPS_CA_FALLBACK:-} + +ca_source='' +if [[ -n $encoded ]]; then + ca_source=secret +elif [[ $fallback == mitmproxy ]]; then + ca_source=mitmproxy +elif [[ $required == 1 ]]; then + fail 'WHEELPLAY_HTTPS_CA_REQUIRED=1 but there is no WHEELPLAY_HTTPS_CA_PEM_BASE64 secret and no mitmproxy fallback.' +else + announce notice 'No WHEELPLAY_HTTPS_CA_PEM_BASE64 secret; building without a bundled HTTPS signing CA.' + exit 0 +fi + +umask 077 +mkdir -p -- "$output_dir" +pem_dir=$(cd -- "$output_dir" && pwd -P) +pem=$pem_dir/emudhra-ca.pem + +if [[ $ca_source == secret ]]; then + # Base64 only encodes bytes; GitHub Secrets provides the confidentiality, so the + # value must never be echoed or written into the checkout. + if ! printf '%s' "${encoded//[[:space:]]/}" | base64 --decode > "$pem" 2>/dev/null; then + rm -f -- "$pem" + fail 'WHEELPLAY_HTTPS_CA_PEM_BASE64 is not valid Base64. Re-encode the combined PEM file and update the secret.' + fi +else + notify_source + command -v curl > /dev/null || fail 'WHEELPLAY_HTTPS_CA_FALLBACK=mitmproxy needs curl to read the pinned mitmproxy source.' + download=$pem_dir/certs.py + if ! curl --fail --silent --show-error --location --max-time 60 \ + --max-filesize 1048576 --output "$download" "$fallback_url"; then + rm -f -- "$download" + fail "Could not download $fallback_url for the mitmproxy CA fallback." + fi + # Take only the combined PEM constant; the rest of certs.py is irrelevant here. + awk -v marker="$fallback_marker" ' + index($0, marker) == 1 { capture = 1; next } + capture && $0 == "\"\"\"" { exit } + capture { sub(/\r$/, ""); print } + ' "$download" > "$pem" + rm -f -- "$download" + if ! grep -q -- '-----BEGIN PRIVATE KEY-----' "$pem"; then + rm -f -- "$pem" + fail "The pinned mitmproxy source no longer contains $fallback_marker at $fallback_commit." + fi +fi + +size=$(wc -c < "$pem") +if ((size == 0)); then + rm -f -- "$pem" + fail "Bundled HTTPS CA from the $ca_source is empty." +fi +if ((size > max_bytes)); then + rm -f -- "$pem" + fail "HTTPS signing CA PEM is ${size} bytes; the bundled CA is limited to ${max_bytes} bytes (2 MiB)." +fi + +key_count=$(grep -c -E '^-----BEGIN (RSA |EC )?PRIVATE KEY-----' "$pem" || true) +cert_count=$(grep -c -E '^-----BEGIN CERTIFICATE-----' "$pem" || true) +if [[ $key_count != 1 ]] || [[ $cert_count == 0 ]] || grep -q 'ENCRYPTED' "$pem"; then + rm -f -- "$pem" + fail "HTTPS signing CA PEM from the $ca_source needs exactly one unencrypted RSA/EC private key and at least one certificate." +fi + +# Only the path reaches the build; the key stays in the runner's temporary directory. +printf '%s\n' "$pem" diff --git a/.github/workflows/debug-build.yml b/.github/workflows/debug-build.yml index d89e9fbc..c9b59769 100644 --- a/.github/workflows/debug-build.yml +++ b/.github/workflows/debug-build.yml @@ -71,6 +71,9 @@ jobs: - name: Verify SDK installation helper run: node --test test/ci-android-*.test.js + - name: Verify HTTPS CA provisioning helper + run: node --test test/ci-https-ca.test.js + - name: Install missing Android packages run: | bash .github/scripts/install-android-packages.sh \ @@ -79,6 +82,14 @@ jobs: "ndk;$ANDROID_NDK_VERSION" \ "cmake;$ANDROID_CMAKE_VERSION" + - name: Provision bundled HTTPS signing CA + env: + WHEELPLAY_HTTPS_CA_PEM_BASE64: ${{ secrets.WHEELPLAY_HTTPS_CA_PEM_BASE64 }} + # Same defaults as the Release build: always bundle a CA, secret first. + WHEELPLAY_HTTPS_CA_REQUIRED: ${{ vars.WHEELPLAY_HTTPS_CA_REQUIRED || '1' }} + WHEELPLAY_HTTPS_CA_FALLBACK: ${{ vars.WHEELPLAY_HTTPS_CA_FALLBACK || 'mitmproxy' }} + run: bash .github/scripts/provision-https-ca-env.sh + - name: Build and lint Debug artifacts env: USE_RELEASE_SIGNING: ${{ github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/')) }} @@ -151,6 +162,11 @@ jobs: path: mobile/build/reports/lint-results-debug.* if-no-files-found: warn + # The provisioned CA is job-scoped; remove it once every artifact is uploaded. + - name: Remove provisioned HTTPS signing CA + if: always() + run: rm -rf -- "$RUNNER_TEMP"/wheelplay-https-ca.* + browser-runtime: name: Browser HTTP on Android ${{ matrix.api-level }} needs: build diff --git a/.github/workflows/release-build.yml b/.github/workflows/release-build.yml index 749266f3..71a7ef32 100644 --- a/.github/workflows/release-build.yml +++ b/.github/workflows/release-build.yml @@ -38,12 +38,36 @@ jobs: ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + # Optional bundled HTTPS signing CA; see docs/HTTPS_SIGNING_CA.md. + WHEELPLAY_HTTPS_CA_PEM_BASE64: ${{ secrets.WHEELPLAY_HTTPS_CA_PEM_BASE64 }} + # Defaults: a CA is always bundled, taken from the pinned mitmproxy source + # when the secret is absent. Override with 0 / none to disable. + WHEELPLAY_HTTPS_CA_REQUIRED: ${{ vars.WHEELPLAY_HTTPS_CA_REQUIRED || '1' }} + WHEELPLAY_HTTPS_CA_FALLBACK: ${{ vars.WHEELPLAY_HTTPS_CA_FALLBACK || 'mitmproxy' }} run: bash .github/scripts/build-signed-android.sh :mobile:assembleRelease :mobile:bundleRelease - name: Verify APK signature run: '"$ANDROID_HOME/build-tools/36.0.0/apksigner" verify --verbose mobile/build/outputs/apk/release/mobile-release.apk' + - name: Verify bundled HTTPS signing CA + id: bundled-ca + env: + WHEELPLAY_HTTPS_CA_PEM_BASE64: ${{ secrets.WHEELPLAY_HTTPS_CA_PEM_BASE64 }} + WHEELPLAY_HTTPS_CA_FALLBACK: ${{ vars.WHEELPLAY_HTTPS_CA_FALLBACK || 'mitmproxy' }} + run: | + if [[ -z $WHEELPLAY_HTTPS_CA_PEM_BASE64 && $WHEELPLAY_HTTPS_CA_FALLBACK != mitmproxy ]]; then + echo 'No HTTPS CA secret or fallback; this Release has no bundled HTTPS signing CA.' + exit 0 + fi + apk=mobile/build/outputs/apk/release/mobile-release.apk + unzip -p "$apk" assets/web-tls/emudhra-ca.pem > /dev/null + if [[ -z $WHEELPLAY_HTTPS_CA_PEM_BASE64 ]]; then + echo 'fallback=true' >> "$GITHUB_OUTPUT" + echo '::notice::Bundled CA comes from the mitmproxy source; see docs/HTTPS_SIGNING_CA.md.' + else + echo 'Bundled HTTPS signing CA is present in the Release APK.' + fi - uses: actions/upload-artifact@v4 with: - name: wheelplay-release + name: wheelplay-release${{ steps.bundled-ca.outputs.fallback == 'true' && '-MITMPROXY-CA' || '' }} path: | mobile/build/outputs/apk/release/mobile-release.apk mobile/build/outputs/bundle/release/mobile-release.aab diff --git a/common/src/main/java/com/shilapi/xcertplay/web/LanTls.kt b/common/src/main/java/com/shilapi/xcertplay/web/LanTls.kt index e68721e3..3363fb49 100644 --- a/common/src/main/java/com/shilapi/xcertplay/web/LanTls.kt +++ b/common/src/main/java/com/shilapi/xcertplay/web/LanTls.kt @@ -8,6 +8,7 @@ import java.io.ByteArrayOutputStream import java.io.File import java.io.InputStream import java.io.StringReader +import java.io.StringWriter import java.math.BigInteger import java.security.KeyFactory import java.security.KeyPairGenerator @@ -44,8 +45,10 @@ import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo +import org.bouncycastle.util.io.pem.PemReader +import org.bouncycastle.util.io.pem.PemWriter -/** Local CA or imported server identity, stored only in private non-backup storage. */ +/** Local CA, imported server identity, or imported signer in private non-backup storage. */ internal object LanTls { data class Endpoint( val sockets: SSLServerSocketFactory, @@ -53,6 +56,8 @@ internal object LanTls { val fingerprint: String, val custom: Boolean = false, val subject: String = "", + val signingCa: Boolean = false, + val bundledCa: Boolean = false, ) class Prepared(val encoded: ByteArray, val endpoint: Endpoint) : AutoCloseable { @@ -62,6 +67,7 @@ internal object LanTls { } const val MAX_IMPORT_BYTES = 2 * 1024 * 1024 + const val BUNDLED_CA_ASSET = "web-tls/emudhra-ca.pem" private val provider = BouncyCastleProvider() fun readImport(input: InputStream): ByteArray = @@ -85,17 +91,66 @@ internal object LanTls { fun hasCustom(context: Context) = customFile(context).baseFile.exists() + fun hasBundledCa(context: Context) = + try { context.assets.open(BUNDLED_CA_ASSET).use { true } } + catch (_: java.io.FileNotFoundException) { false } + + fun usesBundledCa(context: Context) = !hasCustom(context) && WebListenSettings.bundledCaEnabled(context) + + private fun loadCustom(context: Context): KeyStore = + KeyStore.getInstance("PKCS12").apply { + customFile(context).openRead().use { load(it, CharArray(0)) } + } + + @Synchronized + fun hasSigningCa(context: Context) = + hasCustom(context) && loadCustom(context).isKeyEntry("signer") + + fun generatesCertificates(context: Context) = !hasCustom(context) || hasSigningCa(context) + @Synchronized fun create(context: Context, addresses: List, hostname: String = ""): Endpoint { val file = customFile(context) if (file.baseFile.exists()) { - val store = KeyStore.getInstance("PKCS12") - file.openRead().use { store.load(it, CharArray(0)) } + val store = loadCustom(context) + if (store.isKeyEntry("signer")) return signingEndpoint(store, addresses, hostname) return endpoint(store, "server", true) } + if (usesBundledCa(context)) return createBundled(context, addresses, hostname) return createDefault(context, addresses, hostname) } + fun createBundled(context: Context, addresses: List, hostname: String = ""): Endpoint { + val pem = context.assets.open(BUNDLED_CA_ASSET).use(::readImport) + return try { + prepareSigningCaBundle(pem, addresses, hostname).use { + it.endpoint.copy(bundledCa = true) + } + } finally { pem.fill(0) } + } + + /** Combined key + certificate PEM, like mitmproxy's embedded CA bundle. */ + fun prepareSigningCaBundle(pem: ByteArray, addresses: List, hostname: String = ""): Prepared { + require(pem.size in 1..MAX_IMPORT_BYTES) { "Invalid HTTPS CA bundle size" } + val certificates = StringWriter() + val privateKey = StringWriter() + PemWriter(certificates).use { certWriter -> + PemWriter(privateKey).use { keyWriter -> + PemReader(StringReader(pem.toString(Charsets.UTF_8))).use { reader -> + while (true) { + val value = reader.readPemObject() ?: break + if (value.type == "CERTIFICATE") certWriter.writeObject(value) + else keyWriter.writeObject(value) + } + } + } + } + val chain = certificates.toString().toByteArray(Charsets.UTF_8) + val key = privateKey.toString().toByteArray(Charsets.UTF_8) + return try { prepareSigningCaPem(chain, key, addresses = addresses, hostname = hostname) } + finally { chain.fill(0); key.fill(0) } + } + @Synchronized fun createDefault(context: Context, addresses: List, hostname: String = ""): Endpoint { val password = CharArray(0) @@ -141,7 +196,12 @@ internal object LanTls { return endpoint(leafStore, "server", false) } - private fun endpoint(store: KeyStore, alias: String, custom: Boolean): Endpoint { + private fun endpoint( + store: KeyStore, + alias: String, + custom: Boolean, + signingCa: Boolean = false, + ): Endpoint { val chain = store.getCertificateChain(alias).map { it as X509Certificate } chain.forEach { it.checkValidity() } val managers = @@ -161,6 +221,7 @@ internal object LanTls { fingerprint, custom, chain.first().subjectX500Principal.name, + signingCa, ) } @@ -169,6 +230,41 @@ internal object LanTls { privateKey: ByteArray, password: CharArray = CharArray(0), ): Prepared { + val (key, chain) = readPemIdentity(certificates, privateKey, password) + return prepare(key, chain) + } + + /** The first certificate is the signing CA, followed by its ordered issuer chain. */ + fun prepareSigningCaPem( + certificates: ByteArray, + privateKey: ByteArray, + password: CharArray = CharArray(0), + addresses: List, + hostname: String = "", + ): Prepared { + val (parsedKey, chain) = readPemIdentity(certificates, privateKey, password) + val key = normalizeKey(parsedKey) + SigningCa.validate(key, chain) + val store = KeyStore.getInstance("PKCS12").apply { + load(null, CharArray(0)) + setKeyEntry("signer", key, CharArray(0), chain.toTypedArray()) + } + val endpoint = signingEndpoint(store, addresses, hostname) + return Prepared(encode(store), endpoint) + } + + private fun signingEndpoint(store: KeyStore, addresses: List, hostname: String): Endpoint { + val key = store.getKey("signer", CharArray(0)) as PrivateKey + val chain = store.getCertificateChain("signer").map { it as X509Certificate } + val identity = SigningCa.issue(key, chain, addresses, hostname) + return endpoint(identity, "server", true, signingCa = true) + } + + private fun readPemIdentity( + certificates: ByteArray, + privateKey: ByteArray, + password: CharArray, + ): Pair> { requireUi( certificates.size in 1..MAX_IMPORT_BYTES && privateKey.size in 1..MAX_IMPORT_BYTES ) { @@ -212,7 +308,7 @@ internal object LanTls { } converter.getPrivateKey(info) } - return prepare(key, chain) + return key to chain } private fun loadPkcs12(bytes: ByteArray, password: CharArray): KeyStore { @@ -266,14 +362,16 @@ internal object LanTls { return prepare(key, chain) } - private fun prepare(privateKey: PrivateKey, chain: List): Prepared { + private fun normalizeKey(privateKey: PrivateKey): PrivateKey = // PEM converters may name an EC key "ECDSA". Conscrypt's PrivateKeyEntry // requires the same "EC" algorithm name as the certificate's public key. - val key = - if (privateKey.algorithm.equals("ECDSA", ignoreCase = true)) - KeyFactory.getInstance("EC", provider) - .generatePrivate(PKCS8EncodedKeySpec(privateKey.encoded)) - else privateKey + if (privateKey.algorithm.equals("ECDSA", ignoreCase = true)) + KeyFactory.getInstance("EC", provider) + .generatePrivate(PKCS8EncodedKeySpec(privateKey.encoded)) + else privateKey + + private fun prepare(privateKey: PrivateKey, chain: List): Prepared { + val key = normalizeKey(privateKey) requireUi(chain.isNotEmpty() && chain.first().basicConstraints < 0) { UiText(UiR.string.ui_a_server_certificate_is_required_a_ca_certificate_cannot) } @@ -320,12 +418,12 @@ internal object LanTls { load(null, CharArray(0)) setKeyEntry("server", key, CharArray(0), chain.toTypedArray()) } - val bytes = - ByteArrayOutputStream().use { - store.store(it, CharArray(0)) - it.toByteArray() - } - return Prepared(bytes, endpoint(store, "server", true)) + return Prepared(encode(store), endpoint(store, "server", true)) + } + + private fun encode(store: KeyStore) = ByteArrayOutputStream().use { + store.store(it, CharArray(0)) + it.toByteArray() } @Synchronized diff --git a/common/src/main/java/com/shilapi/xcertplay/web/LanWebServer.kt b/common/src/main/java/com/shilapi/xcertplay/web/LanWebServer.kt index 3d628428..c5fc7d02 100644 --- a/common/src/main/java/com/shilapi/xcertplay/web/LanWebServer.kt +++ b/common/src/main/java/com/shilapi/xcertplay/web/LanWebServer.kt @@ -149,6 +149,8 @@ internal class LanWebServer( .put("fingerprint", WebSession.tls?.fingerprint) .put("port", WebSession.httpsPortFor(context, session.headers["host"])) .put("customCertificate", WebSession.tls?.custom == true) + .put("signingCa", WebSession.tls?.signingCa == true) + .put("bundledCa", WebSession.tls?.bundledCa == true) .put("enabled", WebListenSettings.httpsEnabled(context)) .put("error", WebSession.tlsError) .toString(), diff --git a/common/src/main/java/com/shilapi/xcertplay/web/SigningCa.kt b/common/src/main/java/com/shilapi/xcertplay/web/SigningCa.kt new file mode 100644 index 00000000..f7a02957 --- /dev/null +++ b/common/src/main/java/com/shilapi/xcertplay/web/SigningCa.kt @@ -0,0 +1,121 @@ +package com.shilapi.xcertplay.web + +import com.shilapi.xcertplay.host.R +import com.shilapi.xcertplay.i18n.UiText +import com.shilapi.xcertplay.i18n.requireUi +import java.math.BigInteger +import java.security.KeyPairGenerator +import java.security.KeyStore +import java.security.PrivateKey +import java.security.SecureRandom +import java.security.Signature +import java.security.cert.X509Certificate +import java.util.Date +import org.bouncycastle.asn1.x500.X500Name +import org.bouncycastle.asn1.x509.BasicConstraints +import org.bouncycastle.asn1.x509.ExtendedKeyUsage +import org.bouncycastle.asn1.x509.Extension +import org.bouncycastle.asn1.x509.GeneralName +import org.bouncycastle.asn1.x509.GeneralNames +import org.bouncycastle.asn1.x509.KeyPurposeId +import org.bouncycastle.asn1.x509.KeyUsage +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter +import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder +import org.bouncycastle.jce.provider.BouncyCastleProvider +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder + +/** Supplied signing material only; no vendor keys, trust-store edits, or network interception. */ +internal object SigningCa { + private val provider = BouncyCastleProvider() + + private fun algorithm(key: PrivateKey) = when (key.algorithm.uppercase()) { + "RSA" -> "SHA256withRSA" + "EC", "ECDSA" -> "SHA384withECDSA" + else -> throw IllegalArgumentException("Unsupported CA key algorithm: ${key.algorithm}") + } + + fun validate(key: PrivateKey, chain: List) { + requireUi(chain.isNotEmpty()) { UiText(R.string.settings_ca_chain_required) } + chain.forEachIndexed { index, certificate -> + certificate.checkValidity() + requireUi(certificate.basicConstraints >= index) { + UiText(R.string.settings_ca_constraints_invalid) + } + requireUi(certificate.keyUsage?.let { it.getOrNull(5) == true } != false) { + UiText(R.string.settings_ca_constraints_invalid) + } + requireUi(certificate.extendedKeyUsage?.let { + "1.3.6.1.5.5.7.3.1" in it || "2.5.29.37.0" in it + } != false) { UiText(R.string.settings_ca_server_use_required) } + if (index < chain.lastIndex) { + val issuer = chain[index + 1] + requireUi(certificate.issuerX500Principal == issuer.subjectX500Principal) { + UiText(R.string.settings_ca_chain_order) + } + certificate.verify(issuer.publicKey, provider) + } + } + val probe = ByteArray(32).also(SecureRandom()::nextBytes) + val signature = Signature.getInstance(algorithm(key), provider).run { + initSign(key) + update(probe) + sign() + } + val matches = Signature.getInstance(algorithm(key), provider).run { + // Key matching is independent of digitalSignature usage: CA keys can be + // restricted to keyCertSign, which was checked above. + initVerify(chain.first().publicKey) + update(probe) + verify(signature) + } + requireUi(matches) { UiText(R.string.settings_ca_key_mismatch) } + } + + fun issue( + key: PrivateKey, + chain: List, + addresses: List, + hostname: String, + ): KeyStore { + validate(key, chain) + val now = System.currentTimeMillis() + val notBefore = maxOf(now - 300_000, chain.maxOf { it.notBefore.time }) + val notAfter = minOf(now + 7 * 86_400_000L, chain.minOf { it.notAfter.time }) + val keys = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair() + val issuer = chain.first() + val builder = JcaX509v3CertificateBuilder( + X500Name.getInstance(issuer.subjectX500Principal.encoded), + BigInteger(159, SecureRandom()).add(BigInteger.ONE), + Date(notBefore), + Date(notAfter), + X500Name("CN=WheelPlay LAN"), + keys.public, + ) + builder.addExtension(Extension.basicConstraints, true, BasicConstraints(false)) + builder.addExtension(Extension.keyUsage, true, + KeyUsage(KeyUsage.digitalSignature or KeyUsage.keyEncipherment)) + builder.addExtension(Extension.extendedKeyUsage, false, + ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)) + val names = (addresses + "127.0.0.1" + "::1").distinct().map { + GeneralName(GeneralName.iPAddress, it) + } + GeneralName(GeneralName.dNSName, "localhost") + listOfNotNull( + hostname.takeIf { it.isNotEmpty() }?.let { GeneralName(GeneralName.dNSName, it) } + ) + builder.addExtension(Extension.subjectAlternativeName, false, GeneralNames(names.toTypedArray())) + val extensions = JcaX509ExtensionUtils() + // This overload copies the issuer's actual SKI, including non-SHA1 identifiers. + builder.addExtension(Extension.authorityKeyIdentifier, false, + extensions.createAuthorityKeyIdentifier(issuer)) + builder.addExtension(Extension.subjectKeyIdentifier, false, + extensions.createSubjectKeyIdentifier(keys.public)) + val leaf = JcaX509CertificateConverter().setProvider(provider).getCertificate( + builder.build(JcaContentSignerBuilder(algorithm(key)).setProvider(provider).build(key)) + ) + leaf.verify(issuer.publicKey, provider) + return KeyStore.getInstance("PKCS12").apply { + load(null, CharArray(0)) + setKeyEntry("server", keys.private, CharArray(0), (listOf(leaf) + chain).toTypedArray()) + } + } +} diff --git a/common/src/main/java/com/shilapi/xcertplay/web/WebListenSettings.kt b/common/src/main/java/com/shilapi/xcertplay/web/WebListenSettings.kt index 53d0c212..5d1f6665 100644 --- a/common/src/main/java/com/shilapi/xcertplay/web/WebListenSettings.kt +++ b/common/src/main/java/com/shilapi/xcertplay/web/WebListenSettings.kt @@ -18,6 +18,8 @@ internal object WebListenSettings { DEFAULT(UiR.string.ui_default_local_certificate), PEM(UiR.string.host_pem), PKCS12(UiR.string.host_pkcs_12), + EMUDHRA_CA(R.string.settings_emudhra_ca), + BUNDLED_CA(R.string.settings_bundled_ca), } @Synchronized @@ -80,6 +82,19 @@ internal object WebListenSettings { fun httpsEnabled(context: Context) = preferences(context).getBoolean("https_enabled", true) + // A provisioned build opts in on first use; an explicit choice of the local CA stays local. + fun bundledCaEnabled(context: Context): Boolean { + val prefs = preferences(context) + return prefs.getBoolean("bundled_ca_enabled", + prefs.getString("certificate_type", null) != "DEFAULT" && LanTls.hasBundledCa(context)) + } + + fun saveBundledCaEnabled(context: Context, enabled: Boolean) { + check(preferences(context).edit().putBoolean("bundled_ca_enabled", enabled).commit()) { + context.getString(R.string.settings_bundled_ca_save_failed) + } + } + fun hostname(context: Context) = preferences(context) .getString("hostname", "") @@ -106,7 +121,8 @@ internal object WebListenSettings { preferences(context) .getString( "certificate_type", - if (LanTls.hasCustom(context)) "PEM" else "DEFAULT", + if (LanTls.hasCustom(context)) "PEM" + else if (LanTls.usesBundledCa(context)) "BUNDLED_CA" else "DEFAULT", )!! ) } diff --git a/common/src/main/java/com/shilapi/xcertplay/web/WebSession.kt b/common/src/main/java/com/shilapi/xcertplay/web/WebSession.kt index 49eab91b..4d6cfa4c 100644 --- a/common/src/main/java/com/shilapi/xcertplay/web/WebSession.kt +++ b/common/src/main/java/com/shilapi/xcertplay/web/WebSession.kt @@ -497,6 +497,24 @@ internal object WebSession { LanTls.saveCustom(context, prepared) } + /** Snapshot the current SANs and install the signer through the existing rollback path. */ + @Synchronized + fun installSigningCa( + context: Context, + certificates: ByteArray, + privateKey: ByteArray, + password: CharArray = CharArray(0), + ): String? { + val config = TeslaHttpCompatibility.config(context) + return LanTls.prepareSigningCaPem( + certificates, + privateKey, + password, + (addresses(context).map { it.address } + config.accessAddress).distinct(), + WebListenSettings.hostname(context), + ).use { installCertificate(context, it) } + } + @Synchronized fun setHttpsEnabled(context: Context, enabled: Boolean): String? = runCatching { @@ -558,6 +576,7 @@ internal object WebSession { WebListenSettings.hostname(context), ) replaceHttps(context, WebListenSettings.httpsPort(context), endpoint) { + WebListenSettings.saveBundledCaEnabled(context, false) LanTls.clearCustom(context) } } @@ -568,6 +587,18 @@ internal object WebSession { ) } + fun useBundledCertificate(context: Context): String? = + runCatching { + val config = TeslaHttpCompatibility.config(context) + val endpoint = LanTls.createBundled(context, + (addresses(context).map { it.address } + config.accessAddress).distinct(), + WebListenSettings.hostname(context)) + replaceHttps(context, WebListenSettings.httpsPort(context), endpoint) { + WebListenSettings.saveBundledCaEnabled(context, true) + LanTls.clearCustom(context) + } + }.getOrElse { it.userMessage(context) } + private fun createTls(context: Context): LanTls.Endpoint { val config = TeslaHttpCompatibility.config(context) return LanTls.create( @@ -654,7 +685,7 @@ internal object WebSession { if ( server == null || !WebListenSettings.httpsEnabled(context) || - LanTls.hasCustom(context) + !LanTls.generatesCertificates(context) ) return serverGeneration @@ -668,7 +699,7 @@ internal object WebSession { if ( serverGeneration != generation || server == null || - LanTls.hasCustom(context) || + !LanTls.generatesCertificates(context) || TeslaHttpCompatibility.config(context) != config || WebListenSettings.hostname(context) != hostname || !WebListenSettings.httpsEnabled(context) diff --git a/common/src/main/java/moe/feng/wheelplay/WheelPlayActivity.kt b/common/src/main/java/moe/feng/wheelplay/WheelPlayActivity.kt index 72470b6a..fab3e364 100644 --- a/common/src/main/java/moe/feng/wheelplay/WheelPlayActivity.kt +++ b/common/src/main/java/moe/feng/wheelplay/WheelPlayActivity.kt @@ -85,6 +85,7 @@ class WheelPlayActivity : AppCompatActivity() { } } private var pendingPemCertificate: ByteArray? = null + private var importingSigningCa = false private val pemCertificatePicker = registerForActivityResult(CertificateDocument()) { uri -> if (uri != null) { webBusy = true @@ -101,6 +102,8 @@ class WheelPlayActivity : AppCompatActivity() { } private val pemKeyPicker = registerForActivityResult(CertificateDocument()) { uri -> val certificate = pendingPemCertificate + val signingCa = importingSigningCa + importingSigningCa = false pendingPemCertificate = null if (uri == null || certificate == null) certificate?.fill(0) else textInput(getString(UiR.string.ui_pem_private_key_password_leave_blank_if_unencrypted), "", true, onCancel = { certificate.fill(0) }) { value -> @@ -108,7 +111,10 @@ class WheelPlayActivity : AppCompatActivity() { configureWeb(getString(UiR.string.ui_https_certificate_imported_reconnect_your_browser)) { try { val key = readCertificateFile(uri) - try { LanTls.preparePem(certificate, key, password).use { WebSession.installCertificate(this, it) } } + try { + if (signingCa) WebSession.installSigningCa(this, certificate, key, password) + else LanTls.preparePem(certificate, key, password).use { WebSession.installCertificate(this, it) } + } finally { key.fill(0) } } finally { certificate.fill(0); password.fill('\u0000') } } @@ -610,7 +616,10 @@ class WheelPlayActivity : AppCompatActivity() { SettingsCommand.SELECT_ICON -> oemImagePicker.launch("image/*") SettingsCommand.IMPORT_APK -> if (canImportAuthentication()) launchAuthenticationPicker { selectAuthenticationApk.launch(arrayOf("*/*")) } SettingsCommand.IMPORT_FILES -> if (canImportAuthentication()) launchAuthenticationPicker { selectAuthenticationKey.launch(arrayOf("*/*")) } - SettingsCommand.SELECT_PEM -> pemCertificatePicker.launch(arrayOf("*/*")) + SettingsCommand.SELECT_PEM, SettingsCommand.SELECT_SIGNING_CA -> { + importingSigningCa = command == SettingsCommand.SELECT_SIGNING_CA + pemCertificatePicker.launch(arrayOf("*/*")) + } SettingsCommand.SELECT_PKCS12 -> pkcs12Picker.launch(arrayOf("*/*")) SettingsCommand.APP_PERMISSIONS -> openSystem(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))) SettingsCommand.BLUETOOTH_SETTINGS -> openSystem(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)) diff --git a/common/src/main/java/moe/feng/wheelplay/settings/SettingsState.kt b/common/src/main/java/moe/feng/wheelplay/settings/SettingsState.kt index 18540644..f6ea5904 100644 --- a/common/src/main/java/moe/feng/wheelplay/settings/SettingsState.kt +++ b/common/src/main/java/moe/feng/wheelplay/settings/SettingsState.kt @@ -78,6 +78,7 @@ internal enum class SettingsCommand { IMPORT_FILES, SELECT_PEM, SELECT_PKCS12, + SELECT_SIGNING_CA, APP_PERMISSIONS, BLUETOOTH_SETTINGS, WIRELESS_HELP, @@ -110,6 +111,9 @@ internal data class SettingsState( val certificateType: WebListenSettings.CertificateType = WebListenSettings.CertificateType.DEFAULT, val customCertificate: Boolean = false, + val signingCa: Boolean = false, + val bundledCaAvailable: Boolean = false, + val bundledCertificate: Boolean = false, val navigationAvailable: Boolean = false, val tesla: TeslaHttpConfig = TeslaHttpConfig(), val browsers: List = emptyList(), diff --git a/common/src/main/java/moe/feng/wheelplay/settings/SettingsViewModel.kt b/common/src/main/java/moe/feng/wheelplay/settings/SettingsViewModel.kt index 1e3b7e4d..8b7b5499 100644 --- a/common/src/main/java/moe/feng/wheelplay/settings/SettingsViewModel.kt +++ b/common/src/main/java/moe/feng/wheelplay/settings/SettingsViewModel.kt @@ -151,6 +151,9 @@ internal class SettingsViewModel( mdnsHostname = WebListenSettings.mdnsHostname(app), certificateType = WebListenSettings.certificateType(app), customCertificate = LanTls.hasCustom(app), + signingCa = runCatching { LanTls.hasSigningCa(app) }.getOrDefault(false), + bundledCaAvailable = LanTls.hasBundledCa(app), + bundledCertificate = LanTls.usesBundledCa(app), navigationAvailable = BydOutputSettings.available(app), tesla = TeslaHttpCompatibility.config(app), browsers = WebSession.rememberedBrowsers(app).list(), @@ -250,6 +253,12 @@ internal class SettingsViewModel( if (it == null) WebListenSettings.saveCertificateType(app, type) } } + else if (type == WebListenSettings.CertificateType.BUNDLED_CA) + SettingsEffect.WebUpdate(app.getString(R.string.settings_bundled_ca_applied)) { + WebSession.useBundledCertificate(app).also { + if (it == null) WebListenSettings.saveCertificateType(app, type) + } + } else { WebListenSettings.saveCertificateType(app, type) SettingsEffect.None diff --git a/common/src/main/java/moe/feng/wheelplay/settings/WebSettingsScreen.kt b/common/src/main/java/moe/feng/wheelplay/settings/WebSettingsScreen.kt index 1f578e65..ba9757d0 100644 --- a/common/src/main/java/moe/feng/wheelplay/settings/WebSettingsScreen.kt +++ b/common/src/main/java/moe/feng/wheelplay/settings/WebSettingsScreen.kt @@ -63,7 +63,9 @@ internal fun WebSettingsScreen(state: SettingsState, actions: SettingsActions) { settingsString(R.string.settings_certificate_type), style = MaterialTheme.typography.titleMedium, ) - WebListenSettings.CertificateType.entries.forEach { type -> + WebListenSettings.CertificateType.entries.filter { + it != WebListenSettings.CertificateType.BUNDLED_CA || state.bundledCaAvailable + }.forEach { type -> Row( Modifier.fillMaxWidth() .testTag("certificate:${type.name}") @@ -83,6 +85,8 @@ internal fun WebSettingsScreen(state: SettingsState, actions: SettingsActions) { } when (state.certificateType) { WebListenSettings.CertificateType.DEFAULT -> Unit + WebListenSettings.CertificateType.BUNDLED_CA -> + SettingsDescription(R.string.settings_bundled_ca_description) WebListenSettings.CertificateType.PEM -> SettingsButton(R.string.settings_select_pem, enabled) { actions.command(SettingsCommand.SELECT_PEM) @@ -91,9 +95,17 @@ internal fun WebSettingsScreen(state: SettingsState, actions: SettingsActions) { SettingsButton(R.string.settings_select_pkcs12, enabled) { actions.command(SettingsCommand.SELECT_PKCS12) } + WebListenSettings.CertificateType.EMUDHRA_CA -> { + SettingsButton(R.string.settings_select_signing_ca, enabled) { + actions.command(SettingsCommand.SELECT_SIGNING_CA) + } + SettingsDescription(R.string.settings_signing_ca_description) + } } SettingsDescription( - if (state.customCertificate) R.string.settings_certificate_custom + if (state.bundledCertificate) R.string.settings_certificate_bundled_ca + else if (state.signingCa) R.string.settings_certificate_signing_ca + else if (state.customCertificate) R.string.settings_certificate_custom else R.string.settings_certificate_default ) SettingsDescription(R.string.settings_certificate_description) diff --git a/common/src/main/res/values-zh-rCN/settings_strings.xml b/common/src/main/res/values-zh-rCN/settings_strings.xml index 9b654f83..497ce5e2 100644 --- a/common/src/main/res/values-zh-rCN/settings_strings.xml +++ b/common/src/main/res/values-zh-rCN/settings_strings.xml @@ -125,11 +125,25 @@ 启用 HTTPS 为浏览器提供 HTTPS 访问;浏览器麦克风需要可信证书。 证书类型 + eMudhra CA 签发(手动导入) + 内置 eMudhra CA + 使用编译时内置的 CA 私钥和证书链,按当前 IP 与 Web 域名签发服务器证书。 + 当前使用内置 CA 动态签发 + 已应用内置 CA,请重新连接浏览器 + 无法保存内置 CA 设置 + 选择 CA 证书链与私钥 + 依次选择签发 CA 及其上级证书链、PEM 私钥。WheelPlay 按当前 IP 与 Web 域名签发服务器证书。 + 当前使用导入的 CA 动态签发 + 需要提供签发 CA 证书链 + 各级签发者必须是具有证书签发权限且路径长度足够的 CA + CA 证书链不允许签发 TLS 服务器证书 + 证书链须从签发 CA 到上级依次排列,只提供一条证书路径 + 签发 CA 证书与私钥不匹配 选择 PEM 证书与私钥 选择 PKCS#12 文件 当前使用自定义证书 当前使用默认本地证书 - 证书和私钥保存在 App 私有存储。PEM 依次选择证书链、私钥;PKCS#12 可选择私钥条目。 + 导入的证书和私钥保存在 App 私有存储。PEM 依次选择证书链、私钥;PKCS#12 可选择私钥条目。 连接方案 主要用于帮助屏蔽私有网段访问的车机绕过地址限制,访问手机上的本地服务。除 Tesla 外,有同类限制的其他品牌车机也可尝试。 启用免 Root Tesla 兼容 diff --git a/common/src/main/res/values-zh-rTW/settings_strings.xml b/common/src/main/res/values-zh-rTW/settings_strings.xml index 98df8295..38cbf6c0 100644 --- a/common/src/main/res/values-zh-rTW/settings_strings.xml +++ b/common/src/main/res/values-zh-rTW/settings_strings.xml @@ -125,11 +125,25 @@ 啟用 HTTPS 為瀏覽器提供 HTTPS 存取;瀏覽器麥克風需要可信憑證。 憑證型別 + eMudhra CA 簽發(手動匯入) + 內建 eMudhra CA + 使用編譯時內建的 CA 私密金鑰和憑證鏈,按目前 IP 與 Web 網域簽發伺服器憑證。 + 目前使用內建 CA 動態簽發 + 已套用內建 CA,請重新連線瀏覽器 + 無法儲存內建 CA 設定 + 選擇 CA 憑證鏈與私密金鑰 + 依次選擇簽發 CA 及其上級憑證鏈、PEM 私密金鑰。WheelPlay 按目前 IP 與 Web 網域簽發伺服器憑證。 + 目前使用匯入的 CA 動態簽發 + 需要提供簽發 CA 憑證鏈 + 各級簽發者必須是具有憑證簽發權限且路徑長度足夠的 CA + CA 憑證鏈不允許簽發 TLS 伺服器憑證 + 憑證鏈須從簽發 CA 到上級依次排列,只提供一條憑證路徑 + 簽發 CA 憑證與私密金鑰不匹配 選擇 PEM 憑證與私密金鑰 選擇 PKCS#12 檔案 目前使用自定義憑證 目前使用預設本機憑證 - 憑證和私密金鑰儲存在 App 私有儲存。PEM 依次選擇憑證鏈、私密金鑰;PKCS#12 可選擇私密金鑰條目。 + 匯入的憑證和私密金鑰儲存在 App 私有儲存。PEM 依次選擇憑證鏈、私密金鑰;PKCS#12 可選擇私密金鑰條目。 連線方案 主要用於幫助遮蔽私有網段存取的車機繞過地址限制,存取手機上的本機服務。除 Tesla 外,有同類限制的其他品牌車機也可嘗試。 啟用免 Root Tesla 相容 diff --git a/common/src/main/res/values/settings_strings.xml b/common/src/main/res/values/settings_strings.xml index d654875f..f3e987f5 100644 --- a/common/src/main/res/values/settings_strings.xml +++ b/common/src/main/res/values/settings_strings.xml @@ -125,11 +125,25 @@ Enable HTTPS Provide HTTPS access for browsers. Browser microphones require a trusted certificate. Certificate type + eMudhra CA signing (manual import) + Built-in eMudhra CA + Use the CA key and certificate chain included when this app was built. Server certificates follow the current IP addresses and Web hostname. + Using the built-in signing CA + Built-in CA applied; reconnect your browser + Could not save the built-in CA setting + Choose CA chain & private key + Select the signing CA and its ordered issuer chain, then its PEM private key. WheelPlay signs a server certificate for the current IP addresses and Web hostname. + Using an imported signing CA + A signing CA certificate chain is required + Every issuer must be a CA with certificate signing permission and sufficient path length + The CA chain does not permit TLS server certificates + Order the chain from the signing CA to its issuers; supply one certificate path + The signing CA certificate and private key do not match Choose PEM certificate & private key Choose PKCS#12 file Using a custom certificate Using the default local certificate - Certificates and keys are stored privately in the app. For PEM, select the certificate chain, then the private key. PKCS#12 supports selecting a private-key entry. + Imported certificates and keys are stored privately in the app. For PEM, select the certificate chain, then the private key. PKCS#12 supports selecting a private-key entry. Connection method Helps head units that block private IP ranges access this phone\'s local service. Head units from other manufacturers with similar restrictions may also work. Enable rootless Tesla compatibility diff --git a/common/src/test/java/com/shilapi/xcertplay/web/SigningCaTest.kt b/common/src/test/java/com/shilapi/xcertplay/web/SigningCaTest.kt new file mode 100644 index 00000000..00e2edc4 --- /dev/null +++ b/common/src/test/java/com/shilapi/xcertplay/web/SigningCaTest.kt @@ -0,0 +1,399 @@ +package com.shilapi.xcertplay.web + +import moe.feng.wheelplay.MfiAssetStore +import moe.feng.wheelplay.SyntheticMfiIdentity +import java.io.StringWriter +import java.io.File +import java.math.BigInteger +import java.net.URL +import java.security.KeyPair +import java.security.KeyPairGenerator +import java.security.KeyStore +import java.security.cert.X509Certificate +import java.security.spec.ECGenParameterSpec +import java.util.Date +import java.util.concurrent.CompletableFuture +import java.util.concurrent.TimeUnit +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream +import javax.net.ssl.SSLContext +import javax.net.ssl.HttpsURLConnection +import javax.net.ssl.SSLServerSocket +import javax.net.ssl.SSLSocket +import javax.net.ssl.TrustManagerFactory +import org.bouncycastle.asn1.x500.X500Name +import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier +import org.bouncycastle.asn1.x509.BasicConstraints +import org.bouncycastle.asn1.x509.ExtendedKeyUsage +import org.bouncycastle.asn1.x509.Extension +import org.bouncycastle.asn1.x509.KeyPurposeId +import org.bouncycastle.asn1.x509.KeyUsage +import org.bouncycastle.asn1.x509.SubjectKeyIdentifier +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter +import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder +import org.bouncycastle.jce.provider.BouncyCastleProvider +import org.bouncycastle.openssl.PKCS8Generator +import org.bouncycastle.openssl.jcajce.JcaPEMWriter +import org.bouncycastle.openssl.jcajce.JcaPKCS8Generator +import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8EncryptorBuilder +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [29], qualifiers = "zh-rCN") +class SigningCaTest { + private val bc = BouncyCastleProvider() + private val context get() = RuntimeEnvironment.getApplication() + private data class Authority(val key: KeyPair, val chain: List) + + private fun keys(algorithm: String) = KeyPairGenerator.getInstance(algorithm, bc).apply { + if (algorithm == "EC") initialize(ECGenParameterSpec("secp384r1")) else initialize(2048) + }.generateKeyPair() + + private fun certificate( + name: String, + issuer: String, + subjectKey: KeyPair, + signer: KeyPair, + ca: Boolean = true, + pathLength: Int = 2, + keyUsage: Int = KeyUsage.keyCertSign or KeyUsage.cRLSign, + eku: KeyPurposeId = KeyPurposeId.id_kp_serverAuth, + expires: Long = System.currentTimeMillis() + 3 * 86_400_000L, + ): X509Certificate { + val builder = JcaX509v3CertificateBuilder( + X500Name("CN=$issuer"), BigInteger(128, java.security.SecureRandom()), + Date(System.currentTimeMillis() - 60_000), Date(expires), + X500Name("CN=$name"), subjectKey.public, + ) + builder.addExtension(Extension.basicConstraints, true, + if (ca) BasicConstraints(pathLength) else BasicConstraints(false)) + builder.addExtension(Extension.keyUsage, true, KeyUsage(keyUsage)) + builder.addExtension(Extension.extendedKeyUsage, false, ExtendedKeyUsage(eku)) + // A deliberately nonstandard SKI catches accidental SHA1 recomputation in AKI. + builder.addExtension(Extension.subjectKeyIdentifier, false, + SubjectKeyIdentifier(ByteArray(16) { (it + name.length).toByte() })) + return JcaX509CertificateConverter().setProvider(bc).getCertificate(builder.build( + JcaContentSignerBuilder(if (signer.private.algorithm == "RSA") "SHA256withRSA" else "SHA384withECDSA") + .setProvider(bc).build(signer.private) + )) + } + + private fun authority(algorithm: String = "EC"): Authority { + val root = keys(algorithm) + val signer = keys(algorithm) + return Authority(signer, listOf( + certificate("Signer", "Root", signer, root, pathLength = 0), + certificate("Root", "Root", root, root), + )) + } + + private fun pem(vararg values: Any) = StringWriter().also { output -> + JcaPEMWriter(output).use { writer -> values.forEach(writer::writeObject) } + }.toString().toByteArray() + + private fun prepare(authority: Authority, hostname: String = "car.example.com") = + LanTls.prepareSigningCaPem(pem(*authority.chain.toTypedArray()), pem(authority.key.private), + addresses = listOf("127.0.0.1", "6.6.6.6"), hostname = hostname) + + private fun bundle(authority: Authority) = pem(authority.key.private, *authority.chain.toTypedArray()) + + private fun addBundledAsset(bytes: ByteArray) { + val apk = File(context.cacheDir, "test-https-ca.apk") + ZipOutputStream(apk.outputStream()).use { zip -> + zip.putNextEntry(ZipEntry("assets/${LanTls.BUNDLED_CA_ASSET}")) + zip.write(bytes) + zip.closeEntry() + } + val cookie = ReflectionHelpers.callInstanceMethod(context.assets, "addAssetPath", + ReflectionHelpers.ClassParameter.from(String::class.java, apk.absolutePath)) + assertTrue(cookie > 0) + } + + private fun client(root: X509Certificate): SSLContext { + val trust = KeyStore.getInstance(KeyStore.getDefaultType()).apply { + load(null) + setCertificateEntry("root", root) + } + val managers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { init(trust) } + return SSLContext.getInstance("TLS").apply { init(null, managers.trustManagers, null) } + } + + private fun httpsGet(root: X509Certificate): String { + val connection = URL("https://127.0.0.1:${WebSession.httpsPort}/").openConnection() as HttpsURLConnection + connection.sslSocketFactory = client(root).socketFactory + connection.connectTimeout = 5000 + connection.readTimeout = 5000 + return try { connection.inputStream.use { it.reader().readText() } } + finally { connection.disconnect() } + } + + /** Validates the peer with a root-only trust store and HTTPS hostname checks enabled. */ + private fun handshake(endpoint: LanTls.Endpoint, root: X509Certificate): List { + return (endpoint.sockets.createServerSocket(0) as SSLServerSocket).use { listener -> + listener.soTimeout = 5000 + val server = CompletableFuture.runAsync { + (listener.accept() as SSLSocket).use { socket -> + socket.soTimeout = 5000 + socket.startHandshake() + socket.outputStream.write(42) + } + } + val chain = (client(root).socketFactory.createSocket("127.0.0.1", listener.localPort) as SSLSocket).use { socket -> + socket.soTimeout = 5000 + socket.sslParameters = socket.sslParameters.apply { endpointIdentificationAlgorithm = "HTTPS" } + socket.startHandshake() + assertEquals(42, socket.inputStream.read()) + socket.session.peerCertificates.map { it as X509Certificate } + } + server.get(6, TimeUnit.SECONDS) + chain + } + } + + @Test fun rsaAndEcSignersServeTrustedChainsWithIndependentLeafKeysAndMatchingAki() { + for (algorithm in listOf("RSA", "EC")) { + val authority = authority(algorithm) + prepare(authority).use { prepared -> + val endpoint = prepared.endpoint + assertTrue(endpoint.custom) + assertTrue(endpoint.signingCa) + val chain = handshake(endpoint, authority.chain.last()) + val leaf = chain.first() + leaf.verify(authority.key.public, bc) + assertEquals(-1, leaf.basicConstraints) + assertFalse(leaf.publicKey.encoded.contentEquals(authority.key.public.encoded)) + assertEquals(3, chain.size) + assertTrue(leaf.extendedKeyUsage.contains("1.3.6.1.5.5.7.3.1")) + val sans = leaf.subjectAlternativeNames.map { it[1].toString() } + assertTrue(sans.containsAll(listOf("127.0.0.1", "6.6.6.6", "car.example.com", "localhost"))) + assertTrue(authority.chain.all { leaf.notAfter <= it.notAfter && leaf.notBefore >= it.notBefore }) + val ski = SubjectKeyIdentifier.fromExtensions(JcaX509CertificateHolder(authority.chain.first()).extensions) + val aki = AuthorityKeyIdentifier.fromExtensions(JcaX509CertificateHolder(leaf).extensions) + assertArrayEquals(ski.keyIdentifier, aki.keyIdentifier) + } + } + } + + @Test fun encryptedEcSignerPersistsAndNewAddressesAreSignedAfterReload() { + val authority = authority() + val password = "fixture-only".toCharArray() + val encrypted = pem(JcaPKCS8Generator(authority.key.private, + JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.AES_256_CBC) + .setProvider(bc).setPassword(password).build())) + LanTls.prepareSigningCaPem(pem(*authority.chain.toTypedArray()), encrypted, password, + listOf("127.0.0.1"), "old.example.com").use { prepared -> + LanTls.saveCustom(context, prepared) + } + assertTrue(LanTls.hasSigningCa(context)) + assertTrue(LanTls.generatesCertificates(context)) + val restored = LanTls.create(context, listOf("192.168.43.1"), "new.example.com") + val leaf = handshake(restored, authority.chain.last()).first() + val sans = leaf.subjectAlternativeNames.map { it[1].toString() } + assertTrue(sans.containsAll(listOf("192.168.43.1", "new.example.com"))) + assertFalse("old.example.com" in sans) + assertTrue(restored.signingCa) + LanTls.clearCustom(context) + assertFalse(LanTls.hasSigningCa(context)) + assertFalse(LanTls.create(context, emptyList()).signingCa) + } + + @Test fun wrongKeyWrongOrderAndBadSignaturesLeaveInstalledSignerUntouched() { + val authority = authority() + prepare(authority).use { LanTls.saveCustom(context, it) } + val fingerprint = LanTls.create(context, emptyList()).fingerprint + val other = keys("EC") + for (invalid in listOf( + Authority(other, authority.chain), + Authority(authority.key, authority.chain.reversed()), + Authority(authority.key, listOf(authority.chain.first(), + certificate("Root", "Root", other, other))), + )) { + assertTrue(runCatching { prepare(invalid).use {} }.isFailure) + } + assertEquals(fingerprint, LanTls.create(context, emptyList()).fingerprint) + handshake(LanTls.create(context, emptyList()), authority.chain.last()) + } + + @Test fun rejectsLeafCertificatesMissingSigningPermissionRestrictedEkuAndExpiredCa() { + val key = keys("EC") + val invalid = listOf( + certificate("CA", "CA", key, key, ca = false), + certificate("CA", "CA", key, key, keyUsage = KeyUsage.digitalSignature), + certificate("CA", "CA", key, key, eku = KeyPurposeId.id_kp_clientAuth), + certificate("CA", "CA", key, key, expires = System.currentTimeMillis() - 30_000), + ) + invalid.forEach { cert -> + assertTrue(runCatching { prepare(Authority(key, listOf(cert))).use {} }.isFailure) + } + assertFalse(LanTls.hasCustom(context)) + } + + @Test fun rejectsIssuerWithInsufficientPathLength() { + val root = keys("EC") + val signer = keys("EC") + val chain = listOf( + certificate("Signer", "Root", signer, root, pathLength = 0), + certificate("Root", "Root", root, root, pathLength = 0), + ) + assertTrue(runCatching { prepare(Authority(signer, chain)).use {} }.isFailure) + } + + @Test fun signingCaIsSeparateFromExistingServerPemImport() { + val authority = authority() + assertTrue(runCatching { + LanTls.preparePem(pem(*authority.chain.toTypedArray()), pem(authority.key.private)).use {} + }.isFailure) + } + + @Test fun bundledCaAutomaticallySignsWithoutImportAndExplicitLocalChoiceSurvivesRestart() { + val authority = authority() + addBundledAsset(bundle(authority)) + assertTrue(LanTls.hasBundledCa(context)) + assertFalse(LanTls.hasCustom(context)) + assertEquals(WebListenSettings.CertificateType.BUNDLED_CA, WebListenSettings.certificateType(context)) + val first = LanTls.create(context, listOf("127.0.0.1")) + assertTrue(first.bundledCa) + assertTrue(first.signingCa) + handshake(first, authority.chain.last()) + // Selecting a manual-import form without importing must not change the active source. + WebListenSettings.saveCertificateType(context, WebListenSettings.CertificateType.EMUDHRA_CA) + assertTrue(LanTls.create(context, emptyList()).bundledCa) + assertNull(WebSession.restoreDefaultCertificate(context)) + assertFalse(LanTls.create(context, emptyList()).bundledCa) + assertFalse(WebListenSettings.bundledCaEnabled(context)) + assertNull(WebSession.useBundledCertificate(context)) + assertTrue(LanTls.create(context, emptyList()).bundledCa) + assertFalse(LanTls.hasCustom(context)) + } + + @Test fun manualIdentityOverridesBundledCaUntilTheBuiltInSourceIsSelectedAgain() { + val bundled = authority() + val manual = authority() + addBundledAsset(bundle(bundled)) + prepare(manual).use { LanTls.saveCustom(context, it) } + val overridden = LanTls.create(context, emptyList()) + assertFalse(overridden.bundledCa) + handshake(overridden, manual.chain.last()) + assertNull(WebSession.useBundledCertificate(context)) + assertFalse(LanTls.hasCustom(context)) + handshake(LanTls.create(context, emptyList()), bundled.chain.last()) + } + + @Test fun invalidBundledMaterialFailsWithoutReplacingAnExplicitLocalIdentity() { + addBundledAsset("invalid PEM".toByteArray()) + assertTrue(runCatching { LanTls.create(context, emptyList()) }.isFailure) + assertNull(WebSession.restoreDefaultCertificate(context)) + assertFalse(LanTls.create(context, emptyList()).bundledCa) + assertNotNull(WebSession.useBundledCertificate(context)) + assertFalse(LanTls.usesBundledCa(context)) + assertFalse(LanTls.create(context, emptyList()).bundledCa) + } + + @Test fun combinedPemRejectsMissingCertificatesMissingOrMultipleKeysAndBadKeyPairs() { + val authority = authority() + val other = authority() + for (bytes in listOf( + pem(*authority.chain.toTypedArray()), + pem(authority.key.private), + bundle(authority) + pem(authority.key.private), + pem(other.key.private, *authority.chain.toTypedArray()), + )) { + assertTrue(runCatching { LanTls.prepareSigningCaBundle(bytes, emptyList()).use {} }.isFailure) + } + } + + @Test fun explicitlySelectedMissingBundleDoesNotSilentlyGenerateALocalCa() { + assertFalse(LanTls.hasBundledCa(context)) + WebListenSettings.saveBundledCaEnabled(context, true) + assertTrue(runCatching { LanTls.create(context, emptyList()) }.isFailure) + assertNull(WebSession.restoreDefaultCertificate(context)) + assertFalse(LanTls.create(context, emptyList()).bundledCa) + } + + @Test fun bundledHttpsSupportsRequestsRefreshAndSwitchingSourcesWithoutImport() { + val authority = authority() + addBundledAsset(bundle(authority)) + val mfi = SyntheticMfiIdentity.create() + MfiAssetStore(context.noBackupFilesDir).installFiles( + { mfi.key.inputStream() }, { mfi.certificate.inputStream() }) + WebSession.start(context) + try { + waitFor { WebSession.httpsReady } + val code = WebSession.code + assertTrue(WebSession.tls!!.bundledCa) + assertTrue(httpsGet(authority.chain.last()).contains("WheelPlay")) + val previous = WebSession.tls + assertNull(WebSession.setHostname(context, "bundled.example.com")) + waitFor { WebSession.tls !== previous } + assertTrue(WebSession.tls!!.bundledCa) + val sans = handshake(WebSession.tls!!, authority.chain.last()).first().subjectAlternativeNames + assertTrue(sans.any { it[1] == "bundled.example.com" }) + val info = JSONObject(URL("http://127.0.0.1:${WebSession.httpPort}/tls.json").readText()) + assertTrue(info.getBoolean("bundledCa")) + assertNull(WebSession.restoreDefaultCertificate(context)) + assertFalse(WebSession.tls!!.bundledCa) + assertNull(WebSession.useBundledCertificate(context)) + assertTrue(WebSession.tls!!.bundledCa) + assertEquals(code, WebSession.code) + assertFalse(LanTls.hasCustom(context)) + assertTrue(httpsGet(authority.chain.last()).contains("WheelPlay")) + } finally { WebSession.stop() } + } + + private fun waitFor(predicate: () -> Boolean) { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (!predicate() && System.nanoTime() < deadline) Thread.sleep(20) + assertTrue("HTTPS update timed out: ${WebSession.tlsError}", predicate()) + } + + @Test fun webServiceRefreshRestartDisableAndRestoreKeepPairingAndHttpAvailable() { + val mfi = SyntheticMfiIdentity.create() + MfiAssetStore(context.noBackupFilesDir).installFiles( + { mfi.key.inputStream() }, { mfi.certificate.inputStream() }) + val authority = authority() + WebSession.start(context) + try { + waitFor { WebSession.httpsReady } + val code = WebSession.code + assertNull(WebSession.installSigningCa(context, + pem(*authority.chain.toTypedArray()), pem(authority.key.private))) + assertTrue(WebSession.tls!!.signingCa) + assertTrue(httpsGet(authority.chain.last()).contains("WheelPlay")) + val fingerprint = WebSession.tls!!.fingerprint + assertEquals(code, WebSession.code) + assertNull(WebSession.setHostname(context, "changed.example.com")) + waitFor { + WebSession.tls?.let { endpoint -> + handshake(endpoint, authority.chain.last()).first().subjectAlternativeNames + .any { it[1] == "changed.example.com" } + } == true + } + assertEquals(fingerprint, WebSession.tls!!.fingerprint) + assertTrue(httpsGet(authority.chain.last()).contains("WheelPlay")) + val info = JSONObject(URL("http://127.0.0.1:${WebSession.httpPort}/tls.json").readText()) + assertTrue(info.getBoolean("signingCa")) + assertNull(WebSession.setHttpsEnabled(context, false)) + assertTrue(LanTls.hasSigningCa(context)) + assertTrue(URL("http://127.0.0.1:${WebSession.httpPort}/").readText().contains("WheelPlay")) + WebSession.stop() + WebSession.start(context) + assertFalse(WebSession.httpsReady) + assertNull(WebSession.setHttpsEnabled(context, true)) + assertTrue(WebSession.tls!!.signingCa) + assertEquals(fingerprint, WebSession.tls!!.fingerprint) + handshake(WebSession.tls!!, authority.chain.last()) + assertNull(WebSession.restoreDefaultCertificate(context)) + assertFalse(LanTls.hasCustom(context)) + assertFalse(WebSession.tls!!.signingCa) + } finally { WebSession.stop() } + } +} diff --git a/common/src/test/java/moe/feng/wheelplay/HttpsSettingsUiTest.kt b/common/src/test/java/moe/feng/wheelplay/HttpsSettingsUiTest.kt index 098e8481..652fe4f1 100644 --- a/common/src/test/java/moe/feng/wheelplay/HttpsSettingsUiTest.kt +++ b/common/src/test/java/moe/feng/wheelplay/HttpsSettingsUiTest.kt @@ -179,7 +179,8 @@ class HttpsSettingsUiTest : ComposeSettingsTest() { try { val activity = controller.get() SettingsNavigation.open(activity, "Web 服务", compose) - for ((type, title) in listOf("PEM" to "选择 PEM 证书与私钥", "PKCS12" to "选择 PKCS#12 文件")) { + for ((type, title) in listOf("PEM" to "选择 PEM 证书与私钥", "PKCS12" to "选择 PKCS#12 文件", + "EMUDHRA_CA" to "选择 CA 证书链与私钥")) { clickTag("certificate:$type") compose.onNodeWithText(title).performScrollTo().performClick() val intent = shadowOf(activity).nextStartedActivity diff --git a/docs/HTTPS_SIGNING_CA.md b/docs/HTTPS_SIGNING_CA.md new file mode 100644 index 00000000..94b62573 --- /dev/null +++ b/docs/HTTPS_SIGNING_CA.md @@ -0,0 +1,146 @@ +# eMudhra CA 的 HTTPS 签发框架 + +此功能沿用 mitmproxy 的“加载签发 CA → 签发服务器证书 → 配置 TLS 证书链”流程,接入 WheelPlay 自己的 HTTPS 服务。支持编译时内置和运行时手动导入,不按客户端版本选择证书。仓库不附带实际 CA 材料。 + +## 编译时内置 + +与 mitmproxy 的 `EMUDHRA_CHAIN_PEM` 采用相同的组合格式:一个未加密的 RSA / EC CA 私钥,后面是签发 CA 及其有序上级证书链。文件总大小不超过 2 MiB。 + +```text +-----BEGIN PRIVATE KEY----- +签发 CA 私钥 +-----END PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +与私钥匹配的签发 CA +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +上级 CA(可继续追加同一路径中的上级) +-----END CERTIFICATE----- +``` + +将文件放到已被 Git 忽略的 `.local/https-ca/emudhra-ca.pem`,正常构建即可: + +```bash +./gradlew :mobile:assembleDebug +``` + +也可以指定文件位置(相对路径以仓库根目录为基准): + +```bash +WHEELPLAY_HTTPS_CA_PEM=/absolute/path/to/emudhra-ca.pem \ + ./gradlew :mobile:assembleDebug +``` + +同一配置也适用于 Release 构建,Release 签名仍按项目原有配置提供。Gradle 的 `bundleHttpsCa` 任务只复制指定 PEM 到生成的 `assets/web-tls/emudhra-ca.pem`,不会打包源目录中的其他文件;未配置时不会内置 CA。显式指定的文件缺失、为空、超限或没有一个未加密私钥和证书时构建失败。密钥匹配、CA 权限和证书链签名在运行时通过共用的 CA 验证器检查。 + +首次启动且没有自定义身份或明确的本地证书选择时,会自动使用内置 CA,无需打开文件选择器。设置中显示「内置 eMudhra CA」,选中后可切换回内置来源。内置材料每次从当前 APK 加载,不复制为手动导入的持久身份,因此更新 APK 中的 CA 后,重启 Web 服务即可使用新材料。 + +来源优先级:手动导入的身份优先;否则使用已启用的内置 CA;最后是默认本地 CA。明确选择默认本地证书后保持该选择,重启不会重新启用内置 CA。选择手动导入表单但未导入文件,不会替换正在使用的身份。已选中的内置材料无效或在更新后缺失时报告 HTTPS 启动错误,不悄悄替换成另一张 CA。 + +移除环境变量及默认路径下的 PEM 后再次构建,任务会清理旧的生成文件,避免旧 CA 留在 APK 中。运行时手动导入的身份保留在应用私有存储,移除构建材料不会删除它。 + +内置私钥会随 APK 分发且可被提取;这种方式应只用于你决定随该构建一起分发的 CA 材料。构建日志不输出 PEM 内容,仓库也不保存该私钥。 + +### 在 GitHub Actions 中内置 + +CI 读不到本机的 `.local/https-ca/`,因此用仓库 Secret 提供同一份组合 PEM。 + +1. 添加 Repository Secret `WHEELPLAY_HTTPS_CA_PEM_BASE64`,值为组合 PEM 的 Base64: + + ```powershell + Set-Clipboard ([Convert]::ToBase64String([IO.File]::ReadAllBytes('.local/https-ca/emudhra-ca.pem'))) + ``` + + 粘贴后清空剪贴板。Base64 只是编码,不是加密,安全性由 GitHub Secrets 提供;不要把值写进 YAML、Variables、日志或 Issue。 + +2. 运行 **Android Release Build**(或在 `main`/标签上推送 `v*`)。构建步骤把 Secret 解码到 `$RUNNER_TEMP/wheelplay-https-ca.*/emudhra-ca.pem`,用 `WHEELPLAY_HTTPS_CA_PEM` 指向它,步骤结束(含失败)时与签名密钥库一起删除;随后用 `unzip -p` 确认 APK 内 `assets/web-tls/emudhra-ca.pem` 存在。 + +3. 默认 `WHEELPLAY_HTTPS_CA_REQUIRED=1`:Release 必须内置 CA。Secret 优先;没有 Secret 时按下一节的回退取值;两者都没有才失败。 + +`.github/scripts/provision-https-ca.sh` 在 Gradle 启动前重复 `BundleHttpsCa` 的检查(恰好一份未加密 RSA/EC 私钥、至少一张证书、无 `ENCRYPTED`、不超过 2 MiB),Secret 写错会在工具链安装后立刻报错,而不是等到签名阶段。Debug 工作流用同一套默认值:独立步骤 provision 后把路径写进 `GITHUB_ENV`,构建结束再删除;PR 运行读不到 Secret,会走下一节的回退,只有推送 `main`/标签时才使用签名密钥。 + +### 缺 Secret 时的默认回退 + +Release 工作流默认 `WHEELPLAY_HTTPS_CA_FALLBACK=mitmproxy`:没有 Secret 时,构建会从固定 commit `82416906e3ac55b88d215500adf40959e237589d` 读取 `mitmproxy/certs.py` 中的 `EMUDHRA_CHAIN_PEM`,写入 `$RUNNER_TEMP/wheelplay-https-ca.*/emudhra-ca.pem`,随后走同一套 `BundleHttpsCa` 流程。这也让 `WHEELPLAY_HTTPS_CA_REQUIRED=1` 在两种来源下都能满足。 + +该私钥来自 mitmproxy 的公开源码,属于公开材料:用它签出的证书可以被任何人复现,因此这条路径只适合 CI 冒烟,正式分发请配置 Secret(或用下面的命令生成一把自有 CA 放进去)。使用回退时日志会说明来源,artifact 名字带 `-MITMPROXY-CA` 后缀。 + +两个变量都可以用 Repository Variables 覆盖:`WHEELPLAY_HTTPS_CA_FALLBACK` 设为其他值(如 `none`)即关闭回退,此时没有 Secret 会按 `WHEELPLAY_HTTPS_CA_REQUIRED` 决定失败还是跳过;把 `WHEELPLAY_HTTPS_CA_REQUIRED` 设为 `0` 则允许没有内置 CA 的包。 + +要一把固定的自有 CA,可以先生成再放进 Secret: + +```bash +mkdir -p .local/https-ca +openssl req -x509 -newkey rsa:3072 -sha256 -days 3650 -nodes \ + -keyout .local/https-ca/ca-key.pem -out .local/https-ca/ca-cert.pem \ + -subj '/CN=WheelPlay HTTPS CA/O=WheelPlay' \ + -addext 'basicConstraints=critical,CA:TRUE' \ + -addext 'keyUsage=critical,keyCertSign,cRLSign' \ + -addext 'extendedKeyUsage=serverAuth' +cat .local/https-ca/ca-key.pem .local/https-ca/ca-cert.pem > .local/https-ca/emudhra-ca.pem +``` + +## 手动导入 + +1. 在「设置 → Web 服务」打开 HTTPS,选择「eMudhra CA 签发(手动导入)」。此时只切换导入表单,现有证书保持使用。 +2. 点击「选择 CA 证书链与私钥」,先选择 PEM 证书链,再选择与第一张 CA 证书匹配的 PEM 私钥;加密私钥在随后弹出的输入框填写口令。 +3. 导入成功后 HTTPS 使用新签发的服务器证书。域名与 Tesla 兼容访问地址改变时会重新签发;App 重启时从已保存的 CA 重新生成服务器密钥和证书。 +4. 选择「默认本地证书」会删除已导入的身份并恢复本地 CA。导入 PEM / PKCS#12 服务器证书也会替换当前签发身份。关闭 HTTPS 保留已导入的身份,重新开启后继续使用。 + +需要的是**可签发服务器证书的 CA 及其匹配私钥**。普通 eMudhra SSL 服务器证书仍从原有 PEM / PKCS#12 入口导入。 + +证书链文件按签发顺序排列: + +```text +-----BEGIN CERTIFICATE----- +签发 CA(与私钥匹配) +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +上级 CA +-----END CERTIFICATE----- +…… +``` + +每次提供一条有序路径;如存在交叉签名,手动选择所需路径,不把相同签发者的多个替代证书追加到同一文件。最后的根证书可省略,由客户端自身的信任库补全。 + +私钥支持 RSA、EC,含传统 PEM、PKCS#8、对应加密格式,以及传统 EC 私钥前的 EC PARAMETERS。证书链与私钥文件各限制为 2 MiB。文件选择和口令输入复用现有的临时导入流程。 + +## 签发与持久化 + +- CA 导入检查有效期、密钥匹配、CA 约束、keyCertSign(存在 Key Usage 时)、路径长度、服务器用途限制,以及相邻证书的名称和签名。 +- 服务器使用独立的 RSA 2048 位密钥,CA 的 RSA / EC 私钥只用于签名。叶证书包含 `CA:FALSE`、TLS serverAuth、数字签名与密钥加密用途,以及随机序列号。 +- SAN 包含当前局域网 IP、Tesla 兼容访问 IP、`127.0.0.1`、`::1`、`localhost` 和配置的 Web 域名。填写域名不会自动配置 DNS。 +- AKI 复制签发 CA 的实际 SKI,兼容非 SHA-1 SKI。证书链从叶证书开始发送。 +- 叶证书有效期最多七天,且不超出所提供 CA 链的有效区间;在导入、地址/域名刷新及服务重启时重新签发。当前框架没有后台定时续期,持续运行超过有效期前需重启 Web 服务。 +- 手动导入的 CA 身份以 PKCS#12 的 `signer` 条目保存到应用私有 `noBackupFilesDir/browser-server-custom.p12`。原有服务器证书使用 `server` 条目,旧文件无需迁移。此运行时文件包含私钥,不作为构建输入或提交仓库;编译内置来源直接使用 APK 中配置的 PEM。 +- 保存复用 `AtomicFile`,监听更新复用 `WebSession.replaceHttps` 的失败回滚;解析或签发失败不覆盖已有身份。HTTPS 更新不更换当前 HTTP 配对码。 +- `/tls.json` 的 `signingCa` 表示使用提供的 CA 签发,`bundledCa` 进一步表示当前监听使用 APK 内置来源;`/certificate.crt` 仍只导出链尾的公开证书。 + +客户端仍执行正常的证书链、域名、有效期、用途、策略与吊销校验。此功能不修改客户端信任库,也不保证手动提供的证书会受车机信任。CA 导入检查不替代客户端完整的 PKIX 验证。 + +## 代码入口与验证 + +- `common/.../web/SigningCa.kt`:CA 验证、叶证书生成、AKI/SKI 和证书链。 +- `common/.../web/LanTls.kt`:共用 PEM 解析、私有存储、CA/服务器身份识别和 SSLContext。 +- `mobile/build.gradle.kts`:本地 PEM 构建输入、生成 assets 和显式打包范围。 +- `common/.../web/WebSession.kt`:导入应用、地址变化刷新和监听回滚。 +- `common/.../settings/WebSettingsScreen.kt`、`WheelPlayActivity.kt`:手动选择证书链、私钥与口令。 + +使用测试生成的 CA 运行: + +```bash +./gradlew :common:testDebugUnitTest \ + --tests '*SigningCaTest' \ + --tests '*LanTlsTest' \ + --tests '*LanTlsEcTest' \ + --tests '*HttpsSettingsUiTest' \ + --tests '*WebListenSettingsTest' +``` + +测试包含 RSA / EC 根 CA 与中间 CA、真实 TLS 握手与主机名校验、独立服务器密钥、非标准 SKI、有效期限制、加密 PEM、重载与 SAN 刷新、非法材料不覆盖原身份,以及 Web 服务启停和恢复默认身份。 + +2026-11-12 验证:上述四个套件共 28 项测试通过(新增 CA 7 项、原有 TLS 13 项、设置界面 8 项);三种语言资源目录一致性、`:mobile:assembleDebug` 与 `git diff --check` 通过。Debug APK 位于 `mobile/build/outputs/apk/debug/mobile-debug.apk`。测试运行库使用环境的本地缓存,未修改仓库工具链配置。未导入真实 eMudhra 材料,也未在车机上实测。 + +编译内置扩展验证:五个套件共 41 项测试通过,包含新增的六项组合 PEM、真实 AssetManager 读取、自动启用、手动身份优先、明确切换来源、无效材料失败与 HTTPS 请求/刷新测试。使用临时生成的 CA 构建 Debug APK,直接检查 ZIP 中 PEM 与输入逐字节一致,且没有打包源目录中的无关文件;取消配置后再次构建,确认生成目录与 APK 都已移除旧 PEM。两次正常配置缓存构建均通过,当前 Debug APK 未内置测试 CA。测试未使用真实 eMudhra 材料。 + +参考:[mitmproxy 证书机制](https://docs.mitmproxy.org/stable/concepts/certificates/)、[证书实现](https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/certs.py)、[TLS 配置实现](https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/addons/tlsconfig.py)。本框架的 CA 来自 Secret 或本地 PEM;没有配置时回退到 mitmproxy 公开源码中的组合 PEM(公开材料,仅适合冒烟),不实现替代路径自动选择或吊销请求拦截逻辑。 diff --git a/docs/README.md b/docs/README.md index de5fdefb..0e64ddd5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,6 +15,7 @@ - [WebRTC 稳定性与卡顿恢复](WEBRTC_RECOVERY.md):回退原因、可配置容忍时间及真机排查方法。 - [认证资源导入](AUTHENTICATION_IMPORT.md):手动选择资源、从用户下载的 DiPlay APK 提取及本地存储。 - [Tesla HTTP 兼容模式](TESLA_HTTP.md):无证书虚拟地址入口、可选域名和实机验证限制。 +- [eMudhra CA 的 HTTPS 签发框架](HTTPS_SIGNING_CA.md):编译内置、CA 证书链与私钥导入、按访问地址签发及 HTTPS 监听更新。 - [验证记录](VALIDATION.md):已通过的检查、APK 校验值和未完成的真机验证。 - [组件间距检查](SPACING_REVIEW.md):本轮发现、尺寸约定、修正和验证范围。 - [上游来源](UPSTREAM.md):原版提交及本分支改动范围。 diff --git a/docs/RELEASE_SIGNING.md b/docs/RELEASE_SIGNING.md index fdfe5a24..90d2a0d5 100644 --- a/docs/RELEASE_SIGNING.md +++ b/docs/RELEASE_SIGNING.md @@ -44,9 +44,28 @@ Base64 只是二进制到文本的编码,**不是加密**。安全存储由 Gi 提供。不要把 Base64 值放入 YAML、Variables、日志、Issue 或聊天。 公开证书 `.pem` 和本地加载脚本无需上传;本地路径也无需配置为 Secret。 +## 可选的 HTTPS 签发 CA Secret + +编译内置的 HTTPS 签发 CA 与 keystore 分开,使用另一个 Secret: + +| Secret 名称 | 值 | +| --- | --- | +| `WHEELPLAY_HTTPS_CA_PEM_BASE64` | `.local/https-ca/emudhra-ca.pem`(组合 PEM)的 Base64 内容 | + +```powershell +Set-Clipboard ([Convert]::ToBase64String([IO.File]::ReadAllBytes('.local/https-ca/emudhra-ca.pem'))) +``` + +未设置时 Release 仍会内置 CA:默认 `WHEELPLAY_HTTPS_CA_FALLBACK=mitmproxy`,从固定 commit 读取 +mitmproxy 公开源码中的组合 PEM,并给 artifact 加 `-MITMPROXY-CA` 后缀。该私钥是公开材料, +签出的证书可以被复现,只适合冒烟;正式分发请配置上面的 Secret 或按 +[HTTPS_SIGNING_CA.md](HTTPS_SIGNING_CA.md) 生成自有 CA。把 `WHEELPLAY_HTTPS_CA_FALLBACK` +设为其他值可关闭回退,此时 `WHEELPLAY_HTTPS_CA_REQUIRED`(默认 `1`)决定缺 Secret 时失败还是跳过。 +Android Debug Build 工作流使用同一组默认值,因此 PR 与分支构建的 Debug APK 也会内置 CA。 + ## 触发构建 -先配置上述四个 Secrets,再提交并推送 workflow 和构建配置变更。 +先配置上述四个签名 Secrets(以及可选的 CA Secret),再提交并推送 workflow 和构建配置变更。 - **Android Debug Build**:推送到 `main`、推送标签或在 `main`/标签上手动运行时, 使用 Secrets 中的密钥。PR 和其他分支的手动运行使用默认 Debug 密钥。 diff --git a/docs/TESLA_HTTP.md b/docs/TESLA_HTTP.md index 7fb1276a..a5972636 100644 --- a/docs/TESLA_HTTP.md +++ b/docs/TESLA_HTTP.md @@ -72,3 +72,5 @@ 5. 拒绝/撤销 Root,确认失败时不展示共享地址、不反复弹授权;恢复权限后手动重试。 在「设置 → Web 服务」打开「启用 HTTPS」后,可修改 Web HTTPS 端口及证书;关闭后停止 HTTPS 监听并撤下 HTTPS 映射,HTTP 继续可用。默认本地证书包含配置的共享 IP 与可选域名,修改地址后会刷新。导入自定义证书时需由证书本身覆盖实际访问的 IP/域名。详见 [BROWSER_AUDIO.md](BROWSER_AUDIO.md)。 + +如需提供 eMudhra CA 并按访问 IP / 域名签发服务器证书,可编译时内置,也可使用「eMudhra CA 签发(手动导入)」入口,见 [HTTPS_SIGNING_CA.md](HTTPS_SIGNING_CA.md)。 diff --git a/mobile/build.gradle.kts b/mobile/build.gradle.kts index 10e2bd56..bb4979bb 100644 --- a/mobile/build.gradle.kts +++ b/mobile/build.gradle.kts @@ -1,4 +1,5 @@ import java.util.zip.ZipFile +import org.gradle.work.DisableCachingByDefault plugins { alias(libs.plugins.android.application) @@ -11,6 +12,53 @@ val localAuthenticationAssets = providers.environmentVariable("WHEELPLAY_AUTH_AS .orNull?.let { file(it).canonicalFile } ?: rootProject.file(".local/auth-assets").takeIf { it.exists() }?.canonicalFile +// mitmproxy-style combined PEM: one unencrypted CA key, then an ordered certificate path. +// Only this explicit file is copied; the containing directory is never added to assets. +val localHttpsCa = providers.environmentVariable("WHEELPLAY_HTTPS_CA_PEM") + .orNull?.let { rootProject.file(it).canonicalFile } + ?: rootProject.file(".local/https-ca/emudhra-ca.pem").takeIf { it.exists() }?.canonicalFile + +@DisableCachingByDefault(because = "Contains locally provisioned CA private key material") +abstract class BundleHttpsCa : DefaultTask() { + @get:InputFile @get:Optional @get:PathSensitive(PathSensitivity.NONE) + abstract val sourcePem: RegularFileProperty + + @get:OutputDirectory + abstract val outputDirectory: DirectoryProperty + + @TaskAction + fun bundle() { + val destination = outputDirectory.get().asFile + check(!destination.exists() || destination.deleteRecursively()) { + "Could not clear generated HTTPS CA assets" + } + destination.mkdirs() + val source = sourcePem.orNull?.asFile ?: return + check(source.length() in 1..(2 * 1024 * 1024).toLong()) { + "HTTPS CA PEM must be nonempty and at most 2 MiB" + } + val bytes = source.readBytes() + try { + val text = bytes.toString(Charsets.UTF_8) + check(Regex("-----BEGIN (?:RSA |EC )?PRIVATE KEY-----").findAll(text).count() == 1 && + "-----BEGIN CERTIFICATE-----" in text && "ENCRYPTED" !in text) { + "HTTPS CA PEM must contain one unencrypted RSA/EC private key and a CA certificate chain" + } + destination.resolve("web-tls/emudhra-ca.pem").apply { + parentFile.mkdirs() + writeBytes(bytes) + } + } finally { bytes.fill(0) } + } +} + +val bundleHttpsCa by tasks.registering(BundleHttpsCa::class) { + group = "build" + description = "Bundle an optional locally provisioned HTTPS signing CA." + localHttpsCa?.let { sourcePem.set(it) } + outputDirectory.set(layout.buildDirectory.dir("generated/https-ca/assets")) +} + android { namespace = "com.shilapi.xcertplay" compileSdk { @@ -66,6 +114,10 @@ android { } } +androidComponents.onVariants { variant -> + variant.sources.assets?.addGeneratedSourceDirectory(bundleHttpsCa, BundleHttpsCa::outputDirectory) +} + dependencies { androidTestImplementation(project(":projection-plugin-api")) androidTestImplementation("androidx.test:runner:1.6.2") @@ -83,7 +135,7 @@ dependencies { debugImplementation(libs.androidx.compose.ui.tooling) } -// Only the two provisioned local runtime assets are allowed. +// Only explicitly provisioned authentication assets and the generated HTTPS CA are allowed. val credentialAssets = files(android.sourceSets.flatMap { source -> source.assets.directories.map { directory -> fileTree(directory) { @@ -91,17 +143,21 @@ val credentialAssets = files(android.sourceSets.flatMap { source -> "**/*.pem", "**/*.p12", "**/*.pfx", "**/*.jks", "**/*.keystore") } } -}) +}, bundleHttpsCa.map { it.outputDirectory.asFileTree }) val rejectBundledCredentials by tasks.registering { group = "verification" description = "Reject unexpected credential files in APK assets." val filesToCheck = credentialAssets - val allowed = localAuthenticationAssets?.let { dir -> + val allowedAuthentication = localAuthenticationAssets?.let { dir -> listOf("identity.pk8", "certificate.p7b").map { dir.resolve("offline-mfi/$it").canonicalFile }.toSet() } ?: emptySet() + val allowed = allowedAuthentication + if (localHttpsCa != null) setOf( + bundleHttpsCa.get().outputDirectory.get().asFile.resolve("web-tls/emudhra-ca.pem").canonicalFile + ) else emptySet() + dependsOn(bundleHttpsCa) inputs.files(filesToCheck) doLast { - check(allowed.all { it.isFile }) { "Explicit local authentication assets are incomplete" } + check(allowed.all { it.isFile }) { "Explicit local runtime assets are incomplete" } val unexpected = filesToCheck.files.filter { it.canonicalFile !in allowed } check(unexpected.isEmpty()) { "Unexpected credential files in APK assets" } } diff --git a/test/ci-https-ca.test.js b/test/ci-https-ca.test.js new file mode 100644 index 00000000..febbac72 --- /dev/null +++ b/test/ci-https-ca.test.js @@ -0,0 +1,349 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, statSync, rmSync, existsSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawnSync } from 'node:child_process'; + +const provision = fileURLToPath(new URL('../.github/scripts/provision-https-ca.sh', import.meta.url)); +const provisionEnv = fileURLToPath(new URL('../.github/scripts/provision-https-ca-env.sh', import.meta.url)); +const buildScript = fileURLToPath(new URL('../.github/scripts/build-signed-android.sh', import.meta.url)); + +const keyPem = `-----BEGIN PRIVATE KEY----- +MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDAAAAAAAAAAAAAAAAAA +-----END PRIVATE KEY----- +`; +const certPem = (commonName) => `-----BEGIN CERTIFICATE----- +MIIB${Buffer.from(commonName).toString('base64')} +-----END CERTIFICATE----- +`; +const combinedPem = keyPem + certPem('ca') + certPem('root'); +const encode = value => Buffer.from(value).toString('base64'); + +// The pinned mitmproxy extraction is a plain awk slice between a marker line +// and the next bare `"""`, so a synthetic source exercises the same path. +const certsPy = keepMarker => `DEFAULT_DHPARAM = b""" +-----BEGIN DH PARAMETERS----- +MIIB +-----END DH PARAMETERS----- +""" + +# CA kept for revocation tests. +${keepMarker ? 'EMUDHRA_CHAIN_PEM' : 'SOMETHING_ELSE'} = b""" +${combinedPem}""" +`; + +function tempDir(t, prefix) { + const directory = mkdtempSync(join(tmpdir(), prefix)); + t.after(() => rmSync(directory, { recursive: true, force: true })); + return directory; +} + +// A private directory per test keeps parallel runs from sharing fixtures. +function workspace(t) { + const output = join(tempDir(t, 'https ca '), 'out'); + mkdirSync(output); + return { output }; +} + +function curlStub(t, { fixture = certsPy(true), fail = false } = {}) { + const root = tempDir(t, 'https ca curl '); + const bin = join(root, 'bin'); + mkdirSync(bin); + const fixturePath = join(root, 'certs.py'); + writeFileSync(fixturePath, fixture); + writeFileSync(join(bin, 'curl'), `#!/usr/bin/env bash +set -euo pipefail +out='' +while [[ $# -gt 0 ]]; do + case $1 in + --output) out=$2; shift 2;; + --max-time|--max-filesize) shift 2;; + --*) shift;; + *) printf '%s\\n' "$1" >> "$CURL_LOG"; shift;; + esac +done +[[ "\${CURL_FAIL:-0}" == 1 ]] && { echo 'curl: (22) The requested URL returned error: 404' >&2; exit 22; } +cat "$CURL_FIXTURE" > "$out" +`, { mode: 0o755 }); + return { bin, log: join(root, 'curl.log'), fixturePath, fail }; +} + +function provisionCa(t, { secret = '', required = '', fallback = '', fixture, curlFails = false } = {}) { + const stub = curlStub(t, { fixture, fail: curlFails }); + const { output } = workspace(t); + const result = spawnSync('bash', [provision, '--output-dir', output], { + encoding: 'utf8', + env: { + ...process.env, + PATH: `${stub.bin}:${process.env.PATH}`, + CURL_LOG: stub.log, + CURL_FIXTURE: stub.fixturePath, + CURL_FAIL: curlFails ? '1' : '0', + WHEELPLAY_HTTPS_CA_PEM_BASE64: secret, + WHEELPLAY_HTTPS_CA_REQUIRED: required, + WHEELPLAY_HTTPS_CA_FALLBACK: fallback, + }, + }); + return { ...result, output, stub }; +} + +function signedBuild(t, { caSecret = '', fallback = '', fixture, curlFails = false, existingCaPath = '' } = {}) { + const root = tempDir(t, 'https ca build '); + const stub = curlStub(t, { fixture, fail: curlFails }); + const checkout = join(root, 'checkout'); + const runnerTemp = join(root, 'runner-temp'); + mkdirSync(checkout); + mkdirSync(runnerTemp); + const log = join(root, 'gradle.log'); + writeFileSync(join(checkout, 'gradlew'), `#!/usr/bin/env bash +set -euo pipefail +printf 'ca=%s\\n' "\${WHEELPLAY_HTTPS_CA_PEM:-}" > "$CALL_LOG" +if [[ -n \${WHEELPLAY_HTTPS_CA_PEM:-} ]]; then + printf 'ca-head=%s\\n' "$(head -n 1 "$WHEELPLAY_HTTPS_CA_PEM")" >> "$CALL_LOG" + printf 'ca-mode=%s\\n' "$(stat -c '%a' "$WHEELPLAY_HTTPS_CA_PEM")" >> "$CALL_LOG" +fi +printf 'keystore=%s\\n' "$ANDROID_KEYSTORE_PATH" >> "$CALL_LOG" +printf 'keystore-head=%s\\n' "$(head -c 13 "$ANDROID_KEYSTORE_PATH")" >> "$CALL_LOG" +printf 'args=%s\\n' "$*" >> "$CALL_LOG" +`, { mode: 0o755 }); + + const result = spawnSync('bash', [buildScript, ':mobile:assembleRelease', ':mobile:bundleRelease'], { + cwd: checkout, + encoding: 'utf8', + env: { + ...process.env, + PATH: `${stub.bin}:${process.env.PATH}`, + RUNNER_TEMP: runnerTemp, + CALL_LOG: log, + CURL_LOG: stub.log, + CURL_FIXTURE: stub.fixturePath, + CURL_FAIL: curlFails ? '1' : '0', + ANDROID_KEYSTORE_BASE64: encode('fake keystore'), + ANDROID_KEYSTORE_PASSWORD: 'store password', + ANDROID_KEY_ALIAS: 'wheelplay-release', + ANDROID_KEY_PASSWORD: 'key password', + WHEELPLAY_HTTPS_CA_PEM_BASE64: caSecret, + WHEELPLAY_HTTPS_CA_PEM: existingCaPath, + WHEELPLAY_HTTPS_CA_FALLBACK: fallback, + }, + }); + const fields = () => Object.fromEntries(readFileSync(log, 'utf8').trimEnd().split('\n') + .map(line => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)])); + return { ...result, checkout, runnerTemp, fields, stub }; +} + +// Mirrors the Debug workflow: provision once, export only the path, keep the file. +function provisionCaEnv(t, { secret = '', required = '', fallback = '', fixture, curlFails = false } = {}) { + const stub = curlStub(t, { fixture, fail: curlFails }); + const root = tempDir(t, 'https ca env '); + const runnerTemp = join(root, 'runner-temp'); + mkdirSync(runnerTemp); + const githubEnv = join(root, 'github-env'); + writeFileSync(githubEnv, ''); + const result = spawnSync('bash', [provisionEnv], { + encoding: 'utf8', + env: { + ...process.env, + PATH: `${stub.bin}:${process.env.PATH}`, + RUNNER_TEMP: runnerTemp, + GITHUB_ENV: githubEnv, + CURL_LOG: stub.log, + CURL_FIXTURE: stub.fixturePath, + CURL_FAIL: curlFails ? '1' : '0', + WHEELPLAY_HTTPS_CA_PEM_BASE64: secret, + WHEELPLAY_HTTPS_CA_REQUIRED: required, + WHEELPLAY_HTTPS_CA_FALLBACK: fallback, + }, + }); + return { ...result, runnerTemp, githubEnv, stub }; +} + +test('an absent secret is a silent no-op and never reaches the network', t => { + const r = provisionCa(t); + assert.equal(r.status, 0, r.stderr); + assert.equal(r.stdout, ''); + assert.deepEqual(readdirSync(r.output), []); + assert.equal(existsSync(r.stub.log), false); +}); + +test('a required CA that is absent fails the step', t => { + const r = provisionCa(t, { required: '1' }); + assert.equal(r.status, 1); + assert.match(r.stderr, /WHEELPLAY_HTTPS_CA_REQUIRED=1 but there is no WHEELPLAY_HTTPS_CA_PEM_BASE64 secret and no mitmproxy fallback/); + assert.deepEqual(readdirSync(r.output), []); + assert.equal(existsSync(r.stub.log), false); +}); + +test('the secret is decoded into an owner-only file and only its path is printed', t => { + const r = provisionCa(t, { secret: encode(combinedPem) }); + assert.equal(r.status, 0, r.stderr); + const pem = r.stdout.trim(); + assert.equal(pem, join(r.output, 'emudhra-ca.pem')); + assert.equal(readFileSync(pem, 'utf8'), combinedPem); + assert.equal(statSync(pem).mode & 0o777, 0o600); + assert.doesNotMatch(r.stderr, /PRIVATE KEY/); +}); + +test('Base64 with line wrapping and surrounding whitespace is accepted', t => { + const wrapped = encode(combinedPem).replace(/(.{64})/g, '$1\n'); + const r = provisionCa(t, { secret: `\n${wrapped}\n` }); + assert.equal(r.status, 0, r.stderr); + assert.equal(readFileSync(r.stdout.trim(), 'utf8'), combinedPem); +}); + +test('a value that is not Base64 fails with an actionable message', t => { + const r = provisionCa(t, { secret: 'not base64 !!!' }); + assert.equal(r.status, 1); + assert.match(r.stderr, /is not valid Base64/); + assert.deepEqual(readdirSync(r.output), []); +}); + +test('encrypted keys, multiple keys and missing certificates are rejected', async t => { + const cases = { + encrypted: keyPem.replace('PRIVATE KEY', 'ENCRYPTED PRIVATE KEY') + certPem('ca'), + 'two keys': keyPem + keyPem + certPem('ca'), + 'no certificate': keyPem, + }; + for (const [name, pem] of Object.entries(cases)) { + await t.test(name, () => { + const r = provisionCa(t, { secret: encode(pem) }); + assert.equal(r.status, 1); + assert.match(r.stderr, /exactly one unencrypted RSA\/EC private key and at least one certificate/); + assert.deepEqual(readdirSync(r.output), []); + }); + } +}); + +test('the 2 MiB bundled limit matches the Gradle task', t => { + // The over-limit branch cannot be reached through this harness: one environment + // string may not exceed the Linux 128 KiB execve limit, so a decoded 2 MiB + // secret cannot be passed. Keep the two constants from drifting instead. + const helper = readFileSync(provision, 'utf8'); + const gradle = readFileSync(new URL('../mobile/build.gradle.kts', import.meta.url), 'utf8'); + assert.match(helper, /max_bytes=\$\(\(2 \* 1024 \* 1024\)\)/); + assert.match(gradle, /source\.length\(\) in 1\.\.\(2 \* 1024 \* 1024\)\.toLong\(\)/); +}); + +test('a whitespace-only secret decodes to an empty file and fails', t => { + const r = provisionCa(t, { secret: ' \n\t' }); + assert.equal(r.status, 1); + assert.match(r.stderr, /from the secret is empty/); + assert.deepEqual(readdirSync(r.output), []); +}); + +test('the mitmproxy fallback stays off unless it is explicitly requested', t => { + const r = provisionCa(t, { fallback: 'yes' }); + assert.equal(r.status, 0, r.stderr); + assert.equal(r.stdout, ''); + assert.equal(existsSync(r.stub.log), false); +}); + +test('the mitmproxy fallback bundles the pinned constant and records its source', t => { + const r = provisionCa(t, { fallback: 'mitmproxy' }); + assert.equal(r.status, 0, r.stderr); + const pem = r.stdout.trim(); + assert.equal(readFileSync(pem, 'utf8'), combinedPem); + assert.equal(statSync(pem).mode & 0o777, 0o600); + assert.match(r.stderr, /public key material, no identity guarantee/); + assert.match(readFileSync(r.stub.log, 'utf8'), /^https:\/\/raw\.githubusercontent\.com\/mhils\/mitmproxy\/82416906e3ac55b88d215500adf40959e237589d\//); + // The downloaded source is removed; only the PEM reaches Gradle. + assert.deepEqual(readdirSync(r.output), ['emudhra-ca.pem']); +}); + +test('the fallback fails when the pinned source no longer has the constant', t => { + const r = provisionCa(t, { fallback: 'mitmproxy', fixture: certsPy(false) }); + assert.equal(r.status, 1); + assert.match(r.stderr, /no longer contains EMUDHRA_CHAIN_PEM = b/); + assert.deepEqual(readdirSync(r.output), []); +}); + +test('the fallback fails when the download fails', t => { + const r = provisionCa(t, { fallback: 'mitmproxy', curlFails: true }); + assert.equal(r.status, 1); + assert.match(r.stderr, /Could not download .*mitmproxy/); + assert.deepEqual(readdirSync(r.output), []); +}); + +test('a required CA is satisfied by the fallback without touching the secret', t => { + const r = provisionCa(t, { required: '1', fallback: 'mitmproxy' }); + assert.equal(r.status, 0, r.stderr); + assert.equal(readFileSync(r.stdout.trim(), 'utf8'), combinedPem); + assert.match(r.stderr, /public key material/); +}); + +test('the signed build exports the temporary CA path and removes every secret file', t => { + const r = signedBuild(t, { caSecret: encode(combinedPem) }); + assert.equal(r.status, 0, r.stderr); + const fields = r.fields(); + + assert.match(fields.ca, new RegExp(`^${r.runnerTemp.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/wheelplay-https-ca\\.`)); + assert.equal(fields['ca-head'], '-----BEGIN PRIVATE KEY-----'); + assert.equal(fields['ca-mode'], '600'); + assert.match(fields.keystore, /wheelplay-signing\.[^/]+\/wheelplay\.jks$/); + assert.equal(fields['keystore-head'], 'fake keystore'); + assert.equal(fields.args, '--no-daemon --no-configuration-cache :mobile:assembleRelease :mobile:bundleRelease'); + // Nothing may survive the step, and nothing may land in the checkout. + assert.deepEqual(readdirSync(r.runnerTemp), []); + assert.deepEqual(readdirSync(r.checkout).sort(), ['gradlew']); +}); + +test('the signed build can bundle the fallback CA', t => { + const r = signedBuild(t, { fallback: 'mitmproxy' }); + assert.equal(r.status, 0, r.stderr); + const fields = r.fields(); + assert.match(fields.ca, /wheelplay-https-ca\.[^/]+\/emudhra-ca\.pem$/); + assert.equal(fields['ca-head'], '-----BEGIN PRIVATE KEY-----'); + assert.match(r.stderr, /public key material/); + assert.deepEqual(readdirSync(r.runnerTemp), []); + assert.deepEqual(readdirSync(r.checkout).sort(), ['gradlew']); +}); + +test('the signed build runs without any CA secret or fallback', t => { + const r = signedBuild(t); + assert.equal(r.status, 0, r.stderr); + assert.equal(r.fields().ca, ''); + assert.deepEqual(readdirSync(r.runnerTemp), []); + assert.equal(existsSync(join(r.checkout, 'wheelplay-https-ca')), false); +}); + +test('the Debug provisioning step exports only the path and keeps the material', t => { + const r = provisionCaEnv(t, { required: '1', fallback: 'mitmproxy' }); + assert.equal(r.status, 0, r.stderr); + const exported = readFileSync(r.githubEnv, 'utf8'); + assert.match(exported, /^WHEELPLAY_HTTPS_CA_PEM=.*wheelplay-https-ca\.[^/]+\/emudhra-ca\.pem\n$/); + const pem = exported.trim().slice('WHEELPLAY_HTTPS_CA_PEM='.length); + // The workflow cleans this up after the artifacts are uploaded. + assert.equal(readFileSync(pem, 'utf8'), combinedPem); + assert.equal(readdirSync(r.runnerTemp).length, 1); + assert.match(r.stderr, /public key material/); +}); + +test('the Debug provisioning step exports nothing when no CA is configured', t => { + const r = provisionCaEnv(t); + assert.equal(r.status, 0, r.stderr); + assert.equal(readFileSync(r.githubEnv, 'utf8'), ''); + assert.deepEqual(readdirSync(r.runnerTemp), []); + assert.equal(existsSync(r.stub.log), false); +}); + +test('the Debug provisioning step fails on a malformed secret and cleans up', t => { + const r = provisionCaEnv(t, { secret: 'not base64 !!!', required: '1' }); + assert.equal(r.status, 1); + assert.match(r.stderr, /is not valid Base64/); + assert.equal(readFileSync(r.githubEnv, 'utf8'), ''); + assert.deepEqual(readdirSync(r.runnerTemp), []); +}); + +test('the signed build reuses a CA that another step already provisioned', t => { + const directory = tempDir(t, 'https ca pre '); + const existing = join(directory, 'provided.pem'); + writeFileSync(existing, combinedPem); + const r = signedBuild(t, { fallback: 'mitmproxy', existingCaPath: existing }); + assert.equal(r.status, 0, r.stderr); + assert.equal(r.fields().ca, existing); + // No second download, and the caller's directory is left untouched. + assert.equal(existsSync(r.stub.log), false); + assert.equal(readFileSync(existing, 'utf8'), combinedPem); +});