Skip to content

Commit d6d7ec2

Browse files
committed
TLS: fall back to the generic RSASSA-PSS signature name (digest via PSSParameterSpec) when an alternate provider such as SunMSCAPI registers no digest-specific PSS algorithm, fixing RSA-PSS CertificateVerify with Windows smart-card (Windows-MY/CPrivateKey) client keys under TLS 1.2 and 1.3
1 parent d10b2f6 commit d6d7ec2

6 files changed

Lines changed: 282 additions & 0 deletions

File tree

‎ant/jdk14.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,7 @@
269269
<exclude name="**/tls/test/TlsRawKeysProtocolTest.java"/>
270270
<exclude name="**/tls/test/DTLSRawKeysProtocolTest.java"/>
271271
<exclude name="**/tls/test/JcaTlsRawKeysProtocolTest.java"/>
272+
<exclude name="**/tls/crypto/test/JcaTlsRSAPSSAltProviderTest.java"/>
272273
<exclude name="**/tls/AllTests.java"/>
273274
<exclude name="**/CertChainUtil.java"/>
274275
<exclude name="**/TlsTestUtils.java"/>

‎docs/releasenotes.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ <h3>2.1.2 Defects Fixed</h3>
3131
<li>The PKIX CertPathBuilder ("PKIX"/"RFC5280"/"RFC3280") matched candidate issuers by subject name only during its depth-first search, so a CertStore containing many self-issued certificates that share a single subject name and never chain to a trust anchor could be explored as a large number of partial paths before the build concluded no chain exists. The builder now bounds the total number of nodes visited per build; the limit is configurable via the org.bouncycastle.x509.max_cert_path_build_nodes system property (default 262144, far above any legitimate build) and, when exceeded, the build fails with a CertPathBuilderException naming the property. This is the builder-side companion to the existing org.bouncycastle.x509.max_policy_nodes bound.</li>
3232
<li>A group of parse and revocation-handling entry points let an unchecked runtime exception (NullPointerException, ArrayIndexOutOfBoundsException, IllegalStateException or ArithmeticException) escape on empty, content-less or out-of-range input instead of the checked exception each entry point declares - the malformed input was rejected either way, but the leaked type could escape a documented throws contract. Each now fails with its declared type, and well-formed input is unaffected: org.bouncycastle.tsp.cms.CMSTimeStampedData (an empty or truncated stream; the fix also covers its org.bouncycastle.asn1.cms.MetaData and TimeStampDataUtil helpers) and org.bouncycastle.cms.CMSEnvelopedData (an EnvelopedData carrying no encryptedContent) now throw IOException / CMSException rather than NullPointerException; org.bouncycastle.tsp.TimeStampToken rejects a token whose SignerInfo carries no signed attributes with TSPValidationException rather than NullPointerException; org.bouncycastle.cert.cmp.GeneralPKIMessage, org.bouncycastle.est.CSRAttributesResponse, org.bouncycastle.cmc.SimplePKIResponse, org.bouncycastle.openssl.X509TrustedCertificateBlock, org.bouncycastle.tsp.TimeStampRequest, org.bouncycastle.tsp.TimeStampResponse, org.bouncycastle.pkcs.PKCS12PfxPdu and org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo reject empty / no-content / truncated input with their declared CertIOException / IOException / PKCSIOException rather than a leaked NullPointerException, and org.bouncycastle.cert.crmf.CertificateRequestMessage.hasSigningKeyProofOfPossessionWithPKMAC answers false for an absent or non-signing-key proof-of-possession rather than throwing NullPointerException; org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil.parsePrivateKeyBlob and org.bouncycastle.math.ec.ECCurve.decodePoint reject an empty (or null) blob / point encoding with IllegalArgumentException rather than ArrayIndexOutOfBoundsException, closing the point-decode path reached by every untrusted-point consumer (EC key parsing, ECDH/ECIES, TLS); and the PKIX revocation code no longer leaks a runtime exception on attacker-controlled CRL/OCSP fields - PKIXCertPathReviewer and X509RevocationChecker bound an out-of-range CRLReason code against their fixed reason table (reporting "unknown" instead of ArrayIndexOutOfBoundsException / ArithmeticException), RFC3280CertPathUtilities tolerates an absent reasons mask on a CRL distribution point, and ProvOcspRevocationChecker tolerates an OCSP response with no nonce extension.</li>
3333
<li>A network failure while fetching an OCSP response during PKIX revocation checking (unknown host, no route, connection refused/timed out on the responder) was thrown as a hard CertPathValidatorException ("configuration error: ..."), so the PKIXRevocationChecker never fell back to CRL-based checking and path validation failed outright. An unreachable or failing responder is now treated as a recoverable failure ("unable to get OCSP response from ..."), allowing CRL fallback to run; with Option.NO_FALLBACK set validation still fails as before (github #2372).</li>
34+
<li>The (D)TLS API and BCJSSE could not generate an RSA-PSS handshake signature (rsa_pss_rsae_* / rsa_pss_pss_*, mandatory for RSA client certificates under TLS 1.3) when the private-key operation was delegated to an alternate provider that registers only the generic "RSASSA-PSS" signature algorithm and takes the digest from a PSSParameterSpec - the shape of SunMSCAPI, so Windows smart-card client keys (sun.security.mscapi.CPrivateKey from the Windows-MY keystore) failed the handshake with "NoSuchAlgorithmException: SHA256WITHRSASSA-PSS for provider SunMSCAPI" once the digest-specific name lookups (SHA256withRSAandMGF1, then SHA256withRSASSA-PSS) had been exhausted. JcaTlsCrypto now falls back to the generic RSASSA-PSS name, with the digest, MGF and salt length still supplied explicitly through the PSSParameterSpec, so RSA-PSS CertificateVerify signatures work with SunMSCAPI-held keys under both TLS 1.2 and TLS 1.3.</li>
3435
<li>SICBlockCipher (CTR/SIC mode) could report a wrong getPosition() once the block counter had been incremented across consecutive 0xFF bytes of the initial counter block: the counter-minus-IV subtraction inside getPosition applied each borrow by decrementing the neighbouring byte in place, and when that byte was 0x00 the decrement wrapped to 0xFF without propagating the borrow further, leaving the reported position too large by a multiple of 2^16 blocks (for example, an AES CTR cipher initialised with a 16-byte IV ending in FFFF reported position 1048592 after processing 16 bytes). The same subtraction also never processed byte 0 of the counter, so for 8-byte-block ciphers - where all eight counter bytes contribute to the returned value - a full-length IV with a nonzero first byte skewed the reported position by IV[0]*2^56 blocks. These two defects affected only position reporting (getPosition and anything a caller derives from it, such as a relative skip computed from the reported position), not the keystream itself; the subtraction now carries the borrow explicitly across every byte of the counter. Additionally, a backward skip() smaller in magnitude than the cipher's current intra-block offset rewound the position to the start of the current block instead of moving back exactly the requested number of bytes, while still returning the requested count as if the move were exact - so both the position and the keystream resumed from the wrong offset. Forward skips, seekTo(), and backward skips that cross a block boundary were already exact; a mid-block backward skip now lands exactly on the requested position.</li>
3536
</ul>
3637

‎tls/src/main/java/org/bouncycastle/tls/crypto/impl/jcajce/JcaTlsCrypto.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1036,6 +1036,21 @@ protected TlsStreamSigner createStreamSigner(JcaJceHelper helper, String algorit
10361036
{
10371037
// ANDMGF1 has vanished from the Sun PKCS11 provider.
10381038
algorithmName = upperAlg.replace("ANDMGF1", "SSA-PSS");
1039+
try
1040+
{
1041+
dummySigner = helper.createSignature(algorithmName);
1042+
}
1043+
catch (NoSuchAlgorithmException e2)
1044+
{
1045+
// SunMSCAPI only registers the generic name - the digest is carried by the parameter.
1046+
algorithmName = "RSASSA-PSS";
1047+
dummySigner = helper.createSignature(algorithmName);
1048+
}
1049+
}
1050+
else if (upperAlg.endsWith("WITHRSASSA-PSS"))
1051+
{
1052+
// SunMSCAPI only registers the generic name - the digest is carried by the parameter.
1053+
algorithmName = "RSASSA-PSS";
10391054
dummySigner = helper.createSignature(algorithmName);
10401055
}
10411056
else

‎tls/src/test/java/org/bouncycastle/tls/crypto/test/AllTests.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ public static Test suite()
2323

2424
suite.addTestSuite(BcTlsCryptoTest.class);
2525
suite.addTestSuite(JcaTlsCryptoTest.class);
26+
suite.addTestSuite(JcaTlsRSAPSSAltProviderTest.class);
2627

2728
return new BCTestSetup(suite);
2829
}
Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
package org.bouncycastle.tls.crypto.test;
2+
3+
import java.io.OutputStream;
4+
import java.security.InvalidAlgorithmParameterException;
5+
import java.security.InvalidKeyException;
6+
import java.security.KeyPair;
7+
import java.security.KeyPairGenerator;
8+
import java.security.PrivateKey;
9+
import java.security.Provider;
10+
import java.security.PublicKey;
11+
import java.security.SecureRandom;
12+
import java.security.Signature;
13+
import java.security.SignatureException;
14+
import java.security.SignatureSpi;
15+
import java.security.spec.AlgorithmParameterSpec;
16+
17+
import junit.framework.TestCase;
18+
import org.bouncycastle.jce.provider.BouncyCastleProvider;
19+
import org.bouncycastle.tls.SignatureScheme;
20+
import org.bouncycastle.tls.crypto.TlsStreamSigner;
21+
import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCrypto;
22+
import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsCryptoProvider;
23+
import org.bouncycastle.tls.crypto.impl.jcajce.JcaTlsRSAPSSSigner;
24+
import org.bouncycastle.util.Strings;
25+
26+
/**
27+
* Regression test for RSA-PSS CertificateVerify generation when the private key is held by an
28+
* alternate provider that registers only the generic "RSASSA-PSS" signature name and takes the
29+
* digest from a PSSParameterSpec - the shape of SunMSCAPI (Windows smart card keys) since JDK 13.
30+
*/
31+
public class JcaTlsRSAPSSAltProviderTest
32+
extends TestCase
33+
{
34+
private static final BouncyCastleProvider BC = new BouncyCastleProvider();
35+
36+
public void testRSAPSSSignatureWithGenericPSSOnlyAltProvider()
37+
throws Exception
38+
{
39+
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", BC);
40+
kpGen.initialize(2048, new SecureRandom());
41+
KeyPair kp = kpGen.generateKeyPair();
42+
43+
JcaTlsCrypto crypto = new JcaTlsCryptoProvider()
44+
.setProvider(BC)
45+
.setAlternateProvider(new GenericPSSOnlyProvider())
46+
.create(new SecureRandom());
47+
48+
implTestSignatureScheme(crypto, kp, SignatureScheme.rsa_pss_rsae_sha256, "SHA256withRSAandMGF1");
49+
implTestSignatureScheme(crypto, kp, SignatureScheme.rsa_pss_rsae_sha384, "SHA384withRSAandMGF1");
50+
implTestSignatureScheme(crypto, kp, SignatureScheme.rsa_pss_rsae_sha512, "SHA512withRSAandMGF1");
51+
}
52+
53+
private void implTestSignatureScheme(JcaTlsCrypto crypto, KeyPair kp, int signatureScheme, String verifyAlgorithm)
54+
throws Exception
55+
{
56+
PrivateKey opaqueKey = new OpaquePrivateKey(kp.getPrivate());
57+
58+
JcaTlsRSAPSSSigner signer = new JcaTlsRSAPSSSigner(crypto, opaqueKey, signatureScheme);
59+
60+
TlsStreamSigner streamSigner = signer.getStreamSigner(
61+
SignatureScheme.getSignatureAndHashAlgorithm(signatureScheme));
62+
63+
byte[] message = Strings.toByteArray("RSA-PSS via generic-name-only alternate provider");
64+
65+
OutputStream sOut = streamSigner.getOutputStream();
66+
sOut.write(message, 0, message.length);
67+
sOut.close();
68+
69+
byte[] signature = streamSigner.getSignature();
70+
71+
Signature verifier = Signature.getInstance(verifyAlgorithm, BC);
72+
verifier.initVerify(kp.getPublic());
73+
verifier.update(message, 0, message.length);
74+
75+
assertTrue(SignatureScheme.getText(signatureScheme), verifier.verify(signature));
76+
}
77+
78+
/**
79+
* Mimics SunMSCAPI: the only registered signature is the generic "RSASSA-PSS", the digest must
80+
* be supplied via setParameter, and only the provider's own (opaque) key type is accepted.
81+
*/
82+
public static class GenericPSSOnlyProvider
83+
extends Provider
84+
{
85+
GenericPSSOnlyProvider()
86+
{
87+
super("GenericPSSOnly", 1.0, "signs with the generic RSASSA-PSS algorithm name only");
88+
89+
put("Signature.RSASSA-PSS", GenericPSSSignatureSpi.class.getName());
90+
}
91+
}
92+
93+
static class OpaquePrivateKey
94+
implements PrivateKey
95+
{
96+
final PrivateKey inner;
97+
98+
OpaquePrivateKey(PrivateKey inner)
99+
{
100+
this.inner = inner;
101+
}
102+
103+
public String getAlgorithm()
104+
{
105+
return inner.getAlgorithm();
106+
}
107+
108+
public String getFormat()
109+
{
110+
return null;
111+
}
112+
113+
public byte[] getEncoded()
114+
{
115+
return null;
116+
}
117+
}
118+
119+
public static class GenericPSSSignatureSpi
120+
extends SignatureSpi
121+
{
122+
private final Signature delegate;
123+
private boolean parameterSet = false;
124+
125+
public GenericPSSSignatureSpi()
126+
throws Exception
127+
{
128+
this.delegate = Signature.getInstance("RSASSA-PSS", BC);
129+
}
130+
131+
protected void engineInitSign(PrivateKey privateKey)
132+
throws InvalidKeyException
133+
{
134+
if (!(privateKey instanceof OpaquePrivateKey))
135+
{
136+
throw new InvalidKeyException("key type not supported by this provider");
137+
}
138+
139+
delegate.initSign(((OpaquePrivateKey)privateKey).inner);
140+
}
141+
142+
protected void engineInitSign(PrivateKey privateKey, SecureRandom random)
143+
throws InvalidKeyException
144+
{
145+
if (!(privateKey instanceof OpaquePrivateKey))
146+
{
147+
throw new InvalidKeyException("key type not supported by this provider");
148+
}
149+
150+
delegate.initSign(((OpaquePrivateKey)privateKey).inner, random);
151+
}
152+
153+
protected void engineInitVerify(PublicKey publicKey)
154+
throws InvalidKeyException
155+
{
156+
delegate.initVerify(publicKey);
157+
}
158+
159+
protected void engineSetParameter(AlgorithmParameterSpec params)
160+
throws InvalidAlgorithmParameterException
161+
{
162+
delegate.setParameter(params);
163+
parameterSet = true;
164+
}
165+
166+
protected void engineUpdate(byte b)
167+
throws SignatureException
168+
{
169+
checkParameterSet();
170+
delegate.update(b);
171+
}
172+
173+
protected void engineUpdate(byte[] b, int off, int len)
174+
throws SignatureException
175+
{
176+
checkParameterSet();
177+
delegate.update(b, off, len);
178+
}
179+
180+
protected byte[] engineSign()
181+
throws SignatureException
182+
{
183+
checkParameterSet();
184+
return delegate.sign();
185+
}
186+
187+
protected boolean engineVerify(byte[] sigBytes)
188+
throws SignatureException
189+
{
190+
checkParameterSet();
191+
return delegate.verify(sigBytes);
192+
}
193+
194+
protected void engineSetParameter(String param, Object value)
195+
{
196+
throw new UnsupportedOperationException("engineSetParameter unsupported");
197+
}
198+
199+
protected Object engineGetParameter(String param)
200+
{
201+
throw new UnsupportedOperationException("engineGetParameter unsupported");
202+
}
203+
204+
private void checkParameterSet()
205+
throws SignatureException
206+
{
207+
// like SunMSCAPI, the generic algorithm has no default digest
208+
if (!parameterSet)
209+
{
210+
throw new SignatureException("parameters required for RSASSA-PSS signature");
211+
}
212+
}
213+
}
214+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package org.bouncycastle.tls.crypto.test;
2+
3+
import org.bouncycastle.test.PrintTestResult;
4+
5+
import junit.extensions.TestSetup;
6+
import junit.framework.Test;
7+
import junit.framework.TestCase;
8+
import junit.framework.TestSuite;
9+
10+
// NOTE: jdk1.4 overlay - omits JcaTlsRSAPSSAltProviderTest (excluded in ant/jdk14.xml): the jdk1.4
11+
// JcaTlsCrypto overlay deliberately drops the PKCS#11/SunMSCAPI PSS signature-name fallbacks.
12+
public class AllTests
13+
extends TestCase
14+
{
15+
public static void main(String[] args)
16+
throws Exception
17+
{
18+
PrintTestResult.printResult(junit.textui.TestRunner.run(suite()));
19+
}
20+
21+
public static Test suite()
22+
throws Exception
23+
{
24+
TestSuite suite = new TestSuite("TLS crypto tests");
25+
26+
suite.addTestSuite(BcTlsCryptoTest.class);
27+
suite.addTestSuite(JcaTlsCryptoTest.class);
28+
29+
return new BCTestSetup(suite);
30+
}
31+
32+
static class BCTestSetup
33+
extends TestSetup
34+
{
35+
public BCTestSetup(Test test)
36+
{
37+
super(test);
38+
}
39+
40+
protected void setUp()
41+
{
42+
43+
}
44+
45+
protected void tearDown()
46+
{
47+
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)