This commit is contained in:
Phil Race 2018-07-19 10:17:22 -07:00
commit 28e828130d
129 changed files with 2316 additions and 591 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -29,6 +29,8 @@
package com.sun.crypto.provider;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.crypto.IllegalBlockSizeException;
import static com.sun.crypto.provider.AESConstants.AES_BLOCK_SIZE;
@ -68,6 +70,15 @@ final class GCTR extends CounterMode {
return "GCTR";
}
// return the number of blocks until the lower 32 bits roll over
private long blocksUntilRollover() {
ByteBuffer buf = ByteBuffer.wrap(counter, counter.length - 4, 4);
buf.order(ByteOrder.BIG_ENDIAN);
long ctr32 = 0xFFFFFFFFL & buf.getInt();
long blocksLeft = (1L << 32) - ctr32;
return blocksLeft;
}
// input must be multiples of 128-bit blocks when calling update
int update(byte[] in, int inOfs, int inLen, byte[] out, int outOfs) {
if (inLen - inOfs > in.length) {
@ -80,7 +91,25 @@ final class GCTR extends CounterMode {
throw new RuntimeException("output buffer too small");
}
return encrypt(in, inOfs, inLen, out, outOfs);
long blocksLeft = blocksUntilRollover();
int numOfCompleteBlocks = inLen / AES_BLOCK_SIZE;
if (numOfCompleteBlocks >= blocksLeft) {
// Counter Mode encryption cannot be used because counter will
// roll over incorrectly. Use GCM-specific code instead.
byte[] encryptedCntr = new byte[AES_BLOCK_SIZE];
for (int i = 0; i < numOfCompleteBlocks; i++) {
embeddedCipher.encryptBlock(counter, 0, encryptedCntr, 0);
for (int n = 0; n < AES_BLOCK_SIZE; n++) {
int index = (i * AES_BLOCK_SIZE + n);
out[outOfs + index] =
(byte) ((in[inOfs + index] ^ encryptedCntr[n]));
}
GaloisCounterMode.increment32(counter);
}
return inLen;
} else {
return encrypt(in, inOfs, inLen, out, outOfs);
}
}
// input can be arbitrary size when calling doFinal

View file

@ -33,7 +33,6 @@ import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.security.util.HexDumpEncoder;
import sun.security.util.*;
/**
@ -260,21 +259,7 @@ abstract class PBES2Parameters extends AlgorithmParametersSpi {
String kdfAlgo = null;
String cipherAlgo = null;
DerValue pBES2Algorithms = new DerValue(encoded);
if (pBES2Algorithms.tag != DerValue.tag_Sequence) {
throw new IOException("PBE parameter parsing error: "
+ "not an ASN.1 SEQUENCE tag");
}
if (!pkcs5PBES2_OID.equals(pBES2Algorithms.data.getOID())) {
throw new IOException("PBE parameter parsing error: "
+ "expecting the object identifier for PBES2");
}
if (pBES2Algorithms.tag != DerValue.tag_Sequence) {
throw new IOException("PBE parameter parsing error: "
+ "not an ASN.1 SEQUENCE tag");
}
DerValue pBES2_params = pBES2Algorithms.data.getDerValue();
DerValue pBES2_params = new DerValue(encoded);
if (pBES2_params.tag != DerValue.tag_Sequence) {
throw new IOException("PBE parameter parsing error: "
+ "not an ASN.1 SEQUENCE tag");
@ -293,7 +278,6 @@ abstract class PBES2Parameters extends AlgorithmParametersSpi {
@SuppressWarnings("deprecation")
private String parseKDF(DerValue keyDerivationFunc) throws IOException {
String kdfAlgo = null;
if (!pkcs5PBKDF2_OID.equals(keyDerivationFunc.data.getOID())) {
throw new IOException("PBE parameter parsing error: "
@ -318,34 +302,41 @@ abstract class PBES2Parameters extends AlgorithmParametersSpi {
+ "not an ASN.1 OCTET STRING tag");
}
iCount = pBKDF2_params.data.getInteger();
DerValue keyLength = pBKDF2_params.data.getDerValue();
if (keyLength.tag == DerValue.tag_Integer) {
keysize = keyLength.getInteger() * 8; // keysize (in bits)
}
if (pBKDF2_params.tag == DerValue.tag_Sequence) {
DerValue prf = pBKDF2_params.data.getDerValue();
kdfAlgo_OID = prf.data.getOID();
if (hmacWithSHA1_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA1";
} else if (hmacWithSHA224_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA224";
} else if (hmacWithSHA256_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA256";
} else if (hmacWithSHA384_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA384";
} else if (hmacWithSHA512_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA512";
} else {
throw new IOException("PBE parameter parsing error: "
+ "expecting the object identifier for a HmacSHA key "
+ "derivation function");
// keyLength INTEGER (1..MAX) OPTIONAL,
if (pBKDF2_params.data.available() > 0) {
DerValue keyLength = pBKDF2_params.data.getDerValue();
if (keyLength.tag == DerValue.tag_Integer) {
keysize = keyLength.getInteger() * 8; // keysize (in bits)
}
if (prf.data.available() != 0) {
// parameter is 'NULL' for all HmacSHA KDFs
DerValue parameter = prf.data.getDerValue();
if (parameter.tag != DerValue.tag_Null) {
}
// prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1
String kdfAlgo = "HmacSHA1";
if (pBKDF2_params.data.available() > 0) {
if (pBKDF2_params.tag == DerValue.tag_Sequence) {
DerValue prf = pBKDF2_params.data.getDerValue();
kdfAlgo_OID = prf.data.getOID();
if (hmacWithSHA1_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA1";
} else if (hmacWithSHA224_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA224";
} else if (hmacWithSHA256_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA256";
} else if (hmacWithSHA384_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA384";
} else if (hmacWithSHA512_OID.equals(kdfAlgo_OID)) {
kdfAlgo = "HmacSHA512";
} else {
throw new IOException("PBE parameter parsing error: "
+ "not an ASN.1 NULL tag");
+ "expecting the object identifier for a HmacSHA key "
+ "derivation function");
}
if (prf.data.available() != 0) {
// parameter is 'NULL' for all HmacSHA KDFs
DerValue parameter = prf.data.getDerValue();
if (parameter.tag != DerValue.tag_Null) {
throw new IOException("PBE parameter parsing error: "
+ "not an ASN.1 NULL tag");
}
}
}
}
@ -399,8 +390,6 @@ abstract class PBES2Parameters extends AlgorithmParametersSpi {
protected byte[] engineGetEncoded() throws IOException {
DerOutputStream out = new DerOutputStream();
DerOutputStream pBES2Algorithms = new DerOutputStream();
pBES2Algorithms.putOID(pkcs5PBES2_OID);
DerOutputStream pBES2_params = new DerOutputStream();
@ -410,7 +399,10 @@ abstract class PBES2Parameters extends AlgorithmParametersSpi {
DerOutputStream pBKDF2_params = new DerOutputStream();
pBKDF2_params.putOctetString(salt); // choice: 'specified OCTET STRING'
pBKDF2_params.putInteger(iCount);
pBKDF2_params.putInteger(keysize / 8); // derived key length (in octets)
if (keysize > 0) {
pBKDF2_params.putInteger(keysize / 8); // derived key length (in octets)
}
DerOutputStream prf = new DerOutputStream();
// algorithm is id-hmacWithSHA1/SHA224/SHA256/SHA384/SHA512
@ -434,8 +426,7 @@ abstract class PBES2Parameters extends AlgorithmParametersSpi {
}
pBES2_params.write(DerValue.tag_Sequence, encryptionScheme);
pBES2Algorithms.write(DerValue.tag_Sequence, pBES2_params);
out.write(DerValue.tag_Sequence, pBES2Algorithms);
out.write(DerValue.tag_Sequence, pBES2_params);
return out.toByteArray();
}

View file

@ -1807,6 +1807,7 @@ public class KeyStore {
keystore.load(dataStream, password);
} else {
keystore.keyStoreSpi.engineLoad(dataStream, param);
keystore.initialized = true;
}
return keystore;
}

View file

@ -106,7 +106,7 @@ public class PatternSyntaxException
}
sb.append(System.lineSeparator());
sb.append(pattern);
if (index >= 0) {
if (index >= 0 && pattern != null && index < pattern.length()) {
sb.append(System.lineSeparator());
for (int i = 0; i < index; i++) sb.append(' ');
sb.append('^');

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -87,6 +87,9 @@ public class ReflectionFactory {
private static boolean noInflation = false;
private static int inflationThreshold = 15;
// true if deserialization constructor checking is disabled
private static boolean disableSerialConstructorChecks = false;
private ReflectionFactory() {
}
@ -424,10 +427,64 @@ public class ReflectionFactory {
return generateConstructor(cl, constructorToCall);
}
/**
* Given a class, determines whether its superclass has
* any constructors that are accessible from the class.
* This is a special purpose method intended to do access
* checking for a serializable class and its superclasses
* up to, but not including, the first non-serializable
* superclass. This also implies that the superclass is
* always non-null, because a serializable class must be a
* class (not an interface) and Object is not serializable.
*
* @param cl the class from which access is checked
* @return whether the superclass has a constructor accessible from cl
*/
private boolean superHasAccessibleConstructor(Class<?> cl) {
Class<?> superCl = cl.getSuperclass();
assert Serializable.class.isAssignableFrom(cl);
assert superCl != null;
if (packageEquals(cl, superCl)) {
// accessible if any non-private constructor is found
for (Constructor<?> ctor : superCl.getDeclaredConstructors()) {
if ((ctor.getModifiers() & Modifier.PRIVATE) == 0) {
return true;
}
}
return false;
} else {
// sanity check to ensure the parent is protected or public
if ((superCl.getModifiers() & (Modifier.PROTECTED | Modifier.PUBLIC)) == 0) {
return false;
}
// accessible if any constructor is protected or public
for (Constructor<?> ctor : superCl.getDeclaredConstructors()) {
if ((ctor.getModifiers() & (Modifier.PROTECTED | Modifier.PUBLIC)) != 0) {
return true;
}
}
return false;
}
}
/**
* Returns a constructor that allocates an instance of cl and that then initializes
* the instance by calling the no-arg constructor of its first non-serializable
* superclass. This is specified in the Serialization Specification, section 3.1,
* in step 11 of the deserialization process. If cl is not serializable, returns
* cl's no-arg constructor. If no accessible constructor is found, or if the
* class hierarchy is somehow malformed (e.g., a serializable class has no
* superclass), null is returned.
*
* @param cl the class for which a constructor is to be found
* @return the generated constructor, or null if none is available
*/
public final Constructor<?> newConstructorForSerialization(Class<?> cl) {
Class<?> initCl = cl;
while (Serializable.class.isAssignableFrom(initCl)) {
if ((initCl = initCl.getSuperclass()) == null) {
Class<?> prev = initCl;
if ((initCl = initCl.getSuperclass()) == null ||
(!disableSerialConstructorChecks && !superHasAccessibleConstructor(prev))) {
return null;
}
}
@ -653,6 +710,9 @@ public class ReflectionFactory {
}
}
disableSerialConstructorChecks =
"true".equals(props.getProperty("jdk.disableSerialConstructorChecks"));
initted = true;
}

View file

@ -2098,7 +2098,8 @@ public final class PKCS12KeyStore extends KeyStoreSpi {
RetryWithZero.run(pass -> {
// Use JCE
SecretKey skey = getPBEKey(pass);
Cipher cipher = Cipher.getInstance(algOid.toString());
Cipher cipher = Cipher.getInstance(
mapPBEParamsToAlgorithm(algOid, algParams));
cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
loadSafeContents(new DerInputStream(cipher.doFinal(rawData)));
return null;

View file

@ -27,6 +27,7 @@ package sun.security.ssl;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
@ -46,6 +47,9 @@ final class PostHandshakeContext extends HandshakeContext {
"Post-handshake not supported in " + negotiatedProtocol.name);
}
this.localSupportedSignAlgs = new ArrayList<SignatureScheme>(
context.conSession.getLocalSupportedSignatureSchemes());
handshakeConsumers = new LinkedHashMap<>(consumers);
handshakeFinished = true;
}

View file

@ -33,8 +33,11 @@ import java.util.ArrayList;
import java.util.Locale;
import java.util.Arrays;
import java.util.Optional;
import java.util.Collection;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.net.ssl.SSLPeerUnverifiedException;
import static sun.security.ssl.ClientAuthType.CLIENT_AUTH_REQUIRED;
import sun.security.ssl.ClientHello.ClientHelloMessage;
import sun.security.ssl.SSLExtension.ExtensionConsumer;
import sun.security.ssl.SSLExtension.SSLExtensionSpec;
@ -167,7 +170,7 @@ final class PreSharedKeyExtension {
int getIdsEncodedLength() {
int idEncodedLength = 0;
for(PskIdentity curId : identities) {
for (PskIdentity curId : identities) {
idEncodedLength += curId.getEncodedLength();
}
@ -190,7 +193,7 @@ final class PreSharedKeyExtension {
byte[] buffer = new byte[encodedLength];
ByteBuffer m = ByteBuffer.wrap(buffer);
Record.putInt16(m, idsEncodedLength);
for(PskIdentity curId : identities) {
for (PskIdentity curId : identities) {
curId.writeEncoded(m);
}
Record.putInt16(m, bindersEncodedLength);
@ -220,7 +223,7 @@ final class PreSharedKeyExtension {
String identitiesString() {
StringBuilder result = new StringBuilder();
for(PskIdentity curId : identities) {
for (PskIdentity curId : identities) {
result.append(curId.toString() + "\n");
}
@ -229,7 +232,7 @@ final class PreSharedKeyExtension {
String bindersString() {
StringBuilder result = new StringBuilder();
for(byte[] curBinder : binders) {
for (byte[] curBinder : binders) {
result.append("{" + Utilities.toHexString(curBinder) + "}\n");
}
@ -328,6 +331,7 @@ final class PreSharedKeyExtension {
public void consume(ConnectionContext context,
HandshakeMessage message,
ByteBuffer buffer) throws IOException {
ClientHelloMessage clientHello = (ClientHelloMessage) message;
ServerHandshakeContext shc = (ServerHandshakeContext)context;
// Is it a supported and enabled extension?
if (!shc.sslConfig.isAvailable(SSLExtension.CH_PRE_SHARED_KEY)) {
@ -367,8 +371,7 @@ final class PreSharedKeyExtension {
int idIndex = 0;
for (PskIdentity requestedId : pskSpec.identities) {
SSLSessionImpl s = sessionCache.get(requestedId.identity);
if (s != null && s.isRejoinable() &&
s.getPreSharedKey().isPresent()) {
if (s != null && canRejoin(clientHello, shc, s)) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("Resuming session: ", s);
}
@ -392,10 +395,68 @@ final class PreSharedKeyExtension {
// update the context
shc.handshakeExtensions.put(
SSLExtension.CH_PRE_SHARED_KEY, pskSpec);
SSLExtension.CH_PRE_SHARED_KEY, pskSpec);
}
}
private static boolean canRejoin(ClientHelloMessage clientHello,
ServerHandshakeContext shc, SSLSessionImpl s) {
boolean result = s.isRejoinable() && s.getPreSharedKey().isPresent();
// Check protocol version
if (result && s.getProtocolVersion() != shc.negotiatedProtocol) {
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest("Can't resume, incorrect protocol version");
}
result = false;
}
// Validate the required client authentication.
if (result &&
(shc.sslConfig.clientAuthType == CLIENT_AUTH_REQUIRED)) {
try {
s.getPeerPrincipal();
} catch (SSLPeerUnverifiedException e) {
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Can't resume, " +
"client authentication is required");
}
result = false;
}
// Make sure the list of supported signature algorithms matches
Collection<SignatureScheme> sessionSigAlgs =
s.getLocalSupportedSignatureSchemes();
if (result &&
!shc.localSupportedSignAlgs.containsAll(sessionSigAlgs)) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("Can't resume. Session uses different " +
"signature algorithms");
}
result = false;
}
}
// Ensure cipher suite can be negotiated
if (result && (!shc.isNegotiable(s.getSuite()) ||
!clientHello.cipherSuites.contains(s.getSuite()))) {
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Can't resume, unavailable session cipher suite");
}
result = false;
}
return result;
}
private static final
class CHPreSharedKeyUpdate implements HandshakeConsumer {
// Prevent instantiation of this class.
@ -547,6 +608,18 @@ final class PreSharedKeyExtension {
return null;
}
// Make sure the list of supported signature algorithms matches
Collection<SignatureScheme> sessionSigAlgs =
chc.resumingSession.getLocalSupportedSignatureSchemes();
if (!chc.localSupportedSignAlgs.containsAll(sessionSigAlgs)) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine("Existing session uses different " +
"signature algorithms");
}
return null;
}
// The session must have a pre-shared key
Optional<SecretKey> pskOpt = chc.resumingSession.getPreSharedKey();
if (!pskOpt.isPresent()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
@ -658,7 +731,7 @@ final class PreSharedKeyExtension {
} catch (NoSuchAlgorithmException | InvalidKeyException ex) {
throw new IOException(ex);
}
} catch(GeneralSecurityException ex) {
} catch (GeneralSecurityException ex) {
throw new IOException(ex);
}
}

View file

@ -96,7 +96,7 @@ final class SSLSessionImpl extends ExtendedSSLSession {
private boolean invalidated;
private X509Certificate[] localCerts;
private PrivateKey localPrivateKey;
private final String[] localSupportedSignAlgs;
private final Collection<SignatureScheme> localSupportedSignAlgs;
private String[] peerSupportedSignAlgs; // for certificate
private boolean useDefaultPeerSignAlgs = false;
private List<byte[]> statusResponses;
@ -144,7 +144,7 @@ final class SSLSessionImpl extends ExtendedSSLSession {
this.sessionId = new SessionId(false, null);
this.host = null;
this.port = -1;
this.localSupportedSignAlgs = new String[0];
this.localSupportedSignAlgs = Collections.emptySet();
this.serverNameIndication = null;
this.requestedServerNames = Collections.<SNIServerName>emptyList();
this.useExtendedMasterSecret = false;
@ -179,8 +179,9 @@ final class SSLSessionImpl extends ExtendedSSLSession {
this.sessionId = id;
this.host = hc.conContext.transport.getPeerHost();
this.port = hc.conContext.transport.getPeerPort();
this.localSupportedSignAlgs =
SignatureScheme.getAlgorithmNames(hc.localSupportedSignAlgs);
this.localSupportedSignAlgs = hc.localSupportedSignAlgs == null ?
Collections.emptySet() :
Collections.unmodifiableCollection(hc.localSupportedSignAlgs);
this.serverNameIndication = hc.negotiatedServerName;
this.requestedServerNames = Collections.<SNIServerName>unmodifiableList(
hc.getRequestedServerNames());
@ -969,16 +970,20 @@ final class SSLSessionImpl extends ExtendedSSLSession {
}
/**
* Gets an array of supported signature algorithms that the local side is
* willing to verify.
* Gets an array of supported signature algorithm names that the local
* side is willing to verify.
*/
@Override
public String[] getLocalSupportedSignatureAlgorithms() {
if (localSupportedSignAlgs != null) {
return localSupportedSignAlgs.clone();
}
return SignatureScheme.getAlgorithmNames(localSupportedSignAlgs);
}
return new String[0];
/**
* Gets an array of supported signature schemes that the local side is
* willing to verify.
*/
public Collection<SignatureScheme> getLocalSupportedSignatureSchemes() {
return localSupportedSignAlgs;
}
/**

View file

@ -393,6 +393,13 @@ class TransportContext implements ConnectionContext, Closeable {
}
void setUseClientMode(boolean useClientMode) {
// Once handshaking has begun, the mode can not be reset for the
// life of this engine.
if (handshakeContext != null || isNegotiated) {
throw new IllegalArgumentException(
"Cannot change mode after SSL traffic has started");
}
/*
* If we need to change the client mode and the enabled
* protocols and cipher suites haven't specifically been
@ -400,13 +407,6 @@ class TransportContext implements ConnectionContext, Closeable {
* default ones.
*/
if (sslConfig.isClientMode != useClientMode) {
// Once handshaking has begun, the mode can not be reset for the
// life of this engine.
if (handshakeContext != null || isNegotiated) {
throw new IllegalArgumentException(
"Cannot change mode after SSL traffic has started");
}
if (sslContext.isDefaultProtocolVesions(
sslConfig.enabledProtocols)) {
sslConfig.enabledProtocols =