View Javadoc
1   /*
2    * Copyright 2026 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.SecureObjectIdentityHash;
19  
20  import javax.net.ssl.KeyManager;
21  import javax.net.ssl.KeyManagerFactory;
22  import javax.net.ssl.TrustManager;
23  import javax.net.ssl.TrustManagerFactory;
24  import java.nio.ByteBuffer;
25  import java.security.MessageDigest;
26  import java.security.NoSuchAlgorithmException;
27  import java.security.SecureRandom;
28  import java.security.cert.CertificateEncodingException;
29  import java.security.cert.X509Certificate;
30  import java.util.Objects;
31  
32  /**
33   * Derives the {@code session_id_context} for a server context from the material that determines which clients
34   * it accepts.
35   * The session discriminating material is the {@link ClientAuth} mode, the certificate chain it presents,
36   * the certificates it trusts, and any installed credentials.
37   * <p>
38   * The {@code session_id_context} scopes session resumption: a session (and therefore its client-authentication
39   * state) can only be resumed by a context that uses the same {@code session_id_context}. It must hence differ
40   * between contexts which, when sharing a session cache or session-ticket keys, must not accept each others
41   * sessions (for example because they use a different {@link ClientAuth} mode or trust configuration), but it
42   * should be the same for contexts that are configured identically (for example on different nodes of a cluster
43   * that share session-ticket keys), so resumption keeps working between them.
44   * See <a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set_session_id_context.html">
45   * SSL_CTX_set_session_id_context</a> and
46   * <a href="https://github.com/netty/netty/security/advisories/GHSA-6xv6-9mgg-mfvc">GHSA-6xv6-9mgg-mfvc</a>.
47   * <p>
48   * This class securely computes distinct session context identifiers from the discriminating material,
49   * such that resumption is allowed for connections to the same JVM, with optional support for deterministic cross-JVM
50   * session context ids.
51   */
52  public final class SessionIdContextBuilder {
53      private final SecureObjectIdentityHash identityHashes;
54  
55      // When set, use this explicitly and directly, instead of computing a value.
56      private byte[] sessionIdContextOverride;
57  
58      // Common fields:
59      private byte[] seed;
60      private ClientAuth clientAuth;
61      private OpenSslCredential[] credentials;
62  
63      // At most one will be set:
64      private KeyManager keyManagerInstance;
65      private KeyManagerFactory keyManagerFactoryInstance;
66      private X509Certificate[] keyCertChainDecoded;
67  
68      // At most one will be set:
69      private TrustManager trustManagerInstance;
70      private TrustManagerFactory trustManagerFactoryInstance;
71      private X509Certificate[] trustedCertsDecoded;
72  
73      public SessionIdContextBuilder(SecureObjectIdentityHash identityHashes) {
74          this.identityHashes = Objects.requireNonNull(identityHashes, "identityHashes");
75      }
76  
77      private SessionIdContextBuilder() {
78          identityHashes = null;
79      }
80  
81      public static SessionIdContextBuilder randomSessionIdContext() {
82          return new SessionIdContextBuilder()
83              .setSessionIdContextOverride(RandomHolder.getRandomSessionIdContext());
84      }
85  
86      public SessionIdContextBuilder setSessionIdContextOverride(byte[] override) {
87          if (override != null && override.length > 32) {
88              throw new IllegalArgumentException("Session Id Context can be at most 32 bytes");
89          }
90          this.sessionIdContextOverride = override;
91          return this;
92      }
93  
94      public SessionIdContextBuilder setSeed(byte[] seed) {
95          this.seed = seed;
96          return this;
97      }
98  
99      public SessionIdContextBuilder setClientAuth(ClientAuth clientAuth) {
100         this.clientAuth = clientAuth;
101         return this;
102     }
103 
104     public SessionIdContextBuilder setCredentials(OpenSslCredential[] credentials) {
105         this.credentials = credentials;
106         return this;
107     }
108 
109     /**
110      * Use the identity of the given {@link KeyManager} as the local identity material.
111      * {@code null} clears all local identity material.
112      */
113     public SessionIdContextBuilder setKeyManager(KeyManager keyManager) {
114         keyManagerInstance = keyManager;
115         keyManagerFactoryInstance = null;
116         keyCertChainDecoded = null;
117         return this;
118     }
119 
120     /**
121      * Use the identity of the given {@link KeyManagerFactory} as the local identity material.
122      * {@code null} clears all local identity material.
123      */
124     public SessionIdContextBuilder setKeyManagerFactory(KeyManagerFactory keyManagerFactory) {
125         keyManagerFactoryInstance = keyManagerFactory;
126         keyManagerInstance = null;
127         keyCertChainDecoded = null;
128         return this;
129     }
130 
131     /**
132      * Use the given certificate chain as the local identity material.
133      * The private key is deliberately not part of the digest: the chain already identifies it, and digesting
134      * secret material would put a stable fingerprint of it into every session.
135      * {@code null} clears all local identity material.
136      * <p>
137      * The array is not copied, so the caller must not modify it afterwards.
138      */
139     public SessionIdContextBuilder setKeyCertificateChain(X509Certificate[] chain) {
140         keyCertChainDecoded = chain;
141         keyManagerInstance = null;
142         keyManagerFactoryInstance = null;
143         return this;
144     }
145 
146     /**
147      * Use the identity of the given {@link TrustManager} as the trust material.
148      * {@code null} clears all trust material.
149      */
150     public SessionIdContextBuilder setTrustManager(TrustManager trustManager) {
151         trustManagerInstance = trustManager;
152         trustManagerFactoryInstance = null;
153         trustedCertsDecoded = null;
154         return this;
155     }
156 
157     /**
158      * Use the identity of the given {@link TrustManagerFactory} as the trust material.
159      * {@code null} clears all trust material.
160      */
161     public SessionIdContextBuilder setTrustManagerFactory(TrustManagerFactory trustManagerFactory) {
162         trustManagerFactoryInstance = trustManagerFactory;
163         trustManagerInstance = null;
164         trustedCertsDecoded = null;
165         return this;
166     }
167 
168     /**
169      * Use the given certificates as the trust material.
170      * {@code null} clears all trust material.
171      * <p>
172      * The array is not copied, so the caller must not modify it afterwards.
173      */
174     public SessionIdContextBuilder setTrustedCertificates(X509Certificate[] trustedCertificates) {
175         trustedCertsDecoded = trustedCertificates;
176         trustManagerInstance = null;
177         trustManagerFactoryInstance = null;
178         return this;
179     }
180 
181     public byte[] build() {
182         if (sessionIdContextOverride != null) {
183             return sessionIdContextOverride;
184         }
185 
186         final MessageDigest digest;
187         try {
188             digest = MessageDigest.getInstance("SHA-256");
189         } catch (NoSuchAlgorithmException e) {
190             // Every Java implementation is required to support SHA-256.
191             throw new IllegalStateException(e);
192         }
193 
194         ByteBuffer intCarry = ByteBuffer.allocate(Integer.BYTES);
195         update(digest, intCarry, seed);
196         update(digest, intCarry, clientAuth == null ? -1 : clientAuth.ordinal());
197 
198         // Credentials domain
199         if (credentials != null) {
200             update(digest, intCarry, credentials.length);
201             for (OpenSslCredential credential : credentials) {
202                 // All identity hashes are fixed-length, so length prefix is not needed.
203                 identityHashes.updateWithIdentityHash(digest, credential);
204             }
205         } else {
206             update(digest, intCarry, 0); // Empty array and null are equivalent.
207         }
208 
209         // Local identity domain
210         update(digest, intCarry, -2);
211         if (keyManagerFactoryInstance != null) {
212             identityHashes.updateWithIdentityHash(digest, keyManagerFactoryInstance);
213         } else if (keyManagerInstance != null) {
214             identityHashes.updateWithIdentityHash(digest, keyManagerInstance);
215         } else if (keyCertChainDecoded != null) {
216             update(digest, intCarry, keyCertChainDecoded);
217         }
218 
219         // Trust domain
220         update(digest, intCarry, -3);
221         if (trustManagerFactoryInstance != null) {
222             identityHashes.updateWithIdentityHash(digest, trustManagerFactoryInstance);
223         } else if (trustManagerInstance != null) {
224             identityHashes.updateWithIdentityHash(digest, trustManagerInstance);
225         } else if (trustedCertsDecoded != null) {
226             update(digest, intCarry, trustedCertsDecoded);
227         }
228 
229         return digest.digest();
230     }
231 
232     private void update(MessageDigest digest, ByteBuffer size, byte[] value) {
233         if (value == null) {
234             size.putInt(0, -1);
235             digest.update(size.array());
236         } else {
237             size.putInt(0, value.length);
238             digest.update(size.array());
239             digest.update(value);
240         }
241     }
242 
243     private void update(MessageDigest digest, ByteBuffer intBuf, int intValue) {
244         intBuf.putInt(0, intValue);
245         digest.update(intBuf.array());
246     }
247 
248     private void update(MessageDigest digest, ByteBuffer intCarry, X509Certificate[] certs) {
249         if (certs == null) {
250             update(digest, intCarry, -1);
251         } else {
252             update(digest, intCarry, certs.length);
253             for (X509Certificate cert : certs) {
254                 if (cert == null) {
255                     update(digest, intCarry, -1);
256                 } else {
257                     try {
258                         update(digest, intCarry, cert.getEncoded());
259                     } catch (CertificateEncodingException e) {
260                         identityHashes.updateWithIdentityHash(digest, cert);
261                     }
262                 }
263             }
264         }
265     }
266 
267     private static final class RandomHolder {
268         private static final SecureRandom RNG = new SecureRandom();
269 
270         static byte[] getRandomSessionIdContext() {
271             byte[] ctx = new byte[32];
272             RNG.nextBytes(ctx);
273             return ctx;
274         }
275     }
276 }