View Javadoc
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.ssl;
17  
18  import io.netty.util.internal.PlatformDependent;
19  import io.netty.util.internal.SuppressJava6Requirement;
20  
21  import javax.net.ssl.ExtendedSSLSession;
22  import javax.net.ssl.SSLException;
23  import javax.net.ssl.SSLHandshakeException;
24  import javax.net.ssl.X509ExtendedKeyManager;
25  import javax.net.ssl.X509KeyManager;
26  import javax.security.auth.x500.X500Principal;
27  import java.security.PrivateKey;
28  import java.security.cert.X509Certificate;
29  import java.util.Arrays;
30  import java.util.HashMap;
31  import java.util.HashSet;
32  import java.util.Map;
33  import java.util.Set;
34  
35  
36  /**
37   * Manages key material for {@link OpenSslEngine}s and so set the right {@link PrivateKey}s and
38   * {@link X509Certificate}s.
39   */
40  final class OpenSslKeyMaterialManager {
41  
42      // Code in this class is inspired by code of conscrypts:
43      // - https://android.googlesource.com/platform/external/
44      //   conscrypt/+/master/src/main/java/org/conscrypt/OpenSSLEngineImpl.java
45      // - https://android.googlesource.com/platform/external/
46      //   conscrypt/+/master/src/main/java/org/conscrypt/SSLParametersImpl.java
47      //
48      static final String KEY_TYPE_RSA = "RSA";
49      static final String KEY_TYPE_DH_RSA = "DH_RSA";
50      static final String KEY_TYPE_EC = "EC";
51      static final String KEY_TYPE_EC_EC = "EC_EC";
52      static final String KEY_TYPE_EC_RSA = "EC_RSA";
53      static final String KEY_TYPE_EDDSA = "EdDSA";
54  
55      // key type mappings for types.
56      private static final Map<String, String> KEY_TYPES = new HashMap<String, String>();
57      static {
58          KEY_TYPES.put("RSA", KEY_TYPE_RSA);
59          KEY_TYPES.put("DHE_RSA", KEY_TYPE_RSA);
60          KEY_TYPES.put("ECDHE_RSA", KEY_TYPE_RSA);
61          KEY_TYPES.put("ECDHE_ECDSA", KEY_TYPE_EC);
62          KEY_TYPES.put("ECDH_RSA", KEY_TYPE_EC_RSA);
63          KEY_TYPES.put("ECDH_ECDSA", KEY_TYPE_EC_EC);
64          KEY_TYPES.put("DH_RSA", KEY_TYPE_DH_RSA);
65      }
66  
67      private static final int TYPE_RSA     = 1;      // 00001
68      private static final int TYPE_DH_RSA  = 1 << 1; // 00010
69      private static final int TYPE_EC      = 1 << 2; // 00100
70      private static final int TYPE_EC_EC   = 1 << 3; // 01000
71      private static final int TYPE_EC_RSA  = 1 << 4; // 10000
72      private static final int TYPE_EDDSA   = 1 << 5; // 100000
73  
74      private final OpenSslKeyMaterialProvider provider;
75      private final boolean hasTmpDhKeys;
76  
77      OpenSslKeyMaterialManager(OpenSslKeyMaterialProvider provider, boolean hasTmpDhKeys) {
78          this.provider = provider;
79          this.hasTmpDhKeys = hasTmpDhKeys;
80      }
81  
82      void setKeyMaterialServerSide(ReferenceCountedOpenSslEngine engine) throws SSLException {
83          // TLS 1.3 cipher suites don't carry an authentication method, so choose the key type from the peer's
84          // signature algorithms instead. This is consistent with what OpenJDK does:
85          // https://github.com/openjdk/jdk/blob/jdk-26-ga/
86          // src/java.base/share/classes/sun/security/ssl/CertificateMessage.java#L995-L1029
87          if (engine.isTLSv13() && PlatformDependent.javaVersion() >= 7) {
88              if (setKeyMaterialServerSideTLS13(engine)) {
89                  return;
90              }
91          }
92  
93          String[] authMethods = engine.authMethods();
94          if (authMethods.length == 0) {
95              throw new SSLHandshakeException("Unable to find key material");
96          }
97  
98          // authMethods may contain duplicates or may result in the same type
99          // but call chooseServerAlias(...) may be expensive. So let's ensure
100         // we filter out duplicates.
101         Set<String> typeSet = new HashSet<String>(KEY_TYPES.size());
102         for (String authMethod : authMethods) {
103             String type = KEY_TYPES.get(authMethod);
104             if (type != null && typeSet.add(type)) {
105                 String alias = chooseServerAlias(engine, type);
106                 if (alias != null) {
107                     // We found a match... let's set the key material and return.
108                     setKeyMaterial(engine, alias);
109                     return;
110                 }
111             }
112         }
113         if (hasTmpDhKeys && authMethods.length == 1 &&
114                 ("DH_anon".equals(authMethods[0]) || "ECDH_anon".equals(authMethods[0]))) {
115             return; // These auth methods don't require certificates.
116         }
117         throw new SSLHandshakeException("Unable to find key material for auth method(s): "
118                 + Arrays.toString(authMethods));
119     }
120 
121     @SuppressJava6Requirement(reason = "guarded by java version check")
122     private boolean setKeyMaterialServerSideTLS13(ReferenceCountedOpenSslEngine engine) throws SSLException {
123         if (engine.getHandshakeSession() instanceof ExtendedSSLSession) {
124             ExtendedSSLSession session = (ExtendedSSLSession) engine.getHandshakeSession();
125             int seenTypes = 0;
126             for (String algorithm : session.getPeerSupportedSignatureAlgorithms()) {
127                 int typeBit = resolveSignatureAlgorithmKeyTypeBit(algorithm);
128                 if (typeBit == 0 || (seenTypes & typeBit) != 0) {
129                     continue;
130                 }
131 
132                 seenTypes |= typeBit; // mark as seen
133 
134                 String alias = chooseServerAlias(engine, keyTypeString(typeBit));
135                 if (alias != null) {
136                     setKeyMaterial(engine, alias);
137                     return true;
138                 }
139             }
140         }
141         return false;
142     }
143 
144     private static int resolveSignatureAlgorithmKeyTypeBit(String algorithm) {
145         if ("Ed25519".equals(algorithm) || "Ed448".equals(algorithm)) {
146             return TYPE_EDDSA;
147         }
148         if (algorithm.endsWith("withECDSA")) {
149             return TYPE_EC;
150         }
151         if (algorithm.endsWith("withRSA")) {
152             return TYPE_RSA;
153         }
154         return 0;
155     }
156 
157     private static String keyTypeString(int typeBit) {
158         switch (typeBit) {
159             case TYPE_RSA: return KEY_TYPE_RSA;
160             case TYPE_DH_RSA: return KEY_TYPE_DH_RSA;
161             case TYPE_EC: return KEY_TYPE_EC;
162             case TYPE_EC_EC: return KEY_TYPE_EC_EC;
163             case TYPE_EC_RSA: return KEY_TYPE_EC_RSA;
164             case TYPE_EDDSA: return KEY_TYPE_EDDSA;
165             default: return null;
166         }
167     }
168 
169     void setKeyMaterialClientSide(ReferenceCountedOpenSslEngine engine, String[] keyTypes,
170                                   X500Principal[] issuer) throws SSLException {
171         String alias = chooseClientAlias(engine, keyTypes, issuer);
172         // Only try to set the keymaterial if we have a match. This is also consistent with what OpenJDK does:
173         // https://hg.openjdk.java.net/jdk/jdk11/file/76072a077ee1/
174         // src/java.base/share/classes/sun/security/ssl/CertificateRequest.java#l362
175         if (alias != null) {
176             setKeyMaterial(engine, alias);
177         }
178     }
179 
180     private void setKeyMaterial(ReferenceCountedOpenSslEngine engine, String alias) throws SSLException {
181         OpenSslKeyMaterial keyMaterial = null;
182         try {
183             keyMaterial = provider.chooseKeyMaterial(engine.alloc, alias);
184             if (keyMaterial == null) {
185                 return;
186             }
187             engine.setKeyMaterial(keyMaterial);
188         } catch (SSLException e) {
189             throw e;
190         } catch (Exception e) {
191             throw new SSLException(e);
192         } finally {
193             if (keyMaterial != null) {
194                 keyMaterial.release();
195             }
196         }
197     }
198     private String chooseClientAlias(ReferenceCountedOpenSslEngine engine,
199                                        String[] keyTypes, X500Principal[] issuer) {
200         X509KeyManager manager = provider.keyManager();
201         if (manager instanceof X509ExtendedKeyManager) {
202             return ((X509ExtendedKeyManager) manager).chooseEngineClientAlias(keyTypes, issuer, engine);
203         }
204         return manager.chooseClientAlias(keyTypes, issuer, null);
205     }
206 
207     private String chooseServerAlias(ReferenceCountedOpenSslEngine engine, String type) {
208         X509KeyManager manager = provider.keyManager();
209         if (manager instanceof X509ExtendedKeyManager) {
210             return ((X509ExtendedKeyManager) manager).chooseEngineServerAlias(type, null, engine);
211         }
212         return manager.chooseServerAlias(type, null, null);
213     }
214 }