1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.ssl;
17
18 import io.netty.internal.tcnative.CertificateCallback;
19 import io.netty.internal.tcnative.SSL;
20 import io.netty.internal.tcnative.SSLContext;
21 import io.netty.util.internal.EmptyArrays;
22
23 import java.security.KeyStore;
24 import java.security.PrivateKey;
25 import java.security.cert.X509Certificate;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.HashSet;
29 import java.util.LinkedHashSet;
30 import java.util.Map;
31 import java.util.Set;
32 import javax.net.ssl.KeyManagerFactory;
33 import javax.net.ssl.SSLException;
34 import javax.net.ssl.TrustManagerFactory;
35 import javax.net.ssl.X509ExtendedTrustManager;
36 import javax.net.ssl.X509TrustManager;
37 import javax.security.auth.x500.X500Principal;
38
39
40
41
42
43
44
45
46
47 public final class ReferenceCountedOpenSslClientContext extends ReferenceCountedOpenSslContext {
48
49 private static final Set<String> SUPPORTED_KEY_TYPES = Collections.unmodifiableSet(new LinkedHashSet<String>(
50 Arrays.asList(OpenSslKeyMaterialManager.KEY_TYPE_RSA,
51 OpenSslKeyMaterialManager.KEY_TYPE_DH_RSA,
52 OpenSslKeyMaterialManager.KEY_TYPE_EC,
53 OpenSslKeyMaterialManager.KEY_TYPE_EC_RSA,
54 OpenSslKeyMaterialManager.KEY_TYPE_EC_EC)));
55
56 private final OpenSslSessionContext sessionContext;
57
58 ReferenceCountedOpenSslClientContext(X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
59 X509Certificate[] keyCertChain, PrivateKey key, String keyPassword,
60 KeyManagerFactory keyManagerFactory, Iterable<String> ciphers,
61 CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
62 String[] protocols, long sessionCacheSize, long sessionTimeout,
63 boolean enableOcsp, String keyStore, String endpointIdentificationAlgorithm,
64 ResumptionController resumptionController,
65 Map.Entry<SslContextOption<?>, Object>... options) throws SSLException {
66 super(ciphers, cipherFilter, toNegotiator(apn), SSL.SSL_MODE_CLIENT, keyCertChain,
67 ClientAuth.NONE, protocols, false, endpointIdentificationAlgorithm, enableOcsp, true,
68 resumptionController, options);
69 boolean success = false;
70 try {
71 sessionContext = newSessionContext(this, ctx, engineMap, trustCertCollection, trustManagerFactory,
72 keyCertChain, key, keyPassword, keyManagerFactory, keyStore,
73 sessionCacheSize, sessionTimeout, resumptionController);
74 success = true;
75 } finally {
76 if (!success) {
77 release();
78 }
79 }
80 }
81
82 @Override
83 public OpenSslSessionContext sessionContext() {
84 return sessionContext;
85 }
86
87 static OpenSslSessionContext newSessionContext(ReferenceCountedOpenSslContext thiz, long ctx,
88 OpenSslEngineMap engineMap,
89 X509Certificate[] trustCertCollection,
90 TrustManagerFactory trustManagerFactory,
91 X509Certificate[] keyCertChain, PrivateKey key,
92 String keyPassword, KeyManagerFactory keyManagerFactory,
93 String keyStore, long sessionCacheSize, long sessionTimeout,
94 ResumptionController resumptionController)
95 throws SSLException {
96 if (key == null && keyCertChain != null || key != null && keyCertChain == null) {
97 throw new IllegalArgumentException(
98 "Either both keyCertChain and key needs to be null or none of them");
99 }
100 OpenSslKeyMaterialProvider keyMaterialProvider = null;
101 try {
102 try {
103 if (!OpenSsl.useKeyManagerFactory()) {
104 if (keyManagerFactory != null) {
105 throw new IllegalArgumentException(
106 "KeyManagerFactory not supported");
107 }
108 if (keyCertChain != null) {
109 setKeyMaterial(ctx, keyCertChain, key, keyPassword);
110 }
111 } else {
112
113 if (keyManagerFactory == null && keyCertChain != null) {
114 char[] keyPasswordChars = keyStorePassword(keyPassword);
115 KeyStore ks = buildKeyStore(keyCertChain, key, keyPasswordChars, keyStore);
116 if (ks.aliases().hasMoreElements()) {
117 keyManagerFactory = new OpenSslX509KeyManagerFactory();
118 } else {
119 keyManagerFactory = new OpenSslCachingX509KeyManagerFactory(
120 KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()));
121 }
122 keyManagerFactory.init(ks, keyPasswordChars);
123 keyMaterialProvider = providerFor(keyManagerFactory, keyPassword);
124 } else if (keyManagerFactory != null) {
125 keyMaterialProvider = providerFor(keyManagerFactory, keyPassword);
126 }
127
128 if (keyMaterialProvider != null) {
129 OpenSslKeyMaterialManager materialManager = new OpenSslKeyMaterialManager(keyMaterialProvider);
130 SSLContext.setCertificateCallback(ctx, new OpenSslClientCertificateCallback(
131 engineMap, materialManager));
132 }
133 }
134 } catch (Exception e) {
135 throw new SSLException("failed to set certificate and key", e);
136 }
137
138
139
140
141
142
143
144 SSLContext.setVerify(ctx, SSL.SSL_CVERIFY_OPTIONAL, VERIFY_DEPTH);
145
146 try {
147 if (trustCertCollection != null) {
148 trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory, keyStore);
149 } else if (trustManagerFactory == null) {
150 trustManagerFactory = TrustManagerFactory.getInstance(
151 TrustManagerFactory.getDefaultAlgorithm());
152 trustManagerFactory.init((KeyStore) null);
153 }
154 final X509TrustManager manager = chooseTrustManager(
155 trustManagerFactory.getTrustManagers(), resumptionController);
156
157
158
159
160
161
162
163 setVerifyCallback(ctx, engineMap, manager);
164 } catch (Exception e) {
165 if (keyMaterialProvider != null) {
166 keyMaterialProvider.destroy();
167 }
168 throw new SSLException("unable to setup trustmanager", e);
169 }
170 OpenSslClientSessionContext context = new OpenSslClientSessionContext(thiz, keyMaterialProvider);
171 context.setSessionCacheEnabled(CLIENT_ENABLE_SESSION_CACHE);
172 if (sessionCacheSize > 0) {
173 context.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE));
174 }
175 if (sessionTimeout > 0) {
176 context.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE));
177 }
178
179 if (CLIENT_ENABLE_SESSION_TICKET) {
180 context.setTicketKeys();
181 }
182
183 keyMaterialProvider = null;
184 return context;
185 } finally {
186 if (keyMaterialProvider != null) {
187 keyMaterialProvider.destroy();
188 }
189 }
190 }
191
192 private static void setVerifyCallback(long ctx, OpenSslEngineMap engineMap, X509TrustManager manager) {
193
194 if (useExtendedTrustManager(manager)) {
195 SSLContext.setCertVerifyCallback(ctx,
196 new ExtendedTrustManagerVerifyCallback(engineMap, (X509ExtendedTrustManager) manager));
197 } else {
198 SSLContext.setCertVerifyCallback(ctx, new TrustManagerVerifyCallback(engineMap, manager));
199 }
200 }
201
202 static final class OpenSslClientSessionContext extends OpenSslSessionContext {
203 OpenSslClientSessionContext(ReferenceCountedOpenSslContext context, OpenSslKeyMaterialProvider provider) {
204 super(context, provider, SSL.SSL_SESS_CACHE_CLIENT, new OpenSslClientSessionCache(context.engineMap));
205 }
206 }
207
208 private static final class TrustManagerVerifyCallback extends AbstractCertificateVerifier {
209 private final X509TrustManager manager;
210
211 TrustManagerVerifyCallback(OpenSslEngineMap engineMap, X509TrustManager manager) {
212 super(engineMap);
213 this.manager = manager;
214 }
215
216 @Override
217 void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
218 throws Exception {
219 manager.checkServerTrusted(peerCerts, auth);
220 }
221 }
222
223 private static final class ExtendedTrustManagerVerifyCallback extends AbstractCertificateVerifier {
224 private final X509ExtendedTrustManager manager;
225
226 ExtendedTrustManagerVerifyCallback(OpenSslEngineMap engineMap, X509ExtendedTrustManager manager) {
227 super(engineMap);
228 this.manager = manager;
229 }
230
231 @Override
232 void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
233 throws Exception {
234 manager.checkServerTrusted(peerCerts, auth, engine);
235 }
236 }
237
238 private static final class OpenSslClientCertificateCallback implements CertificateCallback {
239 private final OpenSslEngineMap engineMap;
240 private final OpenSslKeyMaterialManager keyManagerHolder;
241
242 OpenSslClientCertificateCallback(OpenSslEngineMap engineMap, OpenSslKeyMaterialManager keyManagerHolder) {
243 this.engineMap = engineMap;
244 this.keyManagerHolder = keyManagerHolder;
245 }
246
247 @Override
248 public void handle(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals) throws Exception {
249 final ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
250
251 if (engine == null) {
252 return;
253 }
254 try {
255 final Set<String> keyTypesSet = supportedClientKeyTypes(keyTypeBytes);
256 final String[] keyTypes = keyTypesSet.toArray(EmptyArrays.EMPTY_STRINGS);
257 final X500Principal[] issuers;
258 if (asn1DerEncodedPrincipals == null) {
259 issuers = null;
260 } else {
261 issuers = new X500Principal[asn1DerEncodedPrincipals.length];
262 for (int i = 0; i < asn1DerEncodedPrincipals.length; i++) {
263 issuers[i] = new X500Principal(asn1DerEncodedPrincipals[i]);
264 }
265 }
266 keyManagerHolder.setKeyMaterialClientSide(engine, keyTypes, issuers);
267 } catch (Throwable cause) {
268 engine.initHandshakeException(cause);
269 if (cause instanceof Exception) {
270 throw (Exception) cause;
271 }
272 throw new SSLException(cause);
273 }
274 }
275
276
277
278
279
280
281
282
283
284 private static Set<String> supportedClientKeyTypes(byte[] clientCertificateTypes) {
285 if (clientCertificateTypes == null) {
286
287 return SUPPORTED_KEY_TYPES;
288 }
289 Set<String> result = new HashSet<String>(clientCertificateTypes.length);
290 for (byte keyTypeCode : clientCertificateTypes) {
291 String keyType = clientKeyType(keyTypeCode);
292 if (keyType == null) {
293
294 continue;
295 }
296 result.add(keyType);
297 }
298 return result;
299 }
300
301 private static String clientKeyType(byte clientCertificateType) {
302
303 switch (clientCertificateType) {
304 case CertificateCallback.TLS_CT_RSA_SIGN:
305 return OpenSslKeyMaterialManager.KEY_TYPE_RSA;
306 case CertificateCallback.TLS_CT_RSA_FIXED_DH:
307 return OpenSslKeyMaterialManager.KEY_TYPE_DH_RSA;
308 case CertificateCallback.TLS_CT_ECDSA_SIGN:
309 return OpenSslKeyMaterialManager.KEY_TYPE_EC;
310 case CertificateCallback.TLS_CT_RSA_FIXED_ECDH:
311 return OpenSslKeyMaterialManager.KEY_TYPE_EC_RSA;
312 case CertificateCallback.TLS_CT_ECDSA_FIXED_ECDH:
313 return OpenSslKeyMaterialManager.KEY_TYPE_EC_EC;
314 default:
315 return null;
316 }
317 }
318 }
319 }