-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCrypt32ExtUtil.java
More file actions
207 lines (172 loc) · 9.44 KB
/
Crypt32ExtUtil.java
File metadata and controls
207 lines (172 loc) · 9.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package org.jetbrains.nativecerts.win32;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.Crypt32;
import com.sun.jna.platform.win32.Kernel32Util;
import com.sun.jna.platform.win32.WTypes;
import com.sun.jna.platform.win32.Win32Exception;
import com.sun.jna.platform.win32.WinCrypt;
import com.sun.jna.ptr.PointerByReference;
import org.jetbrains.nativecerts.NativeTrustedRootsInternalUtils;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.sun.jna.platform.win32.WinError.CRYPT_E_NOT_FOUND;
import static com.sun.jna.platform.win32.WinError.ERROR_FILE_NOT_FOUND;
import static com.sun.jna.platform.win32.WinError.ERROR_NO_MORE_FILES;
import static org.jetbrains.nativecerts.NativeTrustedRootsInternalUtils.renderExceptionMessage;
public class Crypt32ExtUtil {
private final static Logger LOGGER = Logger.getLogger(Crypt32ExtUtil.class.getName());
private static final Map<String, Integer> customTrustedCertificatesLocations = Map.of(
"CERT_SYSTEM_STORE_LOCAL_MACHINE", Crypt32Ext.CERT_SYSTEM_STORE_LOCAL_MACHINE,
"CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY", Crypt32Ext.CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
"CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE", Crypt32Ext.CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
"CERT_SYSTEM_STORE_CURRENT_USER", Crypt32Ext.CERT_SYSTEM_STORE_CURRENT_USER,
"CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY", Crypt32Ext.CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY
);
public static Collection<X509Certificate> getCustomTrustedRootCertificates() {
HashSet<X509Certificate> result = new HashSet<>();
for (Map.Entry<String, Integer> entry : customTrustedCertificatesLocations.entrySet()) {
List<X509Certificate> root = gatherEnterpriseCertsForLocation(entry.getValue(), "ROOT");
List<X509Certificate> intermediates = gatherEnterpriseCertsForLocation(entry.getValue(), "CA");
if (LOGGER.isLoggable(Level.FINE)) {
StringBuilder message = new StringBuilder();
message.append("Received ").append(root.size()).append(" certificates from store ROOT / ").append(entry.getKey());
for (X509Certificate certificate : root) {
message.append("\n ROOT/").append(entry.getKey()).append(": ").append(certificate.getSubjectX500Principal());
}
message.append("\nReceived ").append(intermediates.size()).append(" certificates from store CA (Intermediates) / ").append(entry.getKey());
for (X509Certificate certificate : intermediates) {
message.append("\n CA/").append(entry.getKey()).append(": ").append(certificate.getSubjectX500Principal());
}
LOGGER.fine(message.toString());
}
result.addAll(root);
for (X509Certificate intermediate : intermediates) {
try {
validateCertificate(intermediate.getEncoded());
result.add(intermediate);
} catch (Throwable t) {
LOGGER.log(
Level.FINE,
"Unable to validate whether certificate '" + intermediate.getSubjectX500Principal() + "' is trusted: " + t.getMessage(),
t);
}
}
}
return result;
}
public static void CertCloseStore(WinCrypt.HCERTSTORE handle) {
if (!Crypt32.INSTANCE.CertCloseStore(handle, 0)) {
throw new IllegalStateException("CertCloseStore: " + Kernel32Util.formatMessage(Native.getLastError()));
}
}
public static List<X509Certificate> gatherEnterpriseCertsForLocation(int location, String store_name) {
int flags = location | Crypt32Ext.CERT_STORE_OPEN_EXISTING_FLAG | Crypt32Ext.CERT_STORE_READONLY_FLAG;
WinCrypt.HCERTSTORE hcertstore =
Crypt32Ext.INSTANCE.CertOpenStore(
new WTypes.LPSTR(new Pointer(Crypt32Ext.CERT_STORE_PROV_SYSTEM_REGISTRY_W)),
0,
new WinCrypt.HCRYPTPROV_LEGACY(0),
flags,
new WTypes.LPWSTR(store_name));
if (hcertstore == null) {
int errorCode = Native.getLastError();
if (errorCode == ERROR_NO_MORE_FILES || errorCode == ERROR_FILE_NOT_FOUND) {
return Collections.emptyList();
} else {
throw new Win32Exception(errorCode);
}
}
try {
List<X509Certificate> result = new ArrayList<>();
WinCrypt.CERT_CONTEXT.ByReference prev = null;
while (true) {
WinCrypt.CERT_CONTEXT.ByReference certificate =
Crypt32.INSTANCE.CertEnumCertificatesInStore(
hcertstore, prev == null ? null : prev.getPointer());
if (certificate == null) {
int errorCode = Native.getLastError();
if (errorCode != CRYPT_E_NOT_FOUND && errorCode != ERROR_NO_MORE_FILES) {
throw new Win32Exception(errorCode);
}
break;
}
byte[] bytes = certificate.pbCertEncoded.getByteArray(0, certificate.cbCertEncoded);
try {
X509Certificate x509 = NativeTrustedRootsInternalUtils.parseCertificate(bytes);
result.add(x509);
} catch (Throwable parsingException) {
LOGGER.warning(renderExceptionMessage(
"Unable to parse one of the certificates" +
"from store '" + store_name + "'",
parsingException));
}
prev = certificate;
}
return result;
} finally {
CertCloseStore(hcertstore);
}
}
public static void validateCertificate(byte[] encodedCertificate) {
var certificateContext = Crypt32Ext.INSTANCE.CertCreateCertificateContext(
WinCrypt.X509_ASN_ENCODING | WinCrypt.PKCS_7_ASN_ENCODING, encodedCertificate, encodedCertificate.length);
if (certificateContext == null) {
throw new Win32Exception(Native.getLastError());
}
try {
WinCrypt.CERT_CHAIN_PARA pChainPara = new WinCrypt.CERT_CHAIN_PARA();
pChainPara.cbSize = pChainPara.size();
pChainPara.RequestedUsage.dwType = WinCrypt.USAGE_MATCH_TYPE_AND;
pChainPara.RequestedUsage.Usage.cUsageIdentifier = 0;
pChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = null;
PointerByReference ppChainContext = new PointerByReference();
if (!Crypt32.INSTANCE.CertGetCertificateChain(
null, certificateContext, null, null, pChainPara,
Crypt32Ext.CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY,
null, ppChainContext)) {
throw new Win32Exception(Native.getLastError());
}
if (ppChainContext.getValue() == null) {
throw new IllegalStateException("CertGetCertificateChain was successful, but returned chain context is null");
}
WinCrypt.CERT_CHAIN_CONTEXT pChainContext = Structure.newInstance(WinCrypt.CERT_CHAIN_CONTEXT.class, ppChainContext.getValue());
pChainContext.read();
if (pChainContext.cbSize != pChainContext.size()) {
throw new IllegalStateException("CertGetCertificateChain was successful, but returned chain context size is incorrect." +
"returned cbSize is " + pChainContext.cbSize + ", but the structure size is " + pChainContext.size());
}
try {
WinCrypt.CERT_CHAIN_POLICY_PARA chainPolicyPara = new WinCrypt.CERT_CHAIN_POLICY_PARA();
chainPolicyPara.cbSize = chainPolicyPara.size();
chainPolicyPara.dwFlags = 0;
WinCrypt.CERT_CHAIN_POLICY_STATUS policyStatus = new WinCrypt.CERT_CHAIN_POLICY_STATUS();
policyStatus.dwError = 1; // extra check that CertVerifyCertificateChainPolicy actually sets this field
policyStatus.cbSize = policyStatus.size();
if (!Crypt32.INSTANCE.CertVerifyCertificateChainPolicy(
new WTypes.LPSTR(Pointer.createConstant(Crypt32Ext.CERT_CHAIN_POLICY_SSL)),
pChainContext, chainPolicyPara, policyStatus)) {
throw new Win32Exception(Native.getLastError());
}
int dwError = policyStatus.dwError;
if (dwError != 0) {
throw new Win32Exception(dwError, null, "CertVerifyCertificateChainPolicy failed to validate certificate with code " +
Integer.toHexString(dwError) + ":\n" + Kernel32Util.formatMessage(dwError)) {
};
}
} finally {
Crypt32.INSTANCE.CertFreeCertificateChain(pChainContext);
}
} finally {
Crypt32.INSTANCE.CertFreeCertificateContext(certificateContext);
}
}
}