Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions library/src/androidTest/assets/client.p12.base64
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
MIIJ/wIBAzCCCbUGCSqGSIb3DQEHAaCCCaYEggmiMIIJnjCCBAoGCSqGSIb3DQEHBqCCA/swggP3
AgEAMIID8AYJKoZIhvcNAQcBMF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBDnZ6Bn9zI0
eNV0zhk+XqFPAgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQyegFMlAsHFYHZ5nd4fqg
dYCCA4DnOAX1n/UWD6WbK6GijxPm1sxrLI3iFNZTuDnwJEnVQlj5XepShrH8ov17ldi8c4mnnBI/
5e1KM1xAEhk3CN58wDg79dqzjdNM+AYS24M/6u217ZL1Y4FbvVlxc6fKhG4oSD3eyWMS+ebaKFVK
82EJXNGEVLdMZfnTh7khBAGENWmYg4LrZEFZKxg3FfhucrR3gApdfF2FfzFCcvWwR0BbBfyfSKHJ
LlIxvBk40a2HBhPhWUkwvjTeGgIgMtdAemi/7k7HZaeb+kzs3RYfS+zlmxAYFI3n0AgEK9dUuLBj
AKAQWq+3N8t5e5LwDX1L1dwGIcP4xn7hdFCj+eD0n8Wt1FmfVRKKqwv41uFEtvA+wLmfm6iGRbwt
CVCLieUAOT3aZPuTq1Oq3WH4PcNowtArRLbhYV1IAqCkG/CrjdEoRaqSUNd6V3xSPiTbW2K1W2vU
Ej94TobAJb2xauikEX6LtNOOKz5VaRibr+12L2+3SzaewC9N5VNb8cReMHltUoTnSX7/AU/SkzMw
p9tGLUTdxnDixzh9RPSypcbi6OwhRmcGCVykmrui9/uOdIR6G3gXN6YXogubQUrkAZVu2gFNLgZP
d6DlV6kG2XDV4ayEFRe1Jcg3+5C+enO4nlUYun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976Pt4p/0InpCCrkEz43/C1q0MJFyeYGd7n0dIMi+onL3ULctKLgGVoIzPyc
JGNH6Xx6Jr9pIGotGrfpIYcdG+mdUsZoEYe8+MdpKp8zlXK7rhXzoP+ob+DD7XnqLj41A0ChxiWS
SpUb1XMMq3nfFkDd3+d09FGYerhxas6YF4VTY/UK1pBRHipIJGETLhv98n76nuDkubNPkew1mN3f
QfezZSuT2aquaT8Zj2cXaDm2SXDrBvcg2Soz39ggXqN3N3EAUPtlocIvVsJ8zVhikd+cOWo/Q5bb
1jKgUeZUMSUwIwYJKoZIhvcNAQkVMRYEFPf0h+/5GKvzdDOTO1JRakspMoktMEEwMTANBglghkgB
ZQMEAgEFAAQg2pwMd1aow4OZQ9aspu7Su5Q2/6akU/zmg5GM4DVVOewECAfEbwQx1ggsAgIIAA==
2 changes: 2 additions & 0 deletions library/src/androidTest/assets/client.p12.base64.license
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SPDX-FileCopyrightText: 2026 Nextcloud contributors
SPDX-License-Identifier: MIT
Original file line number Diff line number Diff line change
@@ -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));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -324,10 +324,16 @@ private static <T> LinkedList<String> filterAliases(Collection<T> 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);
}

/**
Expand All @@ -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) {
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> 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();
}
}
}
Loading