Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/ssl/ECDHServerKeyExchange.java
38830 views
1
/*
2
* Copyright (c) 2015, 2018, 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
package sun.security.ssl;
27
28
import java.io.IOException;
29
import java.nio.ByteBuffer;
30
import java.security.CryptoPrimitive;
31
import java.security.InvalidAlgorithmParameterException;
32
import java.security.InvalidKeyException;
33
import java.security.Key;
34
import java.security.KeyFactory;
35
import java.security.NoSuchAlgorithmException;
36
import java.security.PrivateKey;
37
import java.security.PublicKey;
38
import java.security.Signature;
39
import java.security.SignatureException;
40
import java.security.interfaces.ECPublicKey;
41
import java.security.spec.ECParameterSpec;
42
import java.security.spec.ECPoint;
43
import java.security.spec.ECPublicKeySpec;
44
import java.security.spec.InvalidKeySpecException;
45
import java.text.MessageFormat;
46
import java.util.EnumSet;
47
import java.util.Locale;
48
import java.util.Map;
49
import sun.security.ssl.ECDHKeyExchange.ECDHECredentials;
50
import sun.security.ssl.ECDHKeyExchange.ECDHEPossession;
51
import sun.security.ssl.SSLHandshake.HandshakeMessage;
52
import sun.security.ssl.SupportedGroupsExtension.NamedGroup;
53
import sun.security.ssl.SupportedGroupsExtension.SupportedGroups;
54
import sun.security.ssl.X509Authentication.X509Credentials;
55
import sun.security.ssl.X509Authentication.X509Possession;
56
import sun.misc.HexDumpEncoder;
57
58
/**
59
* Pack of the ServerKeyExchange handshake message.
60
*/
61
final class ECDHServerKeyExchange {
62
static final SSLConsumer ecdheHandshakeConsumer =
63
new ECDHServerKeyExchangeConsumer();
64
static final HandshakeProducer ecdheHandshakeProducer =
65
new ECDHServerKeyExchangeProducer();
66
67
/**
68
* The ECDH ServerKeyExchange handshake message.
69
*/
70
private static final
71
class ECDHServerKeyExchangeMessage extends HandshakeMessage {
72
private static final byte CURVE_NAMED_CURVE = (byte)0x03;
73
74
// id of the named curve
75
private final NamedGroup namedGroup;
76
77
// encoded public point
78
private final byte[] publicPoint;
79
80
// signature bytes, or null if anonymous
81
private final byte[] paramsSignature;
82
83
// public key object encapsulated in this message
84
private final ECPublicKey publicKey;
85
86
private final boolean useExplicitSigAlgorithm;
87
88
// the signature algorithm used by this ServerKeyExchange message
89
private final SignatureScheme signatureScheme;
90
91
ECDHServerKeyExchangeMessage(
92
HandshakeContext handshakeContext) throws IOException {
93
super(handshakeContext);
94
95
// This happens in server side only.
96
ServerHandshakeContext shc =
97
(ServerHandshakeContext)handshakeContext;
98
99
ECDHEPossession ecdhePossession = null;
100
X509Possession x509Possession = null;
101
for (SSLPossession possession : shc.handshakePossessions) {
102
if (possession instanceof ECDHEPossession) {
103
ecdhePossession = (ECDHEPossession)possession;
104
if (x509Possession != null) {
105
break;
106
}
107
} else if (possession instanceof X509Possession) {
108
x509Possession = (X509Possession)possession;
109
if (ecdhePossession != null) {
110
break;
111
}
112
}
113
}
114
115
if (ecdhePossession == null) {
116
// unlikely
117
throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
118
"No ECDHE credentials negotiated for server key exchange");
119
}
120
121
publicKey = ecdhePossession.publicKey;
122
ECParameterSpec params = publicKey.getParams();
123
ECPoint point = publicKey.getW();
124
publicPoint = JsseJce.encodePoint(point, params.getCurve());
125
126
this.namedGroup = NamedGroup.valueOf(params);
127
if ((namedGroup == null) || (namedGroup.oid == null) ) {
128
// unlikely
129
throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
130
"Unnamed EC parameter spec: " + params);
131
}
132
133
if (x509Possession == null) {
134
// anonymous, no authentication, no signature
135
paramsSignature = null;
136
signatureScheme = null;
137
useExplicitSigAlgorithm = false;
138
} else {
139
useExplicitSigAlgorithm =
140
shc.negotiatedProtocol.useTLS12PlusSpec();
141
Signature signer = null;
142
if (useExplicitSigAlgorithm) {
143
Map.Entry<SignatureScheme, Signature> schemeAndSigner =
144
SignatureScheme.getSignerOfPreferableAlgorithm(
145
shc.peerRequestedSignatureSchemes,
146
x509Possession,
147
shc.negotiatedProtocol);
148
if (schemeAndSigner == null) {
149
// Unlikely, the credentials generator should have
150
// selected the preferable signature algorithm properly.
151
throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
152
"No supported signature algorithm for " +
153
x509Possession.popPrivateKey.getAlgorithm() +
154
" key");
155
} else {
156
signatureScheme = schemeAndSigner.getKey();
157
signer = schemeAndSigner.getValue();
158
}
159
} else {
160
signatureScheme = null;
161
try {
162
signer = getSignature(
163
x509Possession.popPrivateKey.getAlgorithm(),
164
x509Possession.popPrivateKey);
165
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
166
throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
167
"Unsupported signature algorithm: " +
168
x509Possession.popPrivateKey.getAlgorithm(), e);
169
}
170
}
171
172
byte[] signature = null;
173
try {
174
updateSignature(signer, shc.clientHelloRandom.randomBytes,
175
shc.serverHelloRandom.randomBytes,
176
namedGroup.id, publicPoint);
177
signature = signer.sign();
178
} catch (SignatureException ex) {
179
throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
180
"Failed to sign ecdhe parameters: " +
181
x509Possession.popPrivateKey.getAlgorithm(), ex);
182
}
183
paramsSignature = signature;
184
}
185
}
186
187
ECDHServerKeyExchangeMessage(HandshakeContext handshakeContext,
188
ByteBuffer m) throws IOException {
189
super(handshakeContext);
190
191
// This happens in client side only.
192
ClientHandshakeContext chc =
193
(ClientHandshakeContext)handshakeContext;
194
195
byte curveType = (byte)Record.getInt8(m);
196
if (curveType != CURVE_NAMED_CURVE) {
197
// Unlikely as only the named curves should be negotiated.
198
throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
199
"Unsupported ECCurveType: " + curveType);
200
}
201
202
int namedGroupId = Record.getInt16(m);
203
this.namedGroup = NamedGroup.valueOf(namedGroupId);
204
if (namedGroup == null) {
205
throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
206
"Unknown named group ID: " + namedGroupId);
207
}
208
209
if (!SupportedGroups.isSupported(namedGroup)) {
210
throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
211
"Unsupported named group: " + namedGroup);
212
}
213
214
if (namedGroup.oid == null) {
215
throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
216
"Unknown named EC curve: " + namedGroup);
217
}
218
219
ECParameterSpec parameters =
220
JsseJce.getECParameterSpec(namedGroup.oid);
221
if (parameters == null) {
222
throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
223
"No supported EC parameter: " + namedGroup);
224
}
225
226
publicPoint = Record.getBytes8(m);
227
if (publicPoint.length == 0) {
228
throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
229
"Insufficient ECPoint data: " + namedGroup);
230
}
231
232
ECPublicKey ecPublicKey = null;
233
try {
234
ECPoint point =
235
JsseJce.decodePoint(publicPoint, parameters.getCurve());
236
KeyFactory factory = JsseJce.getKeyFactory("EC");
237
ecPublicKey = (ECPublicKey)factory.generatePublic(
238
new ECPublicKeySpec(point, parameters));
239
} catch (NoSuchAlgorithmException |
240
InvalidKeySpecException | IOException ex) {
241
throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
242
"Invalid ECPoint: " + namedGroup, ex);
243
}
244
245
publicKey = ecPublicKey;
246
247
X509Credentials x509Credentials = null;
248
for (SSLCredentials cd : chc.handshakeCredentials) {
249
if (cd instanceof X509Credentials) {
250
x509Credentials = (X509Credentials)cd;
251
break;
252
}
253
}
254
255
if (x509Credentials == null) {
256
// anonymous, no authentication, no signature
257
if (m.hasRemaining()) {
258
throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
259
"Invalid DH ServerKeyExchange: unknown extra data");
260
}
261
this.signatureScheme = null;
262
this.paramsSignature = null;
263
this.useExplicitSigAlgorithm = false;
264
265
return;
266
}
267
268
this.useExplicitSigAlgorithm =
269
chc.negotiatedProtocol.useTLS12PlusSpec();
270
if (useExplicitSigAlgorithm) {
271
int ssid = Record.getInt16(m);
272
signatureScheme = SignatureScheme.valueOf(ssid);
273
if (signatureScheme == null) {
274
throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
275
"Invalid signature algorithm (" + ssid +
276
") used in ECDH ServerKeyExchange handshake message");
277
}
278
279
if (!chc.localSupportedSignAlgs.contains(signatureScheme)) {
280
throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
281
"Unsupported signature algorithm (" +
282
signatureScheme.name +
283
") used in ECDH ServerKeyExchange handshake message");
284
}
285
} else {
286
signatureScheme = null;
287
}
288
289
// read and verify the signature
290
paramsSignature = Record.getBytes16(m);
291
Signature signer;
292
if (useExplicitSigAlgorithm) {
293
try {
294
signer = signatureScheme.getVerifier(
295
x509Credentials.popPublicKey);
296
} catch (NoSuchAlgorithmException | InvalidKeyException |
297
InvalidAlgorithmParameterException nsae) {
298
throw chc.conContext.fatal(Alert.INTERNAL_ERROR,
299
"Unsupported signature algorithm: " +
300
signatureScheme.name, nsae);
301
}
302
} else {
303
try {
304
signer = getSignature(
305
x509Credentials.popPublicKey.getAlgorithm(),
306
x509Credentials.popPublicKey);
307
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
308
throw chc.conContext.fatal(Alert.INTERNAL_ERROR,
309
"Unsupported signature algorithm: " +
310
x509Credentials.popPublicKey.getAlgorithm(), e);
311
}
312
}
313
314
try {
315
updateSignature(signer,
316
chc.clientHelloRandom.randomBytes,
317
chc.serverHelloRandom.randomBytes,
318
namedGroup.id, publicPoint);
319
320
if (!signer.verify(paramsSignature)) {
321
throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
322
"Invalid ECDH ServerKeyExchange signature");
323
}
324
} catch (SignatureException ex) {
325
throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
326
"Cannot verify ECDH ServerKeyExchange signature", ex);
327
}
328
}
329
330
@Override
331
public SSLHandshake handshakeType() {
332
return SSLHandshake.SERVER_KEY_EXCHANGE;
333
}
334
335
@Override
336
public int messageLength() {
337
int sigLen = 0;
338
if (paramsSignature != null) {
339
sigLen = 2 + paramsSignature.length;
340
if (useExplicitSigAlgorithm) {
341
sigLen += SignatureScheme.sizeInRecord();
342
}
343
}
344
345
return 4 + publicPoint.length + sigLen;
346
}
347
348
@Override
349
public void send(HandshakeOutStream hos) throws IOException {
350
hos.putInt8(CURVE_NAMED_CURVE);
351
hos.putInt16(namedGroup.id);
352
hos.putBytes8(publicPoint);
353
if (paramsSignature != null) {
354
if (useExplicitSigAlgorithm) {
355
hos.putInt16(signatureScheme.id);
356
}
357
358
hos.putBytes16(paramsSignature);
359
}
360
}
361
362
@Override
363
public String toString() {
364
if (useExplicitSigAlgorithm) {
365
MessageFormat messageFormat = new MessageFormat(
366
"\"ECDH ServerKeyExchange\": '{'\n" +
367
" \"parameters\": '{'\n" +
368
" \"named group\": \"{0}\"\n" +
369
" \"ecdh public\": '{'\n" +
370
"{1}\n" +
371
" '}',\n" +
372
" '}',\n" +
373
" \"digital signature\": '{'\n" +
374
" \"signature algorithm\": \"{2}\"\n" +
375
" \"signature\": '{'\n" +
376
"{3}\n" +
377
" '}',\n" +
378
" '}'\n" +
379
"'}'",
380
Locale.ENGLISH);
381
382
HexDumpEncoder hexEncoder = new HexDumpEncoder();
383
Object[] messageFields = {
384
namedGroup.name,
385
Utilities.indent(
386
hexEncoder.encodeBuffer(publicPoint), " "),
387
signatureScheme.name,
388
Utilities.indent(
389
hexEncoder.encodeBuffer(paramsSignature), " ")
390
};
391
return messageFormat.format(messageFields);
392
} else if (paramsSignature != null) {
393
MessageFormat messageFormat = new MessageFormat(
394
"\"ECDH ServerKeyExchange\": '{'\n" +
395
" \"parameters\": '{'\n" +
396
" \"named group\": \"{0}\"\n" +
397
" \"ecdh public\": '{'\n" +
398
"{1}\n" +
399
" '}',\n" +
400
" '}',\n" +
401
" \"signature\": '{'\n" +
402
"{2}\n" +
403
" '}'\n" +
404
"'}'",
405
Locale.ENGLISH);
406
407
HexDumpEncoder hexEncoder = new HexDumpEncoder();
408
Object[] messageFields = {
409
namedGroup.name,
410
Utilities.indent(
411
hexEncoder.encodeBuffer(publicPoint), " "),
412
Utilities.indent(
413
hexEncoder.encodeBuffer(paramsSignature), " ")
414
};
415
416
return messageFormat.format(messageFields);
417
} else { // anonymous
418
MessageFormat messageFormat = new MessageFormat(
419
"\"ECDH ServerKeyExchange\": '{'\n" +
420
" \"parameters\": '{'\n" +
421
" \"named group\": \"{0}\"\n" +
422
" \"ecdh public\": '{'\n" +
423
"{1}\n" +
424
" '}',\n" +
425
" '}'\n" +
426
"'}'",
427
Locale.ENGLISH);
428
429
HexDumpEncoder hexEncoder = new HexDumpEncoder();
430
Object[] messageFields = {
431
namedGroup.name,
432
Utilities.indent(
433
hexEncoder.encodeBuffer(publicPoint), " "),
434
};
435
436
return messageFormat.format(messageFields);
437
}
438
}
439
440
private static Signature getSignature(String keyAlgorithm,
441
Key key) throws NoSuchAlgorithmException, InvalidKeyException {
442
Signature signer = null;
443
switch (keyAlgorithm) {
444
case "EC":
445
signer = JsseJce.getSignature(JsseJce.SIGNATURE_ECDSA);
446
break;
447
case "RSA":
448
signer = RSASignature.getInstance();
449
break;
450
default:
451
throw new NoSuchAlgorithmException(
452
"neither an RSA or a EC key : " + keyAlgorithm);
453
}
454
455
if (signer != null) {
456
if (key instanceof PublicKey) {
457
signer.initVerify((PublicKey)(key));
458
} else {
459
signer.initSign((PrivateKey)key);
460
}
461
}
462
463
return signer;
464
}
465
466
private static void updateSignature(Signature sig,
467
byte[] clntNonce, byte[] svrNonce, int namedGroupId,
468
byte[] publicPoint) throws SignatureException {
469
sig.update(clntNonce);
470
sig.update(svrNonce);
471
472
sig.update(CURVE_NAMED_CURVE);
473
sig.update((byte)((namedGroupId >> 8) & 0xFF));
474
sig.update((byte)(namedGroupId & 0xFF));
475
sig.update((byte)publicPoint.length);
476
sig.update(publicPoint);
477
}
478
}
479
480
/**
481
* The ECDH "ServerKeyExchange" handshake message producer.
482
*/
483
private static final
484
class ECDHServerKeyExchangeProducer implements HandshakeProducer {
485
// Prevent instantiation of this class.
486
private ECDHServerKeyExchangeProducer() {
487
// blank
488
}
489
490
@Override
491
public byte[] produce(ConnectionContext context,
492
HandshakeMessage message) throws IOException {
493
// The producing happens in server side only.
494
ServerHandshakeContext shc = (ServerHandshakeContext)context;
495
ECDHServerKeyExchangeMessage skem =
496
new ECDHServerKeyExchangeMessage(shc);
497
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
498
SSLLogger.fine(
499
"Produced ECDH ServerKeyExchange handshake message", skem);
500
}
501
502
// Output the handshake message.
503
skem.write(shc.handshakeOutput);
504
shc.handshakeOutput.flush();
505
506
// The handshake message has been delivered.
507
return null;
508
}
509
}
510
511
/**
512
* The ECDH "ServerKeyExchange" handshake message consumer.
513
*/
514
private static final
515
class ECDHServerKeyExchangeConsumer implements SSLConsumer {
516
// Prevent instantiation of this class.
517
private ECDHServerKeyExchangeConsumer() {
518
// blank
519
}
520
521
@Override
522
public void consume(ConnectionContext context,
523
ByteBuffer message) throws IOException {
524
// The consuming happens in client side only.
525
ClientHandshakeContext chc = (ClientHandshakeContext)context;
526
527
ECDHServerKeyExchangeMessage skem =
528
new ECDHServerKeyExchangeMessage(chc, message);
529
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
530
SSLLogger.fine(
531
"Consuming ECDH ServerKeyExchange handshake message", skem);
532
}
533
534
//
535
// validate
536
//
537
// check constraints of EC PublicKey
538
if (!chc.algorithmConstraints.permits(
539
EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
540
skem.publicKey)) {
541
throw chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY,
542
"ECDH ServerKeyExchange does not comply " +
543
"to algorithm constraints");
544
}
545
546
//
547
// update
548
//
549
chc.handshakeCredentials.add(
550
new ECDHECredentials(skem.publicKey, skem.namedGroup));
551
552
//
553
// produce
554
//
555
// Need no new handshake message producers here.
556
}
557
}
558
}
559
560
561