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.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.util.Collections;
37 import java.util.LinkedHashSet;
38 import java.util.List;
39 import java.util.Set;
40
41 import javax.net.ssl.SSLContext;
42 import javax.net.ssl.SSLHandshakeException;
43 import javax.net.ssl.TrustManager;
44
45 import static java.util.Arrays.asList;
46
47
48
49
50 final class SslUtils {
51 private static final InternalLogger logger = InternalLoggerFactory.getInstance(SslUtils.class);
52
53
54 static final Set<String> TLSV13_CIPHERS = Collections.unmodifiableSet(new LinkedHashSet<String>(
55 asList("TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256",
56 "TLS_AES_128_GCM_SHA256", "TLS_AES_128_CCM_8_SHA256",
57 "TLS_AES_128_CCM_SHA256")));
58
59 static final short DTLS_1_0 = (short) 0xFEFF;
60 static final short DTLS_1_2 = (short) 0xFEFD;
61 static final short DTLS_1_3 = (short) 0xFEFC;
62 static final short DTLS_RECORD_HEADER_LENGTH = 13;
63
64
65
66
67 static final int GMSSL_PROTOCOL_VERSION = 0x101;
68
69 static final String INVALID_CIPHER = "SSL_NULL_WITH_NULL_NULL";
70
71
72
73
74 static final int SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC = 20;
75
76
77
78
79 static final int SSL_CONTENT_TYPE_ALERT = 21;
80
81
82
83
84 static final int SSL_CONTENT_TYPE_HANDSHAKE = 22;
85
86
87
88
89 static final int SSL_CONTENT_TYPE_APPLICATION_DATA = 23;
90
91
92
93
94 static final int SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT = 24;
95
96
97
98
99 static final int SSL_RECORD_HEADER_LENGTH = 5;
100
101
102
103
104 static final int NOT_ENOUGH_DATA = -1;
105
106
107
108
109 static final int NOT_ENCRYPTED = -2;
110
111 static final String[] DEFAULT_CIPHER_SUITES;
112 static final String[] DEFAULT_TLSV13_CIPHER_SUITES;
113 static final String[] TLSV13_CIPHER_SUITES = { "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384" };
114
115
116 static final String PROBING_CERT = "-----BEGIN CERTIFICATE-----\n" +
117 "MIICrjCCAZagAwIBAgIIdSvQPv1QAZQwDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAxMLZXhhbXBs\n" +
118 "ZS5jb20wIBcNMTgwNDA2MjIwNjU5WhgPOTk5OTEyMzEyMzU5NTlaMBYxFDASBgNVBAMTC2V4YW1w\n" +
119 "bGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAggbWsmDQ6zNzRZ5AW8E3eoGl\n" +
120 "qWvOBDb5Fs1oBRrVQHuYmVAoaqwDzXYJ0LOwa293AgWEQ1jpcbZ2hpoYQzqEZBTLnFhMrhRFlH6K\n" +
121 "bJND8Y33kZ/iSVBBDuGbdSbJShlM+4WwQ9IAso4MZ4vW3S1iv5fGGpLgbtXRmBf/RU8omN0Gijlv\n" +
122 "WlLWHWijLN8xQtySFuBQ7ssW8RcKAary3pUm6UUQB+Co6lnfti0Tzag8PgjhAJq2Z3wbsGRnP2YS\n" +
123 "vYoaK6qzmHXRYlp/PxrjBAZAmkLJs4YTm/XFF+fkeYx4i9zqHbyone5yerRibsHaXZWLnUL+rFoe\n" +
124 "MdKvr0VS3sGmhQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQADQi441pKmXf9FvUV5EHU4v8nJT9Iq\n" +
125 "yqwsKwXnr7AsUlDGHBD7jGrjAXnG5rGxuNKBQ35wRxJATKrUtyaquFUL6H8O6aGQehiFTk6zmPbe\n" +
126 "12Gu44vqqTgIUxnv3JQJiox8S2hMxsSddpeCmSdvmalvD6WG4NthH6B9ZaBEiep1+0s0RUaBYn73\n" +
127 "I7CCUaAtbjfR6pcJjrFk5ei7uwdQZFSJtkP2z8r7zfeANJddAKFlkaMWn7u+OIVuB4XPooWicObk\n" +
128 "NAHFtP65bocUYnDpTVdiyvn8DdqyZ/EO8n1bBKBzuSLplk2msW4pdgaFgY7Vw/0wzcFXfUXmL1uy\n" +
129 "G8sQD/wx\n" +
130 "-----END CERTIFICATE-----";
131 static final String PROBING_KEY = "-----BEGIN PRIVATE KEY-----\n" +
132 "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCCBtayYNDrM3NFnkBbwTd6gaWp\n" +
133 "a84ENvkWzWgFGtVAe5iZUChqrAPNdgnQs7Brb3cCBYRDWOlxtnaGmhhDOoRkFMucWEyuFEWUfops\n" +
134 "k0PxjfeRn+JJUEEO4Zt1JslKGUz7hbBD0gCyjgxni9bdLWK/l8YakuBu1dGYF/9FTyiY3QaKOW9a\n" +
135 "UtYdaKMs3zFC3JIW4FDuyxbxFwoBqvLelSbpRRAH4KjqWd+2LRPNqDw+COEAmrZnfBuwZGc/ZhK9\n" +
136 "ihorqrOYddFiWn8/GuMEBkCaQsmzhhOb9cUX5+R5jHiL3OodvKid7nJ6tGJuwdpdlYudQv6sWh4x\n" +
137 "0q+vRVLewaaFAgMBAAECggEAP8tPJvFtTxhNJAkCloHz0D0vpDHqQBMgntlkgayqmBqLwhyb18pR\n" +
138 "i0qwgh7HHc7wWqOOQuSqlEnrWRrdcI6TSe8R/sErzfTQNoznKWIPYcI/hskk4sdnQ//Yn9/Jvnsv\n" +
139 "U/BBjOTJxtD+sQbhAl80JcA3R+5sAr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BoudiTBS9Uog66ueLYZqpgxlM/6OhYg86Gm3U2ycvMxYjBM1NFiyze21AqAhI+HX+Ot\n" +
153 "mraV2/guSgDgZAhukRZzeQ2RucI=\n" +
154 "-----END PRIVATE KEY-----";
155
156 private static final boolean TLSV1_3_JDK_SUPPORTED;
157 private static final boolean TLSV1_3_JDK_DEFAULT_ENABLED;
158
159 static {
160 TLSV1_3_JDK_SUPPORTED = isTLSv13SupportedByJDK0(null);
161 TLSV1_3_JDK_DEFAULT_ENABLED = isTLSv13EnabledByJDK0(null);
162 if (TLSV1_3_JDK_SUPPORTED) {
163 DEFAULT_TLSV13_CIPHER_SUITES = TLSV13_CIPHER_SUITES;
164 } else {
165 DEFAULT_TLSV13_CIPHER_SUITES = EmptyArrays.EMPTY_STRINGS;
166 }
167
168 Set<String> defaultCiphers = new LinkedHashSet<String>();
169
170 defaultCiphers.add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384");
171 defaultCiphers.add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256");
172 defaultCiphers.add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
173 defaultCiphers.add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");
174 defaultCiphers.add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
175
176 defaultCiphers.add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");
177
178 defaultCiphers.add("TLS_RSA_WITH_AES_128_GCM_SHA256");
179 defaultCiphers.add("TLS_RSA_WITH_AES_128_CBC_SHA");
180
181 defaultCiphers.add("TLS_RSA_WITH_AES_256_CBC_SHA");
182
183 Collections.addAll(defaultCiphers, DEFAULT_TLSV13_CIPHER_SUITES);
184
185 DEFAULT_CIPHER_SUITES = defaultCiphers.toArray(EmptyArrays.EMPTY_STRINGS);
186 }
187
188
189
190
191 static boolean isTLSv13SupportedByJDK(Provider provider) {
192 if (provider == null) {
193 return TLSV1_3_JDK_SUPPORTED;
194 }
195 return isTLSv13SupportedByJDK0(provider);
196 }
197
198 private static boolean isTLSv13SupportedByJDK0(Provider provider) {
199 try {
200 return arrayContains(newInitContext(provider)
201 .getSupportedSSLParameters().getProtocols(), SslProtocols.TLS_v1_3);
202 } catch (Throwable cause) {
203 logger.debug("Unable to detect if JDK SSLEngine with provider {} supports TLSv1.3, assuming no",
204 provider, cause);
205 return false;
206 }
207 }
208
209
210
211
212 static boolean isTLSv13EnabledByJDK(Provider provider) {
213 if (provider == null) {
214 return TLSV1_3_JDK_DEFAULT_ENABLED;
215 }
216 return isTLSv13EnabledByJDK0(provider);
217 }
218
219 private static boolean isTLSv13EnabledByJDK0(Provider provider) {
220 try {
221 return arrayContains(newInitContext(provider)
222 .getDefaultSSLParameters().getProtocols(), SslProtocols.TLS_v1_3);
223 } catch (Throwable cause) {
224 logger.debug("Unable to detect if JDK SSLEngine with provider {} enables TLSv1.3 by default," +
225 " assuming no", provider, cause);
226 return false;
227 }
228 }
229
230 private static SSLContext newInitContext(Provider provider)
231 throws NoSuchAlgorithmException, KeyManagementException {
232 final SSLContext context;
233 if (provider == null) {
234 context = SSLContext.getInstance("TLS");
235 } else {
236 context = SSLContext.getInstance("TLS", provider);
237 }
238 context.init(null, new TrustManager[0], null);
239 return context;
240 }
241
242 static SSLContext getSSLContext(String provider)
243 throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
244 final SSLContext context;
245 if (StringUtil.isNullOrEmpty(provider)) {
246 context = SSLContext.getInstance(getTlsVersion());
247 } else {
248 context = SSLContext.getInstance(getTlsVersion(), provider);
249 }
250 context.init(null, new TrustManager[0], null);
251 return context;
252 }
253
254 private static String getTlsVersion() {
255 return TLSV1_3_JDK_SUPPORTED ? SslProtocols.TLS_v1_3 : SslProtocols.TLS_v1_2;
256 }
257
258 static boolean arrayContains(String[] array, String value) {
259 for (String v: array) {
260 if (value.equals(v)) {
261 return true;
262 }
263 }
264 return false;
265 }
266
267
268
269
270 static void addIfSupported(Set<String> supported, List<String> enabled, String... names) {
271 for (String n: names) {
272 if (supported.contains(n)) {
273 enabled.add(n);
274 }
275 }
276 }
277
278 static void useFallbackCiphersIfDefaultIsEmpty(List<String> defaultCiphers, Iterable<String> fallbackCiphers) {
279 if (defaultCiphers.isEmpty()) {
280 for (String cipher : fallbackCiphers) {
281 if (cipher.startsWith("SSL_") || cipher.contains("_RC4_")) {
282 continue;
283 }
284 defaultCiphers.add(cipher);
285 }
286 }
287 }
288
289 static void useFallbackCiphersIfDefaultIsEmpty(List<String> defaultCiphers, String... fallbackCiphers) {
290 useFallbackCiphersIfDefaultIsEmpty(defaultCiphers, asList(fallbackCiphers));
291 }
292
293
294
295
296 static SSLHandshakeException toSSLHandshakeException(Throwable e) {
297 if (e instanceof SSLHandshakeException) {
298 return (SSLHandshakeException) e;
299 }
300
301 return (SSLHandshakeException) new SSLHandshakeException(e.getMessage()).initCause(e);
302 }
303
304
305
306
307
308
309
310
311
312
313
314
315
316 static int getEncryptedPacketLength(ByteBuf buffer, int offset, boolean probeSSLv2) {
317 int packetLength = 0;
318
319
320 boolean tls;
321 switch (buffer.getUnsignedByte(offset)) {
322 case SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
323 case SSL_CONTENT_TYPE_ALERT:
324 case SSL_CONTENT_TYPE_HANDSHAKE:
325 case SSL_CONTENT_TYPE_APPLICATION_DATA:
326 case SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT:
327 tls = true;
328 break;
329 default:
330
331 if (!probeSSLv2) {
332 return NOT_ENCRYPTED;
333 }
334 tls = false;
335 }
336
337 if (tls) {
338
339 int majorVersion = buffer.getUnsignedByte(offset + 1);
340 int version = buffer.getShort(offset + 1);
341 if (majorVersion == 3 || version == GMSSL_PROTOCOL_VERSION) {
342
343 packetLength = unsignedShortBE(buffer, offset + 3) + SSL_RECORD_HEADER_LENGTH;
344 if (packetLength <= SSL_RECORD_HEADER_LENGTH) {
345
346 tls = false;
347 }
348 } else if (version == DTLS_1_0 || version == DTLS_1_2 || version == DTLS_1_3) {
349 if (buffer.readableBytes() < offset + DTLS_RECORD_HEADER_LENGTH) {
350 return NOT_ENOUGH_DATA;
351 }
352
353 packetLength = unsignedShortBE(buffer, offset + DTLS_RECORD_HEADER_LENGTH - 2) +
354 DTLS_RECORD_HEADER_LENGTH;
355 } else {
356
357 tls = false;
358 }
359 }
360
361 if (!tls) {
362
363 int headerLength = (buffer.getUnsignedByte(offset) & 0x80) != 0 ? 2 : 3;
364 int majorVersion = buffer.getUnsignedByte(offset + headerLength + 1);
365 if (majorVersion == 2 || majorVersion == 3) {
366
367 packetLength = headerLength == 2 ?
368 (shortBE(buffer, offset) & 0x7FFF) + 2 : (shortBE(buffer, offset) & 0x3FFF) + 3;
369 if (packetLength <= headerLength) {
370 return NOT_ENOUGH_DATA;
371 }
372 } else {
373 return NOT_ENCRYPTED;
374 }
375 }
376 return packetLength;
377 }
378
379
380 @SuppressWarnings("deprecation")
381 private static int unsignedShortBE(ByteBuf buffer, int offset) {
382 int value = buffer.getUnsignedShort(offset);
383 if (buffer.order() == ByteOrder.LITTLE_ENDIAN) {
384 value = Integer.reverseBytes(value) >>> Short.SIZE;
385 }
386 return value;
387 }
388
389
390 @SuppressWarnings("deprecation")
391 private static short shortBE(ByteBuf buffer, int offset) {
392 short value = buffer.getShort(offset);
393 if (buffer.order() == ByteOrder.LITTLE_ENDIAN) {
394 value = Short.reverseBytes(value);
395 }
396 return value;
397 }
398
399 private static short unsignedByte(byte b) {
400 return (short) (b & 0xFF);
401 }
402
403
404 private static int unsignedShortBE(ByteBuffer buffer, int offset) {
405 return shortBE(buffer, offset) & 0xFFFF;
406 }
407
408
409 private static short shortBE(ByteBuffer buffer, int offset) {
410 return buffer.order() == ByteOrder.BIG_ENDIAN ?
411 buffer.getShort(offset) : ByteBufUtil.swapShort(buffer.getShort(offset));
412 }
413
414 static int getEncryptedPacketLength(ByteBuffer[] buffers, int offset) {
415 ByteBuffer buffer = buffers[offset];
416
417
418 if (buffer.remaining() >= SSL_RECORD_HEADER_LENGTH) {
419 return getEncryptedPacketLength(buffer);
420 }
421
422
423 ByteBuffer tmp = ByteBuffer.allocate(5);
424
425 do {
426 buffer = buffers[offset++].duplicate();
427 if (buffer.remaining() > tmp.remaining()) {
428 buffer.limit(buffer.position() + tmp.remaining());
429 }
430 tmp.put(buffer);
431 } while (tmp.hasRemaining());
432
433
434 tmp.flip();
435 return getEncryptedPacketLength(tmp);
436 }
437
438 private static int getEncryptedPacketLength(ByteBuffer buffer) {
439 int packetLength = 0;
440 int pos = buffer.position();
441
442 boolean tls;
443 switch (unsignedByte(buffer.get(pos))) {
444 case SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
445 case SSL_CONTENT_TYPE_ALERT:
446 case SSL_CONTENT_TYPE_HANDSHAKE:
447 case SSL_CONTENT_TYPE_APPLICATION_DATA:
448 case SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT:
449 tls = true;
450 break;
451 default:
452
453 tls = false;
454 }
455
456 if (tls) {
457
458 int majorVersion = unsignedByte(buffer.get(pos + 1));
459 if (majorVersion == 3 || buffer.getShort(pos + 1) == GMSSL_PROTOCOL_VERSION) {
460
461 packetLength = unsignedShortBE(buffer, pos + 3) + SSL_RECORD_HEADER_LENGTH;
462 if (packetLength <= SSL_RECORD_HEADER_LENGTH) {
463
464 tls = false;
465 }
466 } else {
467
468 tls = false;
469 }
470 }
471
472 if (!tls) {
473
474 int headerLength = (unsignedByte(buffer.get(pos)) & 0x80) != 0 ? 2 : 3;
475 int majorVersion = unsignedByte(buffer.get(pos + headerLength + 1));
476 if (majorVersion == 2 || majorVersion == 3) {
477
478 packetLength = headerLength == 2 ?
479 (shortBE(buffer, pos) & 0x7FFF) + 2 : (shortBE(buffer, pos) & 0x3FFF) + 3;
480 if (packetLength <= headerLength) {
481 return NOT_ENOUGH_DATA;
482 }
483 } else {
484 return NOT_ENCRYPTED;
485 }
486 }
487 return packetLength;
488 }
489
490 static void handleHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean notify) {
491
492
493 ctx.flush();
494 if (notify) {
495 ctx.fireUserEventTriggered(new SslHandshakeCompletionEvent(cause));
496 }
497 ctx.close();
498 }
499
500
501
502
503 static void zeroout(ByteBuf buffer) {
504 if (!buffer.isReadOnly()) {
505 buffer.setZero(0, buffer.capacity());
506 }
507 }
508
509
510
511
512 static void zerooutAndRelease(ByteBuf buffer) {
513 zeroout(buffer);
514 buffer.release();
515 }
516
517
518
519
520
521
522 static ByteBuf toBase64(ByteBufAllocator allocator, ByteBuf src) {
523 ByteBuf dst = Base64.encode(src, src.readerIndex(),
524 src.readableBytes(), true, Base64Dialect.STANDARD, allocator);
525 src.readerIndex(src.writerIndex());
526 return dst;
527 }
528
529
530
531
532 static boolean isValidHostNameForSNI(String hostname) {
533
534 return hostname != null &&
535
536
537 hostname.indexOf('.') > 0 &&
538 !hostname.endsWith(".") && !hostname.startsWith("/") &&
539 !NetUtil.isValidIpV4Address(hostname) &&
540 !NetUtil.isValidIpV6Address(hostname);
541 }
542
543
544
545
546 static boolean isTLSv13Cipher(String cipher) {
547
548 return TLSV13_CIPHERS.contains(cipher);
549 }
550
551 private SslUtils() {
552 }
553 }