Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/javax/net/ssl/templates/SSLExplorer.java
41152 views
1
/*
2
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
import java.nio.ByteBuffer;
27
import java.nio.BufferUnderflowException;
28
import java.io.IOException;
29
import javax.net.ssl.*;
30
import java.util.*;
31
32
/**
33
* Instances of this class acts as an explorer of the network data of an
34
* SSL/TLS connection.
35
*/
36
public final class SSLExplorer {
37
38
// Private constructor prevents construction outside this class.
39
private SSLExplorer() {
40
}
41
42
/**
43
* The header size of TLS/SSL records.
44
* <P>
45
* The value of this constant is {@value}.
46
*/
47
public final static int RECORD_HEADER_SIZE = 0x05;
48
49
/**
50
* Returns the required number of bytes in the {@code source}
51
* {@link ByteBuffer} necessary to explore SSL/TLS connection.
52
* <P>
53
* This method tries to parse as few bytes as possible from
54
* {@code source} byte buffer to get the length of an
55
* SSL/TLS record.
56
* <P>
57
* This method accesses the {@code source} parameter in read-only
58
* mode, and does not update the buffer's properties such as capacity,
59
* limit, position, and mark values.
60
*
61
* @param source
62
* a {@link ByteBuffer} containing
63
* inbound or outbound network data for an SSL/TLS connection.
64
* @throws BufferUnderflowException if less than {@code RECORD_HEADER_SIZE}
65
* bytes remaining in {@code source}
66
* @return the required size in byte to explore an SSL/TLS connection
67
*/
68
public final static int getRequiredSize(ByteBuffer source) {
69
70
ByteBuffer input = source.duplicate();
71
72
// Do we have a complete header?
73
if (input.remaining() < RECORD_HEADER_SIZE) {
74
throw new BufferUnderflowException();
75
}
76
77
// Is it a handshake message?
78
byte firstByte = input.get();
79
byte secondByte = input.get();
80
byte thirdByte = input.get();
81
if ((firstByte & 0x80) != 0 && thirdByte == 0x01) {
82
// looks like a V2ClientHello
83
// return (((firstByte & 0x7F) << 8) | (secondByte & 0xFF)) + 2;
84
return RECORD_HEADER_SIZE; // Only need the header fields
85
} else {
86
return (((input.get() & 0xFF) << 8) | (input.get() & 0xFF)) + 5;
87
}
88
}
89
90
/**
91
* Returns the required number of bytes in the {@code source} byte array
92
* necessary to explore SSL/TLS connection.
93
* <P>
94
* This method tries to parse as few bytes as possible from
95
* {@code source} byte array to get the length of an
96
* SSL/TLS record.
97
*
98
* @param source
99
* a byte array containing inbound or outbound network data for
100
* an SSL/TLS connection.
101
* @param offset
102
* the start offset in array {@code source} at which the
103
* network data is read from.
104
* @param length
105
* the maximum number of bytes to read.
106
*
107
* @throws BufferUnderflowException if less than {@code RECORD_HEADER_SIZE}
108
* bytes remaining in {@code source}
109
* @return the required size in byte to explore an SSL/TLS connection
110
*/
111
public final static int getRequiredSize(byte[] source,
112
int offset, int length) throws IOException {
113
114
ByteBuffer byteBuffer =
115
ByteBuffer.wrap(source, offset, length).asReadOnlyBuffer();
116
return getRequiredSize(byteBuffer);
117
}
118
119
/**
120
* Launch and explore the security capabilities from byte buffer.
121
* <P>
122
* This method tries to parse as few records as possible from
123
* {@code source} byte buffer to get the {@link SSLCapabilities}
124
* of an SSL/TLS connection.
125
* <P>
126
* Please NOTE that this method must be called before any handshaking
127
* occurs. The behavior of this method is not defined in this release
128
* if the handshake has begun, or has completed.
129
* <P>
130
* This method accesses the {@code source} parameter in read-only
131
* mode, and does not update the buffer's properties such as capacity,
132
* limit, position, and mark values.
133
*
134
* @param source
135
* a {@link ByteBuffer} containing
136
* inbound or outbound network data for an SSL/TLS connection.
137
*
138
* @throws IOException on network data error
139
* @throws BufferUnderflowException if not enough source bytes available
140
* to make a complete exploration.
141
*
142
* @return the explored {@link SSLCapabilities} of the SSL/TLS
143
* connection
144
*/
145
public final static SSLCapabilities explore(ByteBuffer source)
146
throws IOException {
147
148
ByteBuffer input = source.duplicate();
149
150
// Do we have a complete header?
151
if (input.remaining() < RECORD_HEADER_SIZE) {
152
throw new BufferUnderflowException();
153
}
154
155
// Is it a handshake message?
156
byte firstByte = input.get();
157
byte secondByte = input.get();
158
byte thirdByte = input.get();
159
if ((firstByte & 0x80) != 0 && thirdByte == 0x01) {
160
// looks like a V2ClientHello
161
return exploreV2HelloRecord(input,
162
firstByte, secondByte, thirdByte);
163
} else if (firstByte == 22) { // 22: handshake record
164
return exploreTLSRecord(input,
165
firstByte, secondByte, thirdByte);
166
} else {
167
throw new SSLException("Not handshake record");
168
}
169
}
170
171
/**
172
* Launch and explore the security capabilities from byte array.
173
* <P>
174
* Please NOTE that this method must be called before any handshaking
175
* occurs. The behavior of this method is not defined in this release
176
* if the handshake has begun, or has completed. Once handshake has
177
* begun, or has completed, the security capabilities can not and
178
* should not be launched with this method.
179
*
180
* @param source
181
* a byte array containing inbound or outbound network data for
182
* an SSL/TLS connection.
183
* @param offset
184
* the start offset in array {@code source} at which the
185
* network data is read from.
186
* @param length
187
* the maximum number of bytes to read.
188
*
189
* @throws IOException on network data error
190
* @throws BufferUnderflowException if not enough source bytes available
191
* to make a complete exploration.
192
* @return the explored {@link SSLCapabilities} of the SSL/TLS
193
* connection
194
*
195
* @see #explore(ByteBuffer)
196
*/
197
public final static SSLCapabilities explore(byte[] source,
198
int offset, int length) throws IOException {
199
ByteBuffer byteBuffer =
200
ByteBuffer.wrap(source, offset, length).asReadOnlyBuffer();
201
return explore(byteBuffer);
202
}
203
204
/*
205
* uint8 V2CipherSpec[3];
206
* struct {
207
* uint16 msg_length; // The highest bit MUST be 1;
208
* // the remaining bits contain the length
209
* // of the following data in bytes.
210
* uint8 msg_type; // MUST be 1
211
* Version version;
212
* uint16 cipher_spec_length; // It cannot be zero and MUST be a
213
* // multiple of the V2CipherSpec length.
214
* uint16 session_id_length; // This field MUST be empty.
215
* uint16 challenge_length; // SHOULD use a 32-byte challenge
216
* V2CipherSpec cipher_specs[V2ClientHello.cipher_spec_length];
217
* opaque session_id[V2ClientHello.session_id_length];
218
* opaque challenge[V2ClientHello.challenge_length;
219
* } V2ClientHello;
220
*/
221
private static SSLCapabilities exploreV2HelloRecord(
222
ByteBuffer input, byte firstByte, byte secondByte,
223
byte thirdByte) throws IOException {
224
225
// We only need the header. We have already had enough source bytes.
226
// int recordLength = (firstByte & 0x7F) << 8) | (secondByte & 0xFF);
227
try {
228
// Is it a V2ClientHello?
229
if (thirdByte != 0x01) {
230
throw new SSLException(
231
"Unsupported or Unrecognized SSL record");
232
}
233
234
// What's the hello version?
235
byte helloVersionMajor = input.get();
236
byte helloVersionMinor = input.get();
237
238
// 0x00: major version of SSLv20
239
// 0x02: minor version of SSLv20
240
//
241
// SNIServerName is an extension, SSLv20 doesn't support extension.
242
return new SSLCapabilitiesImpl((byte)0x00, (byte)0x02,
243
helloVersionMajor, helloVersionMinor,
244
Collections.<SNIServerName>emptyList());
245
} catch (BufferUnderflowException bufe) {
246
throw new SSLProtocolException(
247
"Invalid handshake record");
248
}
249
}
250
251
/*
252
* struct {
253
* uint8 major;
254
* uint8 minor;
255
* } ProtocolVersion;
256
*
257
* enum {
258
* change_cipher_spec(20), alert(21), handshake(22),
259
* application_data(23), (255)
260
* } ContentType;
261
*
262
* struct {
263
* ContentType type;
264
* ProtocolVersion version;
265
* uint16 length;
266
* opaque fragment[TLSPlaintext.length];
267
* } TLSPlaintext;
268
*/
269
private static SSLCapabilities exploreTLSRecord(
270
ByteBuffer input, byte firstByte, byte secondByte,
271
byte thirdByte) throws IOException {
272
273
// Is it a handshake message?
274
if (firstByte != 22) { // 22: handshake record
275
throw new SSLException("Not handshake record");
276
}
277
278
// We need the record version to construct SSLCapabilities.
279
byte recordMajorVersion = secondByte;
280
byte recordMinorVersion = thirdByte;
281
282
// Is there enough data for a full record?
283
int recordLength = getInt16(input);
284
if (recordLength > input.remaining()) {
285
throw new BufferUnderflowException();
286
}
287
288
// We have already had enough source bytes.
289
try {
290
return exploreHandshake(input,
291
recordMajorVersion, recordMinorVersion, recordLength);
292
} catch (BufferUnderflowException bufe) {
293
throw new SSLProtocolException(
294
"Invalid handshake record");
295
}
296
}
297
298
/*
299
* enum {
300
* hello_request(0), client_hello(1), server_hello(2),
301
* certificate(11), server_key_exchange (12),
302
* certificate_request(13), server_hello_done(14),
303
* certificate_verify(15), client_key_exchange(16),
304
* finished(20)
305
* (255)
306
* } HandshakeType;
307
*
308
* struct {
309
* HandshakeType msg_type;
310
* uint24 length;
311
* select (HandshakeType) {
312
* case hello_request: HelloRequest;
313
* case client_hello: ClientHello;
314
* case server_hello: ServerHello;
315
* case certificate: Certificate;
316
* case server_key_exchange: ServerKeyExchange;
317
* case certificate_request: CertificateRequest;
318
* case server_hello_done: ServerHelloDone;
319
* case certificate_verify: CertificateVerify;
320
* case client_key_exchange: ClientKeyExchange;
321
* case finished: Finished;
322
* } body;
323
* } Handshake;
324
*/
325
private static SSLCapabilities exploreHandshake(
326
ByteBuffer input, byte recordMajorVersion,
327
byte recordMinorVersion, int recordLength) throws IOException {
328
329
// What is the handshake type?
330
byte handshakeType = input.get();
331
if (handshakeType != 0x01) { // 0x01: client_hello message
332
throw new IllegalStateException("Not initial handshaking");
333
}
334
335
// What is the handshake body length?
336
int handshakeLength = getInt24(input);
337
338
// Theoretically, a single handshake message might span multiple
339
// records, but in practice this does not occur.
340
if (handshakeLength > (recordLength - 4)) { // 4: handshake header size
341
throw new SSLException("Handshake message spans multiple records");
342
}
343
344
input = input.duplicate();
345
input.limit(handshakeLength + input.position());
346
return exploreClientHello(input,
347
recordMajorVersion, recordMinorVersion);
348
}
349
350
/*
351
* struct {
352
* uint32 gmt_unix_time;
353
* opaque random_bytes[28];
354
* } Random;
355
*
356
* opaque SessionID<0..32>;
357
*
358
* uint8 CipherSuite[2];
359
*
360
* enum { null(0), (255) } CompressionMethod;
361
*
362
* struct {
363
* ProtocolVersion client_version;
364
* Random random;
365
* SessionID session_id;
366
* CipherSuite cipher_suites<2..2^16-2>;
367
* CompressionMethod compression_methods<1..2^8-1>;
368
* select (extensions_present) {
369
* case false:
370
* struct {};
371
* case true:
372
* Extension extensions<0..2^16-1>;
373
* };
374
* } ClientHello;
375
*/
376
private static SSLCapabilities exploreClientHello(
377
ByteBuffer input,
378
byte recordMajorVersion,
379
byte recordMinorVersion) throws IOException {
380
381
List<SNIServerName> snList = Collections.<SNIServerName>emptyList();
382
383
// client version
384
byte helloMajorVersion = input.get();
385
byte helloMinorVersion = input.get();
386
387
// ignore random
388
int position = input.position();
389
input.position(position + 32); // 32: the length of Random
390
391
// ignore session id
392
ignoreByteVector8(input);
393
394
// ignore cipher_suites
395
ignoreByteVector16(input);
396
397
// ignore compression methods
398
ignoreByteVector8(input);
399
400
if (input.remaining() > 0) {
401
snList = exploreExtensions(input);
402
}
403
404
return new SSLCapabilitiesImpl(
405
recordMajorVersion, recordMinorVersion,
406
helloMajorVersion, helloMinorVersion, snList);
407
}
408
409
/*
410
* struct {
411
* ExtensionType extension_type;
412
* opaque extension_data<0..2^16-1>;
413
* } Extension;
414
*
415
* enum {
416
* server_name(0), max_fragment_length(1),
417
* client_certificate_url(2), trusted_ca_keys(3),
418
* truncated_hmac(4), status_request(5), (65535)
419
* } ExtensionType;
420
*/
421
private static List<SNIServerName> exploreExtensions(ByteBuffer input)
422
throws IOException {
423
424
int length = getInt16(input); // length of extensions
425
while (length > 0) {
426
int extType = getInt16(input); // extenson type
427
int extLen = getInt16(input); // length of extension data
428
429
if (extType == 0x00) { // 0x00: type of server name indication
430
return exploreSNIExt(input, extLen);
431
} else { // ignore other extensions
432
ignoreByteVector(input, extLen);
433
}
434
435
length -= extLen + 4;
436
}
437
438
return Collections.<SNIServerName>emptyList();
439
}
440
441
/*
442
* struct {
443
* NameType name_type;
444
* select (name_type) {
445
* case host_name: HostName;
446
* } name;
447
* } ServerName;
448
*
449
* enum {
450
* host_name(0), (255)
451
* } NameType;
452
*
453
* opaque HostName<1..2^16-1>;
454
*
455
* struct {
456
* ServerName server_name_list<1..2^16-1>
457
* } ServerNameList;
458
*/
459
private static List<SNIServerName> exploreSNIExt(ByteBuffer input,
460
int extLen) throws IOException {
461
462
Map<Integer, SNIServerName> sniMap = new LinkedHashMap<>();
463
464
int remains = extLen;
465
if (extLen >= 2) { // "server_name" extension in ClientHello
466
int listLen = getInt16(input); // length of server_name_list
467
if (listLen == 0 || listLen + 2 != extLen) {
468
throw new SSLProtocolException(
469
"Invalid server name indication extension");
470
}
471
472
remains -= 2; // 0x02: the length field of server_name_list
473
while (remains > 0) {
474
int code = getInt8(input); // name_type
475
int snLen = getInt16(input); // length field of server name
476
if (snLen > remains) {
477
throw new SSLProtocolException(
478
"Not enough data to fill declared vector size");
479
}
480
byte[] encoded = new byte[snLen];
481
input.get(encoded);
482
483
SNIServerName serverName;
484
switch (code) {
485
case StandardConstants.SNI_HOST_NAME:
486
if (encoded.length == 0) {
487
throw new SSLProtocolException(
488
"Empty HostName in server name indication");
489
}
490
serverName = new SNIHostName(encoded);
491
break;
492
default:
493
serverName = new UnknownServerName(code, encoded);
494
}
495
// check for duplicated server name type
496
if (sniMap.put(serverName.getType(), serverName) != null) {
497
throw new SSLProtocolException(
498
"Duplicated server name of type " +
499
serverName.getType());
500
}
501
502
remains -= encoded.length + 3; // NameType: 1 byte
503
// HostName length: 2 bytes
504
}
505
} else if (extLen == 0) { // "server_name" extension in ServerHello
506
throw new SSLProtocolException(
507
"Not server name indication extension in client");
508
}
509
510
if (remains != 0) {
511
throw new SSLProtocolException(
512
"Invalid server name indication extension");
513
}
514
515
return Collections.<SNIServerName>unmodifiableList(
516
new ArrayList<>(sniMap.values()));
517
}
518
519
private static int getInt8(ByteBuffer input) {
520
return input.get();
521
}
522
523
private static int getInt16(ByteBuffer input) {
524
return ((input.get() & 0xFF) << 8) | (input.get() & 0xFF);
525
}
526
527
private static int getInt24(ByteBuffer input) {
528
return ((input.get() & 0xFF) << 16) | ((input.get() & 0xFF) << 8) |
529
(input.get() & 0xFF);
530
}
531
532
private static void ignoreByteVector8(ByteBuffer input) {
533
ignoreByteVector(input, getInt8(input));
534
}
535
536
private static void ignoreByteVector16(ByteBuffer input) {
537
ignoreByteVector(input, getInt16(input));
538
}
539
540
private static void ignoreByteVector24(ByteBuffer input) {
541
ignoreByteVector(input, getInt24(input));
542
}
543
544
private static void ignoreByteVector(ByteBuffer input, int length) {
545
if (length != 0) {
546
int position = input.position();
547
input.position(position + length);
548
}
549
}
550
551
private static class UnknownServerName extends SNIServerName {
552
UnknownServerName(int code, byte[] encoded) {
553
super(code, encoded);
554
}
555
}
556
557
private static final class SSLCapabilitiesImpl extends SSLCapabilities {
558
private final static Map<Integer, String> versionMap = new HashMap<>(5);
559
560
private final String recordVersion;
561
private final String helloVersion;
562
List<SNIServerName> sniNames;
563
564
static {
565
versionMap.put(0x0002, "SSLv2Hello");
566
versionMap.put(0x0300, "SSLv3");
567
versionMap.put(0x0301, "TLSv1");
568
versionMap.put(0x0302, "TLSv1.1");
569
versionMap.put(0x0303, "TLSv1.2");
570
}
571
572
SSLCapabilitiesImpl(byte recordMajorVersion, byte recordMinorVersion,
573
byte helloMajorVersion, byte helloMinorVersion,
574
List<SNIServerName> sniNames) {
575
576
int version = (recordMajorVersion << 8) | recordMinorVersion;
577
this.recordVersion = versionMap.get(version) != null ?
578
versionMap.get(version) :
579
unknownVersion(recordMajorVersion, recordMinorVersion);
580
581
version = (helloMajorVersion << 8) | helloMinorVersion;
582
this.helloVersion = versionMap.get(version) != null ?
583
versionMap.get(version) :
584
unknownVersion(helloMajorVersion, helloMinorVersion);
585
586
this.sniNames = sniNames;
587
}
588
589
@Override
590
public String getRecordVersion() {
591
return recordVersion;
592
}
593
594
@Override
595
public String getHelloVersion() {
596
return helloVersion;
597
}
598
599
@Override
600
public List<SNIServerName> getServerNames() {
601
if (!sniNames.isEmpty()) {
602
return Collections.<SNIServerName>unmodifiableList(sniNames);
603
}
604
605
return sniNames;
606
}
607
608
private static String unknownVersion(byte major, byte minor) {
609
return "Unknown-" + ((int)major) + "." + ((int)minor);
610
}
611
}
612
}
613
614
615