View Javadoc
1   /*
2    * Copyright 2014 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.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.buffer.ByteBufUtil;
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.handler.codec.base64.Base64;
23  import io.netty.handler.codec.base64.Base64Dialect;
24  import io.netty.util.NetUtil;
25  import io.netty.util.internal.EmptyArrays;
26  import io.netty.util.internal.StringUtil;
27  import io.netty.util.internal.logging.InternalLogger;
28  import io.netty.util.internal.logging.InternalLoggerFactory;
29  
30  import java.nio.ByteBuffer;
31  import java.nio.ByteOrder;
32  import java.security.KeyManagementException;
33  import java.security.NoSuchAlgorithmException;
34  import java.security.NoSuchProviderException;
35  import java.security.Provider;
36  import java.security.SecureRandom;
37  import java.util.Collections;
38  import java.util.LinkedHashSet;
39  import java.util.List;
40  import java.util.Set;
41  
42  import javax.net.ssl.SSLContext;
43  import javax.net.ssl.SSLHandshakeException;
44  import javax.net.ssl.TrustManager;
45  
46  import static java.util.Arrays.asList;
47  
48  /**
49   * Constants for SSL packets.
50   */
51  final class SslUtils {
52      private static final InternalLogger logger = InternalLoggerFactory.getInstance(SslUtils.class);
53  
54      // See https://tools.ietf.org/html/rfc8446#appendix-B.4
55      static final Set<String> TLSV13_CIPHERS = Collections.unmodifiableSet(new LinkedHashSet<String>(
56              asList("TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256",
57                            "TLS_AES_128_GCM_SHA256", "TLS_AES_128_CCM_8_SHA256",
58                            "TLS_AES_128_CCM_SHA256")));
59  
60      static final short DTLS_1_0 = (short) 0xFEFF;
61      static final short DTLS_1_2 = (short) 0xFEFD;
62      static final short DTLS_1_3 = (short) 0xFEFC;
63      static final short DTLS_RECORD_HEADER_LENGTH = 13;
64  
65      /**
66       * GMSSL Protocol Version
67       */
68      static final int GMSSL_PROTOCOL_VERSION = 0x101;
69  
70      static final String INVALID_CIPHER = "SSL_NULL_WITH_NULL_NULL";
71  
72      /**
73       * change cipher spec
74       */
75      static final int SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC = 20;
76  
77      /**
78       * alert
79       */
80      static final int SSL_CONTENT_TYPE_ALERT = 21;
81  
82      /**
83       * handshake
84       */
85      static final int SSL_CONTENT_TYPE_HANDSHAKE = 22;
86  
87      /**
88       * application data
89       */
90      static final int SSL_CONTENT_TYPE_APPLICATION_DATA = 23;
91  
92      /**
93       * HeartBeat Extension
94       */
95      static final int SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT = 24;
96  
97      /**
98       * the length of the ssl record header (in bytes)
99       */
100     static final int SSL_RECORD_HEADER_LENGTH = 5;
101 
102     /**
103      * Not enough data in buffer to parse the record length
104      */
105     static final int NOT_ENOUGH_DATA = -1;
106 
107     /**
108      * data is not encrypted
109      */
110     static final int NOT_ENCRYPTED = -2;
111 
112     static final String[] DEFAULT_CIPHER_SUITES;
113     static final String[] DEFAULT_TLSV13_CIPHER_SUITES;
114     static final String[] TLSV13_CIPHER_SUITES = { "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384" };
115 
116     // self-signed certificate for netty.io and the matching private-key
117     static final String PROBING_CERT = "-----BEGIN CERTIFICATE-----\n" +
118             "MIICrjCCAZagAwIBAgIIdSvQPv1QAZQwDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAxMLZXhhbXBs\n" +
119             "ZS5jb20wIBcNMTgwNDA2MjIwNjU5WhgPOTk5OTEyMzEyMzU5NTlaMBYxFDASBgNVBAMTC2V4YW1w\n" +
120             "bGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAggbWsmDQ6zNzRZ5AW8E3eoGl\n" +
121             "qWvOBDb5Fs1oBRrVQHuYmVAoaqwDzXYJ0LOwa293AgWEQ1jpcbZ2hpoYQzqEZBTLnFhMrhRFlH6K\n" +
122             "bJND8Y33kZ/iSVBBDuGbdSbJShlM+4WwQ9IAso4MZ4vW3S1iv5fGGpLgbtXRmBf/RU8omN0Gijlv\n" +
123             "WlLWHWijLN8xQtySFuBQ7ssW8RcKAary3pUm6UUQB+Co6lnfti0Tzag8PgjhAJq2Z3wbsGRnP2YS\n" +
124             "vYoaK6qzmHXRYlp/PxrjBAZAmkLJs4YTm/XFF+fkeYx4i9zqHbyone5yerRibsHaXZWLnUL+rFoe\n" +
125             "MdKvr0VS3sGmhQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQADQi441pKmXf9FvUV5EHU4v8nJT9Iq\n" +
126             "yqwsKwXnr7AsUlDGHBD7jGrjAXnG5rGxuNKBQ35wRxJATKrUtyaquFUL6H8O6aGQehiFTk6zmPbe\n" +
127             "12Gu44vqqTgIUxnv3JQJiox8S2hMxsSddpeCmSdvmalvD6WG4NthH6B9ZaBEiep1+0s0RUaBYn73\n" +
128             "I7CCUaAtbjfR6pcJjrFk5ei7uwdQZFSJtkP2z8r7zfeANJddAKFlkaMWn7u+OIVuB4XPooWicObk\n" +
129             "NAHFtP65bocUYnDpTVdiyvn8DdqyZ/EO8n1bBKBzuSLplk2msW4pdgaFgY7Vw/0wzcFXfUXmL1uy\n" +
130             "G8sQD/wx\n" +
131             "-----END CERTIFICATE-----";
132     static final String PROBING_KEY = "-----BEGIN PRIVATE KEY-----\n" +
133             "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCCBtayYNDrM3NFnkBbwTd6gaWp\n" +
134             "a84ENvkWzWgFGtVAe5iZUChqrAPNdgnQs7Brb3cCBYRDWOlxtnaGmhhDOoRkFMucWEyuFEWUfops\n" +
135             "k0PxjfeRn+JJUEEO4Zt1JslKGUz7hbBD0gCyjgxni9bdLWK/l8YakuBu1dGYF/9FTyiY3QaKOW9a\n" +
136             "UtYdaKMs3zFC3JIW4FDuyxbxFwoBqvLelSbpRRAH4KjqWd+2LRPNqDw+COEAmrZnfBuwZGc/ZhK9\n" +
137             "ihorqrOYddFiWn8/GuMEBkCaQsmzhhOb9cUX5+R5jHiL3OodvKid7nJ6tGJuwdpdlYudQv6sWh4x\n" +
138             "0q+vRVLewaaFAgMBAAECggEAP8tPJvFtTxhNJAkCloHz0D0vpDHqQBMgntlkgayqmBqLwhyb18pR\n" +
139             "i0qwgh7HHc7wWqOOQuSqlEnrWRrdcI6TSe8R/sErzfTQNoznKWIPYcI/hskk4sdnQ//Yn9/Jvnsv\n" +
140             "U/BBjOTJxtD+sQbhAl80JcA3R+5sArURQkfzzHOL/YMqzAsn5hTzp7HZCxUqBk3KaHRxV7NefeOE\n" +
141             "xlZuWSmxYWfbFIs4kx19/1t7h8CHQWezw+G60G2VBtSBBxDnhBWvqG6R/wpzJ3nEhPLLY9T+XIHe\n" +
142             "ipzdMOOOUZorfIg7M+pyYPji+ZIZxIpY5OjrOzXHciAjRtr5Y7l99K1CG1LguQKBgQDrQfIMxxtZ\n" +
143             "vxU/1cRmUV9l7pt5bjV5R6byXq178LxPKVYNjdZ840Q0/OpZEVqaT1xKVi35ohP1QfNjxPLlHD+K\n" +
144             "iDAR9z6zkwjIrbwPCnb5kuXy4lpwPcmmmkva25fI7qlpHtbcuQdoBdCfr/KkKaUCMPyY89LCXgEw\n" +
145             "5KTDj64UywKBgQCNfbO+eZLGzhiHhtNJurresCsIGWlInv322gL8CSfBMYl6eNfUTZvUDdFhPISL\n" +
146             "UljKWzXDrjw0ujFSPR0XhUGtiq89H+HUTuPPYv25gVXO+HTgBFZEPl4PpA+BUsSVZy0NddneyqLk\n" +
147             "42Wey9omY9Q8WsdNQS5cbUvy0uG6WFoX7wKBgQDZ1jpW8pa0x2bZsQsm4vo+3G5CRnZlUp+XlWt2\n" +
148             "dDcp5dC0xD1zbs1dc0NcLeGDOTDv9FSl7hok42iHXXq8AygjEm/QcuwwQ1nC2HxmQP5holAiUs4D\n" +
149             "WHM8PWs3wFYPzE459EBoKTxeaeP/uWAn+he8q7d5uWvSZlEcANs/6e77eQKBgD21Ar0hfFfj7mK8\n" +
150             "9E0FeRZBsqK3omkfnhcYgZC11Xa2SgT1yvs2Va2n0RcdM5kncr3eBZav2GYOhhAdwyBM55XuE/sO\n" +
151             "eokDVutNeuZ6d5fqV96TRaRBpvgfTvvRwxZ9hvKF4Vz+9wfn/JvCwANaKmegF6ejs7pvmF3whq2k\n" +
152             "drZVAoGAX5YxQ5XMTD0QbMAl7/6qp6S58xNoVdfCkmkj1ZLKaHKIjS/benkKGlySVQVPexPfnkZx\n" +
153             "p/Vv9yyphBoudiTBS9Uog66ueLYZqpgxlM/6OhYg86Gm3U2ycvMxYjBM1NFiyze21AqAhI+HX+Ot\n" +
154             "mraV2/guSgDgZAhukRZzeQ2RucI=\n" +
155             "-----END PRIVATE KEY-----";
156 
157     private static final boolean TLSV1_3_JDK_SUPPORTED;
158     private static final boolean TLSV1_3_JDK_DEFAULT_ENABLED;
159 
160     static {
161         TLSV1_3_JDK_SUPPORTED = isTLSv13SupportedByJDK0(null);
162         TLSV1_3_JDK_DEFAULT_ENABLED = isTLSv13EnabledByJDK0(null);
163         if (TLSV1_3_JDK_SUPPORTED) {
164             DEFAULT_TLSV13_CIPHER_SUITES = TLSV13_CIPHER_SUITES;
165         } else {
166             DEFAULT_TLSV13_CIPHER_SUITES = EmptyArrays.EMPTY_STRINGS;
167         }
168 
169         Set<String> defaultCiphers = new LinkedHashSet<String>();
170         // GCM (Galois/Counter Mode) requires JDK 8.
171         defaultCiphers.add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384");
172         defaultCiphers.add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256");
173         defaultCiphers.add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
174         defaultCiphers.add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");
175         defaultCiphers.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
176         // AES256 requires JCE unlimited strength jurisdiction policy files.
177         defaultCiphers.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");
178         // GCM (Galois/Counter Mode) requires JDK 8.
179         defaultCiphers.add("TLS_RSA_WITH_AES_128_GCM_SHA256");
180         defaultCiphers.add("TLS_RSA_WITH_AES_128_CBC_SHA");
181         // AES256 requires JCE unlimited strength jurisdiction policy files.
182         defaultCiphers.add("TLS_RSA_WITH_AES_256_CBC_SHA");
183 
184         Collections.addAll(defaultCiphers, DEFAULT_TLSV13_CIPHER_SUITES);
185 
186         DEFAULT_CIPHER_SUITES = defaultCiphers.toArray(EmptyArrays.EMPTY_STRINGS);
187     }
188 
189     /**
190      * Returns {@code true} if the JDK itself supports TLSv1.3, {@code false} otherwise.
191      */
192     static boolean isTLSv13SupportedByJDK(Provider provider) {
193         if (provider == null) {
194             return TLSV1_3_JDK_SUPPORTED;
195         }
196         return isTLSv13SupportedByJDK0(provider);
197     }
198 
199     private static boolean isTLSv13SupportedByJDK0(Provider provider) {
200         try {
201             return arrayContains(newInitContext(provider)
202                     .getSupportedSSLParameters().getProtocols(), SslProtocols.TLS_v1_3);
203         } catch (Throwable cause) {
204             logger.debug("Unable to detect if JDK SSLEngine with provider {} supports TLSv1.3, assuming no",
205                     provider, cause);
206             return false;
207         }
208     }
209 
210     /**
211      * Returns {@code true} if the JDK itself supports TLSv1.3 and enabled it by default, {@code false} otherwise.
212      */
213     static boolean isTLSv13EnabledByJDK(Provider provider) {
214         if (provider == null) {
215             return TLSV1_3_JDK_DEFAULT_ENABLED;
216         }
217         return isTLSv13EnabledByJDK0(provider);
218     }
219 
220     private static boolean isTLSv13EnabledByJDK0(Provider provider) {
221         try {
222             return arrayContains(newInitContext(provider)
223                     .getDefaultSSLParameters().getProtocols(), SslProtocols.TLS_v1_3);
224         } catch (Throwable cause) {
225             logger.debug("Unable to detect if JDK SSLEngine with provider {} enables TLSv1.3 by default," +
226                     " assuming no", provider, cause);
227             return false;
228         }
229     }
230 
231     private static SSLContext newInitContext(Provider provider)
232             throws NoSuchAlgorithmException, KeyManagementException {
233         final SSLContext context;
234         if (provider == null) {
235             context = SSLContext.getInstance("TLS");
236         } else {
237             context = SSLContext.getInstance("TLS", provider);
238         }
239         context.init(null, new TrustManager[0], null);
240         return context;
241     }
242 
243     static SSLContext getSSLContext(Provider provider)
244             throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
245         return getSSLContext(provider, null);
246     }
247 
248     static SSLContext getSSLContext(Provider provider, SecureRandom secureRandom)
249             throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
250         final SSLContext context;
251         if (provider == null) {
252             context = SSLContext.getInstance(getTlsVersion());
253         } else {
254             context = SSLContext.getInstance(getTlsVersion(), provider);
255         }
256         context.init(null, new TrustManager[0], secureRandom);
257         return context;
258     }
259 
260     private static String getTlsVersion() {
261         return TLSV1_3_JDK_SUPPORTED ? SslProtocols.TLS_v1_3 : SslProtocols.TLS_v1_2;
262     }
263 
264     static boolean arrayContains(String[] array, String value) {
265         for (String v: array) {
266             if (value.equals(v)) {
267                 return true;
268             }
269         }
270         return false;
271     }
272 
273     /**
274      * Add elements from {@code names} into {@code enabled} if they are in {@code supported}.
275      */
276     static void addIfSupported(Set<String> supported, List<String> enabled, String... names) {
277         for (String n: names) {
278             if (supported.contains(n)) {
279                 enabled.add(n);
280             }
281         }
282     }
283 
284     static void useFallbackCiphersIfDefaultIsEmpty(List<String> defaultCiphers, Iterable<String> fallbackCiphers) {
285         if (defaultCiphers.isEmpty()) {
286             for (String cipher : fallbackCiphers) {
287                 if (cipher.startsWith("SSL_") || cipher.contains("_RC4_")) {
288                     continue;
289                 }
290                 defaultCiphers.add(cipher);
291             }
292         }
293     }
294 
295     static void useFallbackCiphersIfDefaultIsEmpty(List<String> defaultCiphers, String... fallbackCiphers) {
296         useFallbackCiphersIfDefaultIsEmpty(defaultCiphers, asList(fallbackCiphers));
297     }
298 
299     /**
300      * Converts the given exception to a {@link SSLHandshakeException}, if it isn't already.
301      */
302     static SSLHandshakeException toSSLHandshakeException(Throwable e) {
303         if (e instanceof SSLHandshakeException) {
304             return (SSLHandshakeException) e;
305         }
306 
307         return (SSLHandshakeException) new SSLHandshakeException(e.getMessage()).initCause(e);
308     }
309 
310     /**
311      * Return how much bytes can be read out of the encrypted data. Be aware that this method will not increase
312      * the readerIndex of the given {@link ByteBuf}.
313      *
314      * @param   buffer      The {@link ByteBuf} to read from.
315      * @param   offset      The offset to start from.
316      * @param   probeSSLv2  {@code true} if the input {@code buffer} might be SSLv2.
317      * @return              The length of the encrypted packet that is included in the buffer or
318      *                      {@link #SslUtils#NOT_ENOUGH_DATA} if not enough data is present in the
319      *                      {@link ByteBuf}. This will return {@link SslUtils#NOT_ENCRYPTED} if
320      *                      the given {@link ByteBuf} is not encrypted at all.
321      */
322     static int getEncryptedPacketLength(ByteBuf buffer, int offset, boolean probeSSLv2) {
323         assert offset >= buffer.readerIndex();
324         int remaining = buffer.writerIndex() - offset;
325         if (remaining < SSL_RECORD_HEADER_LENGTH) {
326             return NOT_ENOUGH_DATA;
327         }
328         int packetLength = 0;
329         // SSLv3 or TLS - Check ContentType
330         boolean tls;
331         switch (buffer.getUnsignedByte(offset)) {
332             case SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
333             case SSL_CONTENT_TYPE_ALERT:
334             case SSL_CONTENT_TYPE_HANDSHAKE:
335             case SSL_CONTENT_TYPE_APPLICATION_DATA:
336             case SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT:
337                 tls = true;
338                 break;
339             default:
340                 // SSLv2 or bad data
341                 if (!probeSSLv2) {
342                     return NOT_ENCRYPTED;
343                 }
344                 tls = false;
345         }
346 
347         if (tls) {
348             // SSLv3 or TLS or GMSSLv1.0 or GMSSLv1.1 - Check ProtocolVersion
349             int majorVersion = buffer.getUnsignedByte(offset + 1);
350             int version = buffer.getShort(offset + 1);
351             if (majorVersion == 3 || version == GMSSL_PROTOCOL_VERSION) {
352                 // SSLv3 or TLS or GMSSLv1.0 or GMSSLv1.1
353                 packetLength = unsignedShortBE(buffer, offset + 3) + SSL_RECORD_HEADER_LENGTH;
354                 if (packetLength <= SSL_RECORD_HEADER_LENGTH) {
355                     // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data)
356                     tls = false;
357                 }
358             } else if (version == DTLS_1_0 || version == DTLS_1_2 || version == DTLS_1_3) {
359                 if (remaining < DTLS_RECORD_HEADER_LENGTH) {
360                     return NOT_ENOUGH_DATA;
361                 }
362                 // length is the last 2 bytes in the 13 byte header.
363                 packetLength = unsignedShortBE(buffer, offset + DTLS_RECORD_HEADER_LENGTH - 2) +
364                         DTLS_RECORD_HEADER_LENGTH;
365             } else {
366                 // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data)
367                 tls = false;
368             }
369         }
370 
371         if (!tls) {
372             // SSLv2 or bad data - Check the version
373             int headerLength = (buffer.getUnsignedByte(offset) & 0x80) != 0 ? 2 : 3;
374             int majorVersion = buffer.getUnsignedByte(offset + headerLength + 1);
375             if (majorVersion == 2 || majorVersion == 3) {
376                 // SSLv2
377                 packetLength = headerLength == 2 ?
378                         (shortBE(buffer, offset) & 0x7FFF) + 2 : (shortBE(buffer, offset) & 0x3FFF) + 3;
379                 if (packetLength <= headerLength) {
380                     // If there's no data then consider this package as not encrypted.
381                     return NOT_ENCRYPTED;
382                 }
383             } else {
384                 return NOT_ENCRYPTED;
385             }
386         }
387         return packetLength;
388     }
389 
390     // Reads a big-endian unsigned short integer from the buffer
391     @SuppressWarnings("deprecation")
392     private static int unsignedShortBE(ByteBuf buffer, int offset) {
393         int value = buffer.getUnsignedShort(offset);
394         if (buffer.order() == ByteOrder.LITTLE_ENDIAN) {
395             value = Integer.reverseBytes(value) >>> Short.SIZE;
396         }
397         return value;
398     }
399 
400     // Reads a big-endian short integer from the buffer
401     @SuppressWarnings("deprecation")
402     private static short shortBE(ByteBuf buffer, int offset) {
403         short value = buffer.getShort(offset);
404         if (buffer.order() == ByteOrder.LITTLE_ENDIAN) {
405             value = Short.reverseBytes(value);
406         }
407         return value;
408     }
409 
410     private static short unsignedByte(byte b) {
411         return (short) (b & 0xFF);
412     }
413 
414     // Reads a big-endian unsigned short integer from the buffer
415     private static int unsignedShortBE(ByteBuffer buffer, int offset) {
416         return shortBE(buffer, offset) & 0xFFFF;
417     }
418 
419     // Reads a big-endian short integer from the buffer
420     private static short shortBE(ByteBuffer buffer, int offset) {
421         return buffer.order() == ByteOrder.BIG_ENDIAN ?
422                 buffer.getShort(offset) : ByteBufUtil.swapShort(buffer.getShort(offset));
423     }
424 
425     static int getEncryptedPacketLength(ByteBuffer[] buffers, int offset) {
426         ByteBuffer buffer = buffers[offset];
427 
428         // Check if everything we need is in one ByteBuffer. If so we can make use of the fast-path.
429         if (buffer.remaining() >= SSL_RECORD_HEADER_LENGTH) {
430             return getEncryptedPacketLength(buffer);
431         }
432 
433         // We need to copy 5 bytes into a temporary buffer so we can parse out the packet length easily.
434         ByteBuffer tmp = ByteBuffer.allocate(SSL_RECORD_HEADER_LENGTH);
435 
436         do {
437             buffer = buffers[offset++].duplicate();
438             if (buffer.remaining() > tmp.remaining()) {
439                 buffer.limit(buffer.position() + tmp.remaining());
440             }
441             tmp.put(buffer);
442         } while (tmp.hasRemaining() && offset < buffers.length);
443 
444         // Done, flip the buffer so we can read from it.
445         tmp.flip();
446         return getEncryptedPacketLength(tmp);
447     }
448 
449     private static int getEncryptedPacketLength(ByteBuffer buffer) {
450         int remaining = buffer.remaining();
451         if (remaining < SSL_RECORD_HEADER_LENGTH) {
452             return NOT_ENOUGH_DATA;
453         }
454         int packetLength = 0;
455         int pos = buffer.position();
456 
457         // SSLv3 or TLS - Check ContentType
458         boolean tls;
459         switch (unsignedByte(buffer.get(pos))) {
460             case SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
461             case SSL_CONTENT_TYPE_ALERT:
462             case SSL_CONTENT_TYPE_HANDSHAKE:
463             case SSL_CONTENT_TYPE_APPLICATION_DATA:
464             case SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT:
465                 tls = true;
466                 break;
467             default:
468                 // SSLv2 or bad data
469                 tls = false;
470         }
471 
472         if (tls) {
473             // SSLv3 or TLS or GMSSLv1.0 or GMSSLv1.1 - Check ProtocolVersion
474             int majorVersion = unsignedByte(buffer.get(pos + 1));
475             if (majorVersion == 3 || buffer.getShort(pos + 1) == GMSSL_PROTOCOL_VERSION) {
476                 // SSLv3 or TLS or GMSSLv1.0 or GMSSLv1.1
477                 packetLength = unsignedShortBE(buffer, pos + 3) + SSL_RECORD_HEADER_LENGTH;
478                 if (packetLength <= SSL_RECORD_HEADER_LENGTH) {
479                     // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data)
480                     tls = false;
481                 }
482             } else {
483                 // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data)
484                 tls = false;
485             }
486         }
487 
488         if (!tls) {
489             // SSLv2 or bad data - Check the version
490             int headerLength = (unsignedByte(buffer.get(pos)) & 0x80) != 0 ? 2 : 3;
491             int majorVersion = unsignedByte(buffer.get(pos + headerLength + 1));
492             if (majorVersion == 2 || majorVersion == 3) {
493                 // SSLv2
494                 packetLength = headerLength == 2 ?
495                         (shortBE(buffer, pos) & 0x7FFF) + 2 : (shortBE(buffer, pos) & 0x3FFF) + 3;
496                 if (packetLength <= headerLength) {
497                     // If there's no data then consider this package as not encrypted.
498                     return NOT_ENCRYPTED;
499                 }
500             } else {
501                 return NOT_ENCRYPTED;
502             }
503         }
504         return packetLength;
505     }
506 
507     static void handleHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean notify) {
508         // We have may haven written some parts of data before an exception was thrown so ensure we always flush.
509         // See https://github.com/netty/netty/issues/3900#issuecomment-172481830
510         ctx.flush();
511         if (notify) {
512             ctx.fireUserEventTriggered(new SslHandshakeCompletionEvent(cause));
513         }
514         ctx.close();
515     }
516 
517     /**
518      * Fills the {@link ByteBuf} with zero bytes.
519      */
520     static void zeroout(ByteBuf buffer) {
521         if (!buffer.isReadOnly()) {
522             buffer.setZero(0, buffer.capacity());
523         }
524     }
525 
526     /**
527      * Fills the {@link ByteBuf} with zero bytes and releases it.
528      */
529     static void zerooutAndRelease(ByteBuf buffer) {
530         zeroout(buffer);
531         buffer.release();
532     }
533 
534     /**
535      * Same as {@link Base64#encode(ByteBuf, boolean)} but allows the use of a custom {@link ByteBufAllocator}.
536      *
537      * @see Base64#encode(ByteBuf, boolean)
538      */
539     static ByteBuf toBase64(ByteBufAllocator allocator, ByteBuf src) {
540         ByteBuf dst = Base64.encode(src, src.readerIndex(),
541                 src.readableBytes(), true, Base64Dialect.STANDARD, allocator);
542         src.readerIndex(src.writerIndex());
543         return dst;
544     }
545 
546     /**
547      * Validate that the given hostname can be used in SNI extension.
548      */
549     static boolean isValidHostNameForSNI(String hostname) {
550         // See  https://datatracker.ietf.org/doc/html/rfc6066#section-3
551         return hostname != null &&
552                // SNI HostName has to be a FQDN according to TLS SNI Extension spec (see [1]),
553                // which means that is has to have at least a host name and a domain part.
554                hostname.indexOf('.') > 0 &&
555                !hostname.endsWith(".") && !hostname.startsWith("/") &&
556                !NetUtil.isValidIpV4Address(hostname) &&
557                !NetUtil.isValidIpV6Address(hostname);
558     }
559 
560     /**
561      * Returns {@code true} if the given cipher (in openssl format) is for TLSv1.3, {@code false} otherwise.
562      */
563     static boolean isTLSv13Cipher(String cipher) {
564         // See https://tools.ietf.org/html/rfc8446#appendix-B.4
565         return TLSV13_CIPHERS.contains(cipher);
566     }
567 
568     private SslUtils() {
569     }
570 }