Skip to content

Commit 780f7f6

Browse files
committed
Properly check cert chain
by checking root CA and a persistent ID over short lived leaf certs
1 parent 7d5f9c9 commit 780f7f6

6 files changed

Lines changed: 149 additions & 47 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Changes to prior versions can be found on the [GitHub release page](https://gith
1010
## Unreleased
1111

1212
### Added
13-
* Update mechanism `InstallerUpdateMechanism`, which downloads, verifies and runs the EXE or MSI installer matching the current installation. Self-updates are only performed if the registry value `HKLM\SOFTWARE\Skymatic GmbH\Cryptomator\InstallType` is `EXE` or `MSI`.
13+
* Update mechanism `InstallerUpdateMechanism`, which downloads, verifies and runs the EXE or MSI installer matching the current installation. Self-updates are only performed if the registry value `HKLM\SOFTWARE\Skymatic GmbH\Cryptomator\InstallType` is `EXE` or `MSI`, and the expected signer of the installer is configured via the JVM properties `cryptomator.integrationsWin.updateDurableIdentityEku` and `cryptomator.integrationsWin.updateRootCaThumbprint`.
1414

1515

1616
## [1.6.2](https://github.com/cryptomator/integrations-win/releases/1.6.2) - 2026-09-29

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ This project uses the following JVM properties:
99
* `cryptomator.integrationsWin.windowsHelloKeyId` - Identifier for the Windows Hello keypair
1010
* `cryptomator.integrationsWin.windowsHelloKeychainPaths` - Locations of the file-based windowsHello keychain
1111
* `cryptomator.integrationsWin.keychainPaths` - List of file paths, which are checked for data encrypted with the Windows data protection api
12+
* `cryptomator.integrationsWin.updateDurableIdentityEku` - OID of an extended key usage, which the code signing certificate of a downloaded installer must contain. With Azure Artifact Signing, this is the durable identity of the signing account, which stays the same across certificate renewals (e.g. `1.3.6.1.4.1.311.97.986645502.209118791.449271898.355477593` for Skymatic GmbH). Required by `InstallerUpdateMechanism`.
13+
* `cryptomator.integrationsWin.updateRootCaThumbprint` - SHA-1 thumbprint (40 hex characters, without spaces) of the root certificate, at which the certificate chain of a downloaded installer's signature must end (e.g. `F40042E2E5F7E8EF8189FED15519AECE42C3BFA2` for Microsoft Identity Verification Root Certificate Authority 2020). Required by `InstallerUpdateMechanism`.
14+
15+
`InstallerUpdateMechanism` only updates if both of the `update…` properties are set.
1216

1317
## Building
1418

‎src/main/java/org/cryptomator/windows/update/Authenticode.java‎

Lines changed: 79 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package org.cryptomator.windows.update;
22

3+
import java.io.ByteArrayInputStream;
34
import java.lang.foreign.Arena;
45
import java.lang.foreign.FunctionDescriptor;
56
import java.lang.foreign.Linker;
@@ -10,7 +11,16 @@
1011
import java.lang.invoke.MethodHandle;
1112
import java.nio.charset.StandardCharsets;
1213
import java.nio.file.Path;
14+
import java.security.MessageDigest;
15+
import java.security.NoSuchAlgorithmException;
1316
import java.security.SignatureException;
17+
import java.security.cert.CertificateException;
18+
import java.security.cert.CertificateFactory;
19+
import java.security.cert.X509Certificate;
20+
import java.util.ArrayList;
21+
import java.util.HexFormat;
22+
import java.util.List;
23+
import java.util.Objects;
1424
import java.util.Optional;
1525

1626
import static java.lang.foreign.MemoryLayout.PathElement.groupElement;
@@ -25,27 +35,22 @@
2535
*/
2636
final class Authenticode {
2737

28-
// Hand-written bindings, see WinTrust.h, SoftPub.h and wincrypt.h. DLLs are loaded by absolute path to prevent DLL search order hijacking.
38+
// Hand-written bindings, see WinTrust.h, SoftPub.h and wincrypt.h. The DLL is loaded by absolute path to prevent DLL search order hijacking.
2939
private static final Path SYSTEM32 = Path.of(Optional.ofNullable(System.getenv("SystemRoot")).orElse("C:\\Windows"), "System32");
3040
private static final Linker LINKER = Linker.nativeLinker();
3141
private static final SymbolLookup WINTRUST = SymbolLookup.libraryLookup(SYSTEM32.resolve("wintrust.dll"), Arena.global());
32-
private static final SymbolLookup CRYPT32 = SymbolLookup.libraryLookup(SYSTEM32.resolve("crypt32.dll"), Arena.global());
3342

3443
private static final MethodHandle WIN_VERIFY_TRUST = downcall(WINTRUST, "WinVerifyTrust", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS));
3544
private static final MethodHandle WT_HELPER_PROV_DATA_FROM_STATE_DATA = downcall(WINTRUST, "WTHelperProvDataFromStateData", FunctionDescriptor.of(ADDRESS, ADDRESS));
3645
private static final MethodHandle WT_HELPER_GET_PROV_SIGNER_FROM_CHAIN = downcall(WINTRUST, "WTHelperGetProvSignerFromChain", FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_INT, JAVA_INT, JAVA_INT));
3746
private static final MethodHandle WT_HELPER_GET_PROV_CERT_FROM_CHAIN = downcall(WINTRUST, "WTHelperGetProvCertFromChain", FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_INT));
38-
private static final MethodHandle CERT_GET_NAME_STRING_W = downcall(CRYPT32, "CertGetNameStringW", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, JAVA_INT, ADDRESS, ADDRESS, JAVA_INT));
3947

4048
private static final int WTD_UI_NONE = 2;
4149
private static final int WTD_REVOKE_WHOLECHAIN = 0x1;
4250
private static final int WTD_CHOICE_FILE = 1;
4351
private static final int WTD_STATEACTION_VERIFY = 0x1;
4452
private static final int WTD_STATEACTION_CLOSE = 0x2;
4553
private static final int WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x80;
46-
private static final int CERT_NAME_ATTR_TYPE = 3;
47-
private static final String SZ_OID_COMMON_NAME = "2.5.4.3";
48-
private static final long CRYPT_PROVIDER_CERT_PCERT_OFFSET = 8; // DWORD cbStruct, padding, PCCERT_CONTEXT pCert
4954

5055
private static final StructLayout GUID = MemoryLayout.structLayout(
5156
JAVA_INT.withName("Data1"),
@@ -78,17 +83,70 @@ final class Authenticode {
7883
JAVA_INT.withName("dwUIContext"),
7984
ADDRESS.withName("pSignatureSettings"));
8085

86+
// only the leading fields are declared
87+
private static final StructLayout CRYPT_PROVIDER_SGNR = MemoryLayout.structLayout(
88+
JAVA_INT.withName("cbStruct"),
89+
JAVA_INT.withName("sftVerifyAsOfLow"), // FILETIME, 4-byte aligned
90+
JAVA_INT.withName("sftVerifyAsOfHigh"),
91+
JAVA_INT.withName("csCertChain"),
92+
ADDRESS.withName("pasCertChain"));
93+
94+
// only the leading fields are declared
95+
private static final StructLayout CRYPT_PROVIDER_CERT = MemoryLayout.structLayout(
96+
JAVA_INT.withName("cbStruct"),
97+
MemoryLayout.paddingLayout(4),
98+
ADDRESS.withName("pCert"));
99+
100+
private static final StructLayout CERT_CONTEXT = MemoryLayout.structLayout(
101+
JAVA_INT.withName("dwCertEncodingType"),
102+
MemoryLayout.paddingLayout(4),
103+
ADDRESS.withName("pbCertEncoded"),
104+
JAVA_INT.withName("cbCertEncoded"),
105+
MemoryLayout.paddingLayout(4),
106+
ADDRESS.withName("pCertInfo"),
107+
ADDRESS.withName("hCertStore"));
108+
81109
private Authenticode() {
82110
}
83111

112+
/**
113+
* Verifies the embedded Authenticode signature of a file and checks that it was created by the expected signer.
114+
*
115+
* @param file the signed file, e.g. an .exe or .msi
116+
* @param signerEku OID of an extended key usage, which the signing certificate must contain, e.g. the durable identity of an Azure Artifact Signing account
117+
* @param rootThumbprint SHA-1 thumbprint (hex) of the root certificate, at which the certificate chain must end
118+
* @return the signing certificate
119+
* @throws SignatureException if the file is not signed, the signature is not trusted or it was created by a different signer
120+
*/
121+
static X509Certificate verify(Path file, String signerEku, String rootThumbprint) throws SignatureException {
122+
var chain = getVerifiedCertificateChain(file);
123+
var signerCert = chain.getFirst();
124+
var rootCert = chain.getLast();
125+
try {
126+
var ekus = Objects.requireNonNullElse(signerCert.getExtendedKeyUsage(), List.<String>of());
127+
if (!ekus.contains(signerEku)) {
128+
throw new SignatureException("Signing certificate %s of %s lacks extended key usage %s".formatted(signerCert.getSubjectX500Principal(), file, signerEku));
129+
}
130+
var actualRootThumbprint = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(rootCert.getEncoded()));
131+
if (!actualRootThumbprint.equalsIgnoreCase(rootThumbprint)) {
132+
throw new SignatureException("Certificate chain of %s ends at unexpected root %s (thumbprint %s)".formatted(file, rootCert.getSubjectX500Principal(), actualRootThumbprint));
133+
}
134+
} catch (CertificateException e) {
135+
throw new SignatureException("Failed to read certificate of " + file, e);
136+
} catch (NoSuchAlgorithmException e) {
137+
throw new IllegalStateException("Every Java platform is required to support SHA-1", e);
138+
}
139+
return signerCert;
140+
}
141+
84142
/**
85143
* Verifies the embedded Authenticode signature of a file, including the certificate chain and its revocation status.
86144
*
87145
* @param file the signed file, e.g. an .exe or .msi
88-
* @return the common name (CN) of the certificate, which created the primary signature
146+
* @return the certificate chain of the primary signature, starting with the signing certificate and ending with the trusted root certificate
89147
* @throws SignatureException if the file is not signed or the signature is not trusted
90148
*/
91-
static String getVerifiedSignerName(Path file) throws SignatureException {
149+
static List<X509Certificate> getVerifiedCertificateChain(Path file) throws SignatureException {
92150
try (var arena = Arena.ofConfined()) {
93151
var fileInfo = arena.allocate(WINTRUST_FILE_INFO);
94152
setInt(fileInfo, WINTRUST_FILE_INFO, "cbStruct", (int) WINTRUST_FILE_INFO.byteSize());
@@ -111,12 +169,21 @@ static String getVerifiedSignerName(Path file) throws SignatureException {
111169
}
112170
var provData = call(WT_HELPER_PROV_DATA_FROM_STATE_DATA, data.get(ADDRESS, offset(WINTRUST_DATA, "hWVTStateData")));
113171
var signer = provData.equals(NULL) ? NULL : call(WT_HELPER_GET_PROV_SIGNER_FROM_CHAIN, provData, 0, 0, 0);
114-
var cert = signer.equals(NULL) ? NULL : call(WT_HELPER_GET_PROV_CERT_FROM_CHAIN, signer, 0);
115-
if (cert.equals(NULL)) {
172+
int chainLength = signer.equals(NULL) ? 0 : signer.reinterpret(CRYPT_PROVIDER_SGNR.byteSize()).get(JAVA_INT, offset(CRYPT_PROVIDER_SGNR, "csCertChain"));
173+
if (chainLength == 0) {
116174
throw new SignatureException("No signer certificate found for " + file);
117175
}
118-
var certContext = cert.reinterpret(CRYPT_PROVIDER_CERT_PCERT_OFFSET + ADDRESS.byteSize()).get(ADDRESS, CRYPT_PROVIDER_CERT_PCERT_OFFSET);
119-
return getCommonName(arena, certContext);
176+
var certFactory = CertificateFactory.getInstance("X.509");
177+
var chain = new ArrayList<X509Certificate>(chainLength);
178+
for (int i = 0; i < chainLength; i++) {
179+
var cert = call(WT_HELPER_GET_PROV_CERT_FROM_CHAIN, signer, i).reinterpret(CRYPT_PROVIDER_CERT.byteSize());
180+
var certContext = cert.get(ADDRESS, offset(CRYPT_PROVIDER_CERT, "pCert")).reinterpret(CERT_CONTEXT.byteSize());
181+
var encoded = certContext.get(ADDRESS, offset(CERT_CONTEXT, "pbCertEncoded")).reinterpret(certContext.get(JAVA_INT, offset(CERT_CONTEXT, "cbCertEncoded")));
182+
chain.add((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encoded.toArray(JAVA_BYTE))));
183+
}
184+
return chain;
185+
} catch (CertificateException e) {
186+
throw new SignatureException("Failed to read certificate chain of " + file, e);
120187
} finally {
121188
// release state data allocated by WTD_STATEACTION_VERIFY
122189
setInt(data, WINTRUST_DATA, "dwStateAction", WTD_STATEACTION_CLOSE);
@@ -125,14 +192,6 @@ static String getVerifiedSignerName(Path file) throws SignatureException {
125192
}
126193
}
127194

128-
private static String getCommonName(Arena arena, MemorySegment certContext) {
129-
var oid = arena.allocateFrom(SZ_OID_COMMON_NAME, StandardCharsets.US_ASCII);
130-
int length = certGetNameString(certContext, oid, NULL, 0); // number of chars, including the null terminator
131-
var name = arena.allocate((long) length * Character.BYTES);
132-
certGetNameString(certContext, oid, name, length);
133-
return name.getString(0, StandardCharsets.UTF_16LE);
134-
}
135-
136195
// {00AAC56B-CD44-11d0-8CC2-00C04FC295EE}
137196
private static MemorySegment allocateGenericVerifyV2(Arena arena) {
138197
var guid = arena.allocate(GUID);
@@ -151,14 +210,6 @@ private static int winVerifyTrust(MemorySegment actionId, MemorySegment data) {
151210
}
152211
}
153212

154-
private static int certGetNameString(MemorySegment certContext, MemorySegment oid, MemorySegment buffer, int bufferLength) {
155-
try {
156-
return (int) CERT_GET_NAME_STRING_W.invokeExact(certContext, CERT_NAME_ATTR_TYPE, 0, oid, buffer, bufferLength);
157-
} catch (Throwable e) {
158-
throw new AssertionError("should not reach here", e);
159-
}
160-
}
161-
162213
private static MemorySegment call(MethodHandle handle, Object... args) {
163214
try {
164215
return (MemorySegment) handle.invokeWithArguments(args);

‎src/main/java/org/cryptomator/windows/update/InstallerUpdateMechanism.java‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.nio.file.Path;
2020
import java.nio.file.StandardOpenOption;
2121
import java.security.SignatureException;
22+
import java.security.cert.X509Certificate;
2223
import java.util.List;
2324
import java.util.Locale;
2425
import java.util.Optional;
@@ -37,13 +38,17 @@ public class InstallerUpdateMechanism extends DownloadUpdateMechanism {
3738
// written by the Cryptomator installer. Package managers (winget, Chocolatey, ...) set the INSTALLTYPE installer property to a different value, opting out of self-updates.
3839
private static final String INSTALL_TYPE_REG_KEY = "SOFTWARE\\Skymatic GmbH\\Cryptomator";
3940
private static final String INSTALL_TYPE_REG_VALUE = "InstallType";
40-
private static final String EXPECTED_SIGNER = "Skymatic GmbH"; // common name of the code signing certificate
41+
// the installer's signature must chain up to this root CA and the signing certificate must contain this EKU (with Azure Artifact Signing: the durable identity, which stays the same across certificate renewals)
42+
private static final String DURABLE_IDENTITY_EKU_PROPERTY = "cryptomator.integrationsWin.updateDurableIdentityEku";
43+
private static final String ROOT_CA_THUMBPRINT_PROPERTY = "cryptomator.integrationsWin.updateRootCaThumbprint";
4144
private static final Path SYSTEM32 = Path.of(Optional.ofNullable(System.getenv("SystemRoot")).orElse("C:\\Windows"), "System32");
4245

4346
private final Supplier<String> installType;
47+
private final String durableIdentityEku;
48+
private final String rootCaThumbprint;
4449

4550
public InstallerUpdateMechanism() {
46-
this(InstallerUpdateMechanism::readInstallType);
51+
this(InstallerUpdateMechanism::readInstallType, System.getProperty(DURABLE_IDENTITY_EKU_PROPERTY), System.getProperty(ROOT_CA_THUMBPRINT_PROPERTY));
4752
}
4853

4954
// visible for testing
@@ -53,6 +58,10 @@ public InstallerUpdateMechanism() {
5358

5459
@Override
5560
protected DownloadUpdateInfo checkForUpdate(String currentVersion, LatestVersionResponse response) {
61+
if (isNullOrBlank(durableIdentityEku) || isNullOrBlank(rootCaThumbprint)) {
62+
LOG.warn("Properties {} and {} must be set to verify installers, not updating.", DURABLE_IDENTITY_EKU_PROPERTY, ROOT_CA_THUMBPRINT_PROPERTY);
63+
return null;
64+
}
5665
String arch = switch (System.getProperty("os.arch")) {
5766
case "aarch64", "arm64" -> "arm64";
5867
default -> "x64";
@@ -85,18 +94,14 @@ public UpdateStep secondStep(Path workDir, Path assetPath, DownloadUpdateInfo up
8594
}
8695

8796
private UpdateStep verify(Path workDir, Path assetPath) throws IOException {
88-
String signer;
97+
X509Certificate signer;
8998
try {
90-
signer = Authenticode.getVerifiedSignerName(assetPath);
99+
signer = Authenticode.verify(assetPath, durableIdentityEku, rootCaThumbprint);
91100
} catch (SignatureException e) {
92101
LOG.error("Checking signature of {} failed.", assetPath, e);
93102
throw new UpdateFailedException("Invalid Signature.", e);
94103
}
95-
if (!EXPECTED_SIGNER.equals(signer)) {
96-
LOG.error("Installer {} is signed by unexpected signer {}.", assetPath, signer);
97-
throw new UpdateFailedException("Invalid Signature.");
98-
}
99-
LOG.debug("Verified installer {}, signed by {}.", assetPath, signer);
104+
LOG.debug("Verified installer {}, signed by {}.", assetPath, signer.getSubjectX500Principal());
100105
return UpdateStep.of(Localization.get().getString("org.cryptomator.windows.update.installer.restarting"), () -> this.restart(workDir, assetPath));
101106
}
102107

@@ -144,6 +149,10 @@ private UpdateStep restart(Path workDir, Path assetPath) throws IOException {
144149
return UpdateStep.EXIT;
145150
}
146151

152+
private static boolean isNullOrBlank(String s) {
153+
return s == null || s.isBlank();
154+
}
155+
147156
private static String readInstallType() {
148157
try {
149158
return RegistryKey.HKEY_LOCAL_MACHINE.getStringValue(INSTALL_TYPE_REG_KEY, INSTALL_TYPE_REG_VALUE, false);

‎src/test/java/org/cryptomator/windows/update/AuthenticodeIT.java‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import org.junit.jupiter.api.BeforeAll;
55
import org.junit.jupiter.api.Test;
66
import org.junit.jupiter.api.io.TempDir;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.ValueSource;
79

810
import java.io.IOException;
911
import java.net.URISyntaxException;
@@ -18,6 +20,8 @@ public class AuthenticodeIT {
1820

1921
private static final String TRUST_E_SUBJECT_FORM_UNKNOWN = "0x800B0003";
2022
private static final String TRUST_E_BAD_DIGEST = "0x80096010";
23+
private static final String SKYMATIC_DURABLE_IDENTITY = "1.3.6.1.4.1.311.97.986645502.209118791.449271898.355477593";
24+
private static final String MICROSOFT_ROOT_THUMBPRINT = "F40042E2E5F7E8EF8189FED15519AECE42C3BFA2"; // Microsoft Identity Verification Root Certificate Authority 2020
2125

2226
// signed by Skymatic GmbH with a timestamped signature, whose certificate is already expired
2327
private static Path signedDll;
@@ -31,15 +35,37 @@ public static void setup() throws URISyntaxException {
3135
public void testUnknownFileFormat(@TempDir Path tmpDir) throws IOException {
3236
var file = Files.writeString(tmpDir.resolve("not an installer (x).msi"), "not an installer");
3337

34-
var e = Assertions.assertThrows(SignatureException.class, () -> Authenticode.getVerifiedSignerName(file));
38+
var e = Assertions.assertThrows(SignatureException.class, () -> Authenticode.getVerifiedCertificateChain(file));
3539
Assertions.assertTrue(e.getMessage().contains(TRUST_E_SUBJECT_FORM_UNKNOWN), e.getMessage());
3640
}
3741

3842
@Test
39-
public void testSignedFile() throws SignatureException {
40-
var signer = Authenticode.getVerifiedSignerName(signedDll);
43+
public void testCertificateChain() throws SignatureException {
44+
var chain = Authenticode.getVerifiedCertificateChain(signedDll);
4145

42-
Assertions.assertEquals("Skymatic GmbH", signer);
46+
Assertions.assertEquals(4, chain.size());
47+
Assertions.assertEquals("CN=Skymatic GmbH,O=Skymatic GmbH,L=Bonn,C=DE", chain.getFirst().getSubjectX500Principal().getName());
48+
Assertions.assertEquals("CN=Microsoft Identity Verification Root Certificate Authority 2020,O=Microsoft Corporation,C=US", chain.getLast().getSubjectX500Principal().getName());
49+
}
50+
51+
@ParameterizedTest
52+
@ValueSource(strings = {MICROSOFT_ROOT_THUMBPRINT, "f40042e2e5f7e8ef8189fed15519aece42c3bfa2"})
53+
public void testExpectedSigner(String rootThumbprint) throws SignatureException {
54+
var signer = Authenticode.verify(signedDll, SKYMATIC_DURABLE_IDENTITY, rootThumbprint);
55+
56+
Assertions.assertEquals("CN=Skymatic GmbH,O=Skymatic GmbH,L=Bonn,C=DE", signer.getSubjectX500Principal().getName());
57+
}
58+
59+
@Test
60+
public void testUnexpectedSignerEku() {
61+
var e = Assertions.assertThrows(SignatureException.class, () -> Authenticode.verify(signedDll, "1.3.6.1.4.1.311.97.1.2.3.4", MICROSOFT_ROOT_THUMBPRINT));
62+
Assertions.assertTrue(e.getMessage().contains("lacks extended key usage"), e.getMessage());
63+
}
64+
65+
@Test
66+
public void testUnexpectedRoot() {
67+
var e = Assertions.assertThrows(SignatureException.class, () -> Authenticode.verify(signedDll, SKYMATIC_DURABLE_IDENTITY, "0000000000000000000000000000000000000000"));
68+
Assertions.assertTrue(e.getMessage().contains("unexpected root"), e.getMessage());
4369
}
4470

4571
@Test
@@ -53,7 +79,7 @@ public void testTamperedFile(@TempDir Path tmpDir) throws IOException {
5379
ch.write(buf.rewind(), pos);
5480
}
5581

56-
var e = Assertions.assertThrows(SignatureException.class, () -> Authenticode.getVerifiedSignerName(file));
82+
var e = Assertions.assertThrows(SignatureException.class, () -> Authenticode.getVerifiedCertificateChain(file));
5783
Assertions.assertTrue(e.getMessage().contains(TRUST_E_BAD_DIGEST), e.getMessage());
5884
}
5985

0 commit comments

Comments
 (0)