From 03cc2a7a2f9ab06e3d6f196b342e39798cf68eb5 Mon Sep 17 00:00:00 2001 From: morhaviv <61060270+morhaviv@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:39:56 +0200 Subject: [PATCH] feat(tls): support app-managed PKCS#12 certificates with basic tests Preserve existing system KeyChain fallback. Add an instrumented import/removal smoke test and clear temporary key material on failures. Assisted-by: ChatGPT:GPT-6 --- .../src/androidTest/assets/client.p12.base64 | 45 ++++ .../assets/client.p12.base64.license | 2 + .../ManualClientCertificateStoreIT.java | 74 ++++++ .../network/AdvancedX509KeyManager.java | 35 ++- .../ManualClientCertificateMaterial.java | 97 ++++++++ .../network/ManualClientCertificateStore.java | 222 ++++++++++++++++++ .../ManualClientCertificateMaterialTest.java | 63 +++++ .../resources/certificates/client.p12.base64 | 45 ++++ .../certificates/client.p12.base64.license | 2 + 9 files changed, 583 insertions(+), 2 deletions(-) create mode 100644 library/src/androidTest/assets/client.p12.base64 create mode 100644 library/src/androidTest/assets/client.p12.base64.license create mode 100644 library/src/androidTest/java/com/owncloud/android/lib/common/network/ManualClientCertificateStoreIT.java create mode 100644 library/src/main/java/com/owncloud/android/lib/common/network/ManualClientCertificateMaterial.java create mode 100644 library/src/main/java/com/owncloud/android/lib/common/network/ManualClientCertificateStore.java create mode 100644 library/src/test/java/com/owncloud/android/lib/common/network/ManualClientCertificateMaterialTest.java create mode 100644 library/src/test/resources/certificates/client.p12.base64 create mode 100644 library/src/test/resources/certificates/client.p12.base64.license diff --git a/library/src/androidTest/assets/client.p12.base64 b/library/src/androidTest/assets/client.p12.base64 new file mode 100644 index 0000000000..8b2fab5678 --- /dev/null +++ b/library/src/androidTest/assets/client.p12.base64 @@ -0,0 +1,45 @@ +MIIJ/wIBAzCCCbUGCSqGSIb3DQEHAaCCCaYEggmiMIIJnjCCBAoGCSqGSIb3DQEHBqCCA/swggP3 +AgEAMIID8AYJKoZIhvcNAQcBMF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBD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MRYEFPf0h+/5GKvzdDOTO1JRakspMoktMEEwMTANBglghkgB +ZQMEAgEFAAQg2pwMd1aow4OZQ9aspu7Su5Q2/6akU/zmg5GM4DVVOewECAfEbwQx1ggsAgIIAA== diff --git a/library/src/androidTest/assets/client.p12.base64.license b/library/src/androidTest/assets/client.p12.base64.license new file mode 100644 index 0000000000..39052814f1 --- /dev/null +++ b/library/src/androidTest/assets/client.p12.base64.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: 2026 Nextcloud contributors +SPDX-License-Identifier: MIT diff --git a/library/src/androidTest/java/com/owncloud/android/lib/common/network/ManualClientCertificateStoreIT.java b/library/src/androidTest/java/com/owncloud/android/lib/common/network/ManualClientCertificateStoreIT.java new file mode 100644 index 0000000000..8b6b605e7f --- /dev/null +++ b/library/src/androidTest/java/com/owncloud/android/lib/common/network/ManualClientCertificateStoreIT.java @@ -0,0 +1,74 @@ +/* + * Nextcloud Android Library + * + * SPDX-FileCopyrightText: 2026 Nextcloud contributors + * SPDX-License-Identifier: MIT + */ +package com.owncloud.android.lib.common.network; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import android.content.Context; +import android.util.Base64; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +/** Small device test for the AndroidKeyStore-backed certificate import. */ +@RunWith(AndroidJUnit4.class) +public class ManualClientCertificateStoreIT { + @Test + public void importedCertificateIsAvailableOnlyToItsServerAndCanBeRemoved() throws Exception { + Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); + String host = "mtls-instrumentation.example"; + String otherHost = "other-instrumentation.example"; + int port = 443; + byte[] encoded; + try (InputStream stream = InstrumentationRegistry.getInstrumentation().getContext() + .getAssets().open("client.p12.base64"); + ByteArrayOutputStream output = new ByteArrayOutputStream()) { + byte[] buffer = new byte[4096]; + int count; + while ((count = stream.read(buffer)) != -1) { + output.write(buffer, 0, count); + } + encoded = output.toByteArray(); + } + byte[] certificate = Base64.decode(new String(encoded, StandardCharsets.US_ASCII), Base64.DEFAULT); + Arrays.fill(encoded, (byte) 0); + char[] password = "for-tests-only".toCharArray(); + + try { + ManualClientCertificateStore.remove(context, host, port); + assertFalse(ManualClientCertificateStore.isConfigured(context, host, port)); + + ManualClientCertificateStore.importCertificate(context, host, port, certificate, password); + + assertTrue(ManualClientCertificateStore.isConfigured(context, host, port)); + String alias = ManualClientCertificateStore.aliasFor(host, port); + assertNotNull(ManualClientCertificateStore.getPrivateKey(context, alias)); + assertEquals(1, ManualClientCertificateStore.getCertificateChain(context, alias).length); + assertFalse(ManualClientCertificateStore.isConfigured(context, otherHost, port)); + assertNull(ManualClientCertificateStore.getPrivateKey(context, + ManualClientCertificateStore.aliasFor(otherHost, port))); + } finally { + Arrays.fill(password, '\0'); + Arrays.fill(certificate, (byte) 0); + ManualClientCertificateStore.remove(context, host, port); + } + + assertFalse(ManualClientCertificateStore.isConfigured(context, host, port)); + } +} diff --git a/library/src/main/java/com/owncloud/android/lib/common/network/AdvancedX509KeyManager.java b/library/src/main/java/com/owncloud/android/lib/common/network/AdvancedX509KeyManager.java index 5df88bd498..cb759adc2b 100644 --- a/library/src/main/java/com/owncloud/android/lib/common/network/AdvancedX509KeyManager.java +++ b/library/src/main/java/com/owncloud/android/lib/common/network/AdvancedX509KeyManager.java @@ -324,10 +324,16 @@ private static LinkedList filterAliases(Collection aliases, AKMAl * @return keychain alias to use for this connection */ private String chooseAlias(String[] keyTypes, Principal[] issuers, @NonNull Socket socket) { - // Determine connection parameters + // Only a TLS peer hostname, never a reverse-DNS result, may select a manual certificate. String hostname = socket.getInetAddress().getHostName(); int port = socket.getPort(); - return chooseAlias(keyTypes, issuers, hostname, port); + if (socket instanceof javax.net.ssl.SSLSocket) { + javax.net.ssl.SSLSession session = ((javax.net.ssl.SSLSocket) socket).getHandshakeSession(); + if (session != null && session.getPeerHost() != null) { + return chooseAlias(keyTypes, issuers, session.getPeerHost(), port); + } + } + return chooseKeyChainAlias(keyTypes, issuers, hostname, port); } /** @@ -339,6 +345,15 @@ private String chooseAlias(String[] keyTypes, Principal[] issuers, @NonNull Sock * @return keychain alias to use for this connection */ private String chooseAlias(String[] keyTypes, Principal[] issuers, @NonNull String hostname, int port) { + // A configured manual identity takes precedence over Android KeyChain. A damaged identity + // deliberately does not fall back to the system certificate picker. + if (ManualClientCertificateStore.isConfigured(context, hostname, port)) { + return ManualClientCertificateStore.aliasFor(hostname, port); + } + return chooseKeyChainAlias(keyTypes, issuers, hostname, port); + } + + private String chooseKeyChainAlias(String[] keyTypes, Principal[] issuers, String hostname, int port) { // Select certificate for one connection at a time. This is important if multiple connections to the same host // are started in a short time and avoids prompting the user with multiple dialogs for the same host. synchronized (AdvancedX509KeyManager.class) { @@ -405,6 +420,14 @@ public String[] getServerAliases(String keyType, Principal[] issuers) { @Override public X509Certificate[] getCertificateChain(@NonNull String alias) { Log_OC.d(TAG, "getCertificateChain(alias=" + alias + ")"); + if (alias.startsWith(ManualClientCertificateStore.ALIAS_PREFIX)) { + try { + return ManualClientCertificateStore.getCertificateChain(context, alias); + } catch (Exception e) { + Log_OC.e(TAG, "Unable to load manual client certificate chain", e); + return null; + } + } AKMAlias akmAlias = new AKMAlias(alias); if (akmAlias.getType() == KEYCHAIN) { try { @@ -430,6 +453,14 @@ public X509Certificate[] getCertificateChain(@NonNull String alias) { @Override public PrivateKey getPrivateKey(@NonNull String alias) { Log_OC.d(TAG, "getPrivateKey(alias=" + alias + ")"); + if (alias.startsWith(ManualClientCertificateStore.ALIAS_PREFIX)) { + try { + return ManualClientCertificateStore.getPrivateKey(context, alias); + } catch (Exception e) { + Log_OC.e(TAG, "Unable to load manual client private key", e); + return null; + } + } AKMAlias akmAlias = new AKMAlias(alias); if (akmAlias.getType() == KEYCHAIN) { try { diff --git a/library/src/main/java/com/owncloud/android/lib/common/network/ManualClientCertificateMaterial.java b/library/src/main/java/com/owncloud/android/lib/common/network/ManualClientCertificateMaterial.java new file mode 100644 index 0000000000..60af296271 --- /dev/null +++ b/library/src/main/java/com/owncloud/android/lib/common/network/ManualClientCertificateMaterial.java @@ -0,0 +1,97 @@ +/* + * Nextcloud Android Library + * + * SPDX-FileCopyrightText: 2026 Nextcloud contributors + * SPDX-License-Identifier: MIT + */ +package com.owncloud.android.lib.common.network; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Enumeration; + +/** A single client identity that can be kept inside an independently encrypted PKCS#12 blob. */ +public final class ManualClientCertificateMaterial { + private static final String ENTRY_ALIAS = "client"; + private static final char[] INTERNAL_PASSWORD = new char[0]; + + private ManualClientCertificateMaterial() { } + + public static byte[] normalize(byte[] original, char[] password) + throws GeneralSecurityException, IOException { + KeyStore source = KeyStore.getInstance("PKCS12"); + source.load(new ByteArrayInputStream(original), password); + KeyStore.PrivateKeyEntry found = null; + + Enumeration aliases = source.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (!source.isKeyEntry(alias)) { + continue; + } + if (found != null) { + throw new GeneralSecurityException("Only one private key per file is supported"); + } + KeyStore.Entry entry = source.getEntry(alias, new KeyStore.PasswordProtection(password)); + if (!(entry instanceof KeyStore.PrivateKeyEntry)) { + throw new GeneralSecurityException("Client certificate does not contain a private key"); + } + found = (KeyStore.PrivateKeyEntry) entry; + } + if (found == null) { + throw new GeneralSecurityException("No private key in the selected PKCS#12 file"); + } + Certificate[] chain = found.getCertificateChain(); + if (chain == null || chain.length == 0 || !(chain[0] instanceof X509Certificate)) { + throw new GeneralSecurityException("No X.509 certificate chain in PKCS#12 file"); + } + ((X509Certificate) chain[0]).checkValidity(); + + KeyStore normalized = KeyStore.getInstance("PKCS12"); + normalized.load(null, INTERNAL_PASSWORD); + normalized.setKeyEntry(ENTRY_ALIAS, found.getPrivateKey(), INTERNAL_PASSWORD, chain); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + normalized.store(output, INTERNAL_PASSWORD); + return output.toByteArray(); + } + + public static Identity read(byte[] normalized) throws GeneralSecurityException, IOException { + KeyStore store = KeyStore.getInstance("PKCS12"); + store.load(new ByteArrayInputStream(normalized), INTERNAL_PASSWORD); + KeyStore.Entry entry = store.getEntry(ENTRY_ALIAS, new KeyStore.PasswordProtection(INTERNAL_PASSWORD)); + if (!(entry instanceof KeyStore.PrivateKeyEntry)) { + throw new GeneralSecurityException("Stored client certificate is missing its private key"); + } + KeyStore.PrivateKeyEntry identity = (KeyStore.PrivateKeyEntry) entry; + Certificate[] chain = identity.getCertificateChain(); + X509Certificate[] certificates = new X509Certificate[chain.length]; + for (int i = 0; i < chain.length; i++) { + if (!(chain[i] instanceof X509Certificate)) { + throw new GeneralSecurityException("Non-X.509 certificate in stored chain"); + } + certificates[i] = (X509Certificate) chain[i]; + } + certificates[0].checkValidity(); + return new Identity(identity.getPrivateKey(), certificates); + } + + public static final class Identity { + public final PrivateKey privateKey; + private final X509Certificate[] chain; + + private Identity(PrivateKey privateKey, X509Certificate[] chain) { + this.privateKey = privateKey; + this.chain = chain.clone(); + } + + public X509Certificate[] certificateChain() { + return chain.clone(); + } + } +} diff --git a/library/src/main/java/com/owncloud/android/lib/common/network/ManualClientCertificateStore.java b/library/src/main/java/com/owncloud/android/lib/common/network/ManualClientCertificateStore.java new file mode 100644 index 0000000000..cc6e5499e5 --- /dev/null +++ b/library/src/main/java/com/owncloud/android/lib/common/network/ManualClientCertificateStore.java @@ -0,0 +1,222 @@ +/* + * Nextcloud Android Library + * + * SPDX-FileCopyrightText: 2026 Nextcloud contributors + * SPDX-License-Identifier: MIT + */ +package com.owncloud.android.lib.common.network; + +import android.content.Context; +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyProperties; +import android.util.AtomicFile; +import android.util.Base64; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.Key; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.security.PrivateKey; +import java.util.Arrays; +import java.util.Locale; +import java.util.concurrent.ConcurrentHashMap; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; + +/** Encrypted, opt-in client certificates scoped to one TLS hostname and port. */ +public final class ManualClientCertificateStore { + public static final String ALIAS_PREFIX = "MANUAL_"; + private static final String KEY_ALIAS = "NextcloudImportedClientCertificatesV1"; + private static final int MAX_PKCS12_BYTES = 2 * 1024 * 1024; + private static final int GCM_IV_LENGTH = 12; + private static final byte FORMAT_VERSION = 1; + private static final ConcurrentHashMap CACHE = + new ConcurrentHashMap<>(); + + private ManualClientCertificateStore() { } + + private static String serverKey(@NonNull String hostname, int port) { + String host = hostname.toLowerCase(Locale.ROOT); + if (host.isEmpty() || host.contains("/") || host.contains("\\") || host.contains("@") || + host.contains("#") || Character.isWhitespace(host.charAt(0)) || port < 1 || port > 65535) { + throw new IllegalArgumentException("Invalid TLS hostname or port"); + } + return host + ":" + port; + } + + public static String aliasFor(@NonNull String hostname, int port) { + String value = serverKey(hostname, port); + return ALIAS_PREFIX + Base64.encodeToString(value.getBytes(StandardCharsets.UTF_8), + Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); + } + + private static String serverFromAlias(@NonNull String alias) { + if (!alias.startsWith(ALIAS_PREFIX)) { + throw new IllegalArgumentException("Not a manual certificate alias"); + } + String decoded = new String(Base64.decode(alias.substring(ALIAS_PREFIX.length()), + Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING), StandardCharsets.UTF_8); + int separator = decoded.lastIndexOf(':'); + if (separator <= 0 || separator == decoded.length() - 1) { + throw new IllegalArgumentException("Invalid manual certificate alias"); + } + String hostname = decoded.substring(0, separator); + int port = Integer.parseInt(decoded.substring(separator + 1)); + String canonical = serverKey(hostname, port); + if (!canonical.equals(decoded)) { + throw new IllegalArgumentException("Noncanonical manual certificate alias"); + } + return canonical; + } + + private static File file(@NonNull Context context, @NonNull String server) + throws GeneralSecurityException { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(server.getBytes(StandardCharsets.UTF_8)); + String name = Base64.encodeToString(digest, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); + return new File(context.getNoBackupFilesDir(), "mtls-" + name + ".enc"); + } + + public static boolean isConfigured(@NonNull Context context, @NonNull String hostname, int port) { + try { + return file(context, serverKey(hostname, port)).exists(); + } catch (GeneralSecurityException | IllegalArgumentException e) { + return false; + } + } + + public static synchronized void importCertificate(@NonNull Context context, @NonNull String hostname, + int port, @NonNull byte[] contents, + @NonNull char[] password) + throws GeneralSecurityException, IOException { + if (contents.length == 0 || contents.length > MAX_PKCS12_BYTES) { + throw new GeneralSecurityException("Invalid PKCS#12 file size"); + } + String server = serverKey(hostname, port); + byte[] normalized = ManualClientCertificateMaterial.normalize(contents, password); + try { + ManualClientCertificateMaterial.Identity identity = ManualClientCertificateMaterial.read(normalized); + byte[] encrypted = encrypt(normalized); + try { + AtomicFile target = new AtomicFile(file(context, server)); + FileOutputStream stream = target.startWrite(); + try { + stream.write(encrypted); + target.finishWrite(stream); + } catch (IOException | RuntimeException e) { + target.failWrite(stream); + throw e; + } + } finally { + Arrays.fill(encrypted, (byte) 0); + } + CACHE.put(server, identity); + } finally { + Arrays.fill(normalized, (byte) 0); + } + } + + public static synchronized void remove(@NonNull Context context, @NonNull String hostname, int port) + throws GeneralSecurityException { + String server = serverKey(hostname, port); + AtomicFile target = new AtomicFile(file(context, server)); + target.delete(); + CACHE.remove(server); + } + + @Nullable + public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias) + throws GeneralSecurityException, IOException { + ManualClientCertificateMaterial.Identity identity = identity(context, serverFromAlias(alias)); + return identity == null ? null : identity.privateKey; + } + + @Nullable + public static X509Certificate[] getCertificateChain(@NonNull Context context, @NonNull String alias) + throws GeneralSecurityException, IOException { + ManualClientCertificateMaterial.Identity identity = identity(context, serverFromAlias(alias)); + return identity == null ? null : identity.certificateChain(); + } + + @Nullable + private static synchronized ManualClientCertificateMaterial.Identity identity(Context context, String server) + throws GeneralSecurityException, IOException { + if (CACHE.containsKey(server)) { + return CACHE.get(server); + } + AtomicFile source = new AtomicFile(file(context, server)); + if (!source.getBaseFile().exists()) { + return null; + } + byte[] encrypted = source.readFully(); + byte[] normalized; + try { + normalized = decrypt(encrypted); + } finally { + Arrays.fill(encrypted, (byte) 0); + } + try { + ManualClientCertificateMaterial.Identity result = ManualClientCertificateMaterial.read(normalized); + CACHE.put(server, result); + return result; + } finally { + Arrays.fill(normalized, (byte) 0); + } + } + + private static SecretKey aesKey() throws GeneralSecurityException, IOException { + KeyStore keystore = KeyStore.getInstance("AndroidKeyStore"); + keystore.load(null); + Key existing = keystore.getKey(KEY_ALIAS, null); + if (existing instanceof SecretKey) { + return (SecretKey) existing; + } + KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); + generator.init(new KeyGenParameterSpec.Builder(KEY_ALIAS, + KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) + .setKeySize(256) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setRandomizedEncryptionRequired(true) + .build()); + return generator.generateKey(); + } + + private static byte[] encrypt(byte[] plaintext) throws GeneralSecurityException, IOException { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, aesKey(), new SecureRandom()); + byte[] iv = cipher.getIV(); + if (iv.length != GCM_IV_LENGTH) { + throw new GeneralSecurityException("Unexpected AES-GCM IV length"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + output.write(FORMAT_VERSION); + output.write(iv, 0, iv.length); + byte[] ciphertext = cipher.doFinal(plaintext); + output.write(ciphertext, 0, ciphertext.length); + return output.toByteArray(); + } + + private static byte[] decrypt(byte[] encrypted) throws GeneralSecurityException, IOException { + if (encrypted.length < 1 + GCM_IV_LENGTH + 16 || encrypted[0] != FORMAT_VERSION) { + throw new GeneralSecurityException("Invalid encrypted certificate format"); + } + byte[] iv = Arrays.copyOfRange(encrypted, 1, 1 + GCM_IV_LENGTH); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, aesKey(), new GCMParameterSpec(128, iv)); + return cipher.doFinal(encrypted, 1 + GCM_IV_LENGTH, + encrypted.length - (1 + GCM_IV_LENGTH)); + } +} diff --git a/library/src/test/java/com/owncloud/android/lib/common/network/ManualClientCertificateMaterialTest.java b/library/src/test/java/com/owncloud/android/lib/common/network/ManualClientCertificateMaterialTest.java new file mode 100644 index 0000000000..d9c567f959 --- /dev/null +++ b/library/src/test/java/com/owncloud/android/lib/common/network/ManualClientCertificateMaterialTest.java @@ -0,0 +1,63 @@ +/* + * Nextcloud Android Library + * + * SPDX-FileCopyrightText: 2026 Nextcloud contributors + * SPDX-License-Identifier: MIT + */ +package com.owncloud.android.lib.common.network; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import org.junit.Test; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.util.Base64; + +public class ManualClientCertificateMaterialTest { + private byte[] fixture() throws Exception { + try (InputStream stream = getClass().getResourceAsStream("/certificates/client.p12.base64")) { + assertNotNull("Missing test-only PKCS#12 fixture", stream); + byte[] encoded = stream.readAllBytes(); + return Base64.getMimeDecoder().decode(new String(encoded, StandardCharsets.US_ASCII)); + } + } + + @Test + public void importExportPreservesPrivateKeyAndCertificateChain() throws Exception { + byte[] normalized = ManualClientCertificateMaterial.normalize(fixture(), "for-tests-only".toCharArray()); + ManualClientCertificateMaterial.Identity identity = ManualClientCertificateMaterial.read(normalized); + assertNotNull(identity.privateKey); + assertEquals("RSA", identity.privateKey.getAlgorithm()); + assertEquals(1, identity.certificateChain().length); + assertEquals("CN=nextcloud-test-client", identity.certificateChain()[0].getSubjectX500Principal().getName()); + } + + @Test + public void incorrectPasswordIsRejected() throws Exception { + try { + ManualClientCertificateMaterial.normalize(fixture(), "incorrect".toCharArray()); + fail("A wrong PKCS#12 password must not be accepted"); + } catch (GeneralSecurityException | java.io.IOException expected) { + // Expected. + } + } + + @Test + public void fileWithoutPrivateKeyIsRejected() throws Exception { + KeyStore empty = KeyStore.getInstance("PKCS12"); + empty.load(null, new char[0]); + java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream(); + empty.store(output, new char[0]); + try { + ManualClientCertificateMaterial.normalize(output.toByteArray(), new char[0]); + fail("A PKCS#12 file without a private key must not be accepted"); + } catch (GeneralSecurityException expected) { + // Expected. + } + } +} diff --git a/library/src/test/resources/certificates/client.p12.base64 b/library/src/test/resources/certificates/client.p12.base64 new file mode 100644 index 0000000000..8b2fab5678 --- /dev/null +++ b/library/src/test/resources/certificates/client.p12.base64 @@ -0,0 +1,45 @@ +MIIJ/wIBAzCCCbUGCSqGSIb3DQEHAaCCCaYEggmiMIIJnjCCBAoGCSqGSIb3DQEHBqCCA/swggP3 +AgEAMIID8AYJKoZIhvcNAQcBMF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBDnZ6Bn9zI0 +eNV0zhk+XqFPAgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQyegFMlAsHFYHZ5nd4fqg +dYCCA4DnOAX1n/UWD6WbK6GijxPm1sxrLI3iFNZTu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resources/certificates/client.p12.base64.license b/library/src/test/resources/certificates/client.p12.base64.license new file mode 100644 index 0000000000..39052814f1 --- /dev/null +++ b/library/src/test/resources/certificates/client.p12.base64.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: 2026 Nextcloud contributors +SPDX-License-Identifier: MIT