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