Skip to content

Commit 46f8389

Browse files
committed
Add an AnimalSniffer Android API level 26 compatibility gate to the Gradle build, checking each published module's base classes against the Android 8.0 platform signature and failing on a java/javax platform API absent there - the class of regression behind github #2369 - with a per-module allow-list for the intentionally platform-absent references (the optional JNDI fetchers and the legacy bcmail java.awt DataFlavor), based on the initial implementation in github #336.
1 parent 1df82f9 commit 46f8389

5 files changed

Lines changed: 141 additions & 0 deletions

File tree

‎CONTRIBUTORS.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,7 @@
605605
<li>rimuln &lt;https://github.com/rimuln&gt; - diagnosis and fix for PKCS12 getCertificateAlias returning the alias of an unrelated certificate, tracing it to the alias and certificate enumerations of the keystore's certs table diverging in order once keys() enumerated a copy (issue #2384, PR #2385).</li>
606606
<li>Yu Bao &lt;yubao@paypal.com&gt; - reporting an API gap, on behalf of the PayPal Cyber Security Team, that the high-level OpenPGP message API (OpenPGPMessageProcessor / OpenPGPMessageInputStream) gave a caller no way to bound how far a compressed data packet expands, where the low-level PGPCompressedData it wraps has carried a bounded getDataStream(long) overload all along, and that OpenPGPPolicy exposed no equivalent property to set. Suggesting a protocol whitelist for CRL Distribution Point fetching, which is now the org.bouncycastle.x509.CRLDP_protocols property, and suggesting that an OCSP response was read up to the length the responder declared for itself, now capped by org.bouncycastle.ocsp.max_response_size, and suggesting bounds on the OpenPGP ASCII armor headers, now capped by org.bouncycastle.openpgp.max_armor_header_length and org.bouncycastle.openpgp.max_armor_headers.</li>
607607
<li>Arpan Sharma &lt;https://github.com/Arpan0995&gt; - initial audit of BCPQC provider consistency starting with HQC, which led to the exposure of a number of issues in the JCA provider service interfaces for other BCPQC algorithms.</li>
608+
<li>Flowdalic &lt;https://github.com/Flowdalic&gt; - initial implementation of an AnimalSniffer-based Android API-level compatibility check for the Gradle build (PR #336).</li>
608609
</ul>
609610
</body>
610611
</html>

‎build.gradle‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,3 +398,38 @@ task copyMavenJars(type: Copy) {
398398

399399
apply from: "gradle/cbom.gradle"
400400
apply from: "gradle/sbom.gradle"
401+
402+
// Android API-level compatibility gate - see gradle/animalsniffer.gradle (github #336).
403+
// Per jar-producing module: androidIgnored = packages treated as available (the module's
404+
// own generated code and its bundled runtime dependencies); androidAllowed = substrings of
405+
// the remaining, intentionally platform-absent references that are permitted.
406+
def androidApiConfig = [
407+
util : [ignored: [],
408+
allowed: []],
409+
prov : [ignored: [],
410+
allowed: ['javax.naming.']], // optional LDAP cert-store (JNDI absent on Android)
411+
pkix : [ignored: [],
412+
allowed: ['javax.naming.']], // optional LDAP CRL + DANE fetchers
413+
pg : [ignored: [],
414+
allowed: []],
415+
tls : [ignored: [],
416+
// A JDK-version-specific SSLSocketFactory.createSocket overload and a ConcurrentHashMap
417+
// covariant-return keySet(), both absent from Android 8.0 but not reached on Android in
418+
// practice - the createSocket overload is an optional JSSE utility path callers do not invoke.
419+
allowed: ['createSocket(java.net.Socket, java.io.InputStream, boolean)',
420+
'java.util.concurrent.ConcurrentHashMap.keySet']],
421+
mail : [ignored: ['javax.mail.*', 'javax.activation.*'],
422+
allowed: ['java.awt.']], // legacy javax.activation 1.x ActivationDataFlavor (github #242)
423+
jmail: [ignored: ['jakarta.mail.*', 'jakarta.activation.*'],
424+
allowed: []],
425+
mls : [ignored: ['mls_client.*', 'com.google.*', 'io.grpc.*'],
426+
allowed: []],
427+
]
428+
androidApiConfig.each { moduleName, cfg ->
429+
def target = findProject(":${moduleName}")
430+
if (target != null) {
431+
target.ext.androidIgnoredPackages = cfg.ignored
432+
target.ext.androidAllowedRefs = cfg.allowed
433+
target.apply from: rootProject.file('gradle/animalsniffer.gradle')
434+
}
435+
}

‎docs/releasenotes.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ <h3>2.1.3 Additional Features and Functionality</h3>
176176
<li>FrodoKEM and Classic McEliece are now reachable through the javax.crypto.KEM API (JDK 21, JEP 452), which previously only ML-KEM, SM9, NTRU, NTRU Prime and HQC were. The standard BC provider registers KEM.FRODOKEM and KEM.CMCE, plus one parameter-set locked service for each of FrodoKEM's eight and Classic McEliece's sixteen ISO/IEC 18033-2:2006/Amd 2:2026 sets, each with the usual object identifier aliases so a caller dispatching on the OID in a received encoding finds the service. As with the other KEMs the implementations live in the multi-release jar's version 17 tree (org.bouncycastle.jcajce.provider.asymmetric.frodokem.FrodoKEMSpi and .cmce.CMCEKEMSpi with their Encapsulator/Decapsulator peers) and the registrations are gated on SpiUtil.hasKEM(), so on a JDK where javax.crypto.KEM is absent nothing is registered and the existing Cipher, KeyGenerator and KeyFactory services are unaffected. With a null spec the shared secret is the mechanism's own session key - the interoperable form - and a KTSParameterSpec KDF may be layered on top for generic use. Note FrodoKEM differs from ML-KEM in that its session key size follows the parameter set, 192 bits for the 976 sets and 256 for the 1344 sets, so the no-KDF secret size is taken from the key rather than assumed to be 256 bits; Classic McEliece is 256 bits throughout. For the same reason a KDF-less spec asking for more bits than the parameter set produces is refused with an InvalidAlgorithmParameterException naming the set and both sizes, rather than being quietly shortened the way the KTS key-wrapping path does - javax.crypto.KEM validates encapsulate()'s range against secretSize(), so that size has to be honest. The same applies to everything else a KTSParameterSpec can carry that a KEM cannot honour, since the spec validates none of it itself and each otherwise failed as an undeclared unchecked exception out of encapsulate() / decapsulate() rather than as a spec failure the caller can act on: a key size that is not a positive whole number of bytes (one below eight bits yielded a zero-length secret key, one that was not a whole number of bytes silently delivered fewer bits than were asked for, and one within seven of Integer.MAX_VALUE overflowed the rounding up of the byte count), a KDF algorithm identifier naming a KDF or digest the provider cannot service, and an absent key algorithm name. The validation, the algorithm-name reconciliation and the derivation of the secret key itself are shared as new org.bouncycastle.jcajce.provider.asymmetric.util.KdfUtil.resolveKemSpec, resolveAlgorithm and makeSecretKey methods rather than duplicated per KEM. Note makeSecretKey erases the secret it is passed, as the neighbouring makeKeyBytes already did, and validates the requested range before deriving so that an out-of-range request cannot reach SecretKeySpec after the secret has been erased; a caller has to take the encapsulation from the mechanism's output before calling it, and destroy that output afterwards, which is deliberately left at the call site so the ordering stays visible, and every javax.crypto.KEM encapsulator and decapsulator in the provider - ML-KEM, SM9, NTRU, NTRU Prime and HQC as well as the two added here - now reconciles the requested algorithm name through the shared method, which each previously carried its own identical copy of. Behaviour is unchanged, including the exception text for a name the spec does not authorise.</li>
177177
<li>NTRU LPRime, NTRU+ and SMAUG-T are now reachable through the javax.crypto.KEM API as well, which completes the BCPQC KEMs: each already had Cipher, KeyGenerator, KeyFactory and KeyPairGenerator services and only the KEM one was missing. NTRU LPRime gets KEM.NTRULPRIME, a family level service matching the SNTRU Prime counterpart registered beside it in the same class, whose absence was the whole difference between the two. NTRU+ gets KEM.NTRUPLUS and SMAUG-T KEM.SMAUGT, each with one parameter-set locked service per set, mirroring their other services. As elsewhere the implementations are multi-release jar version 17 classes gated on SpiUtil.hasKEM(), and they share KdfUtil.resolveKemSpec and resolveAlgorithm with the other KEMs rather than repeating the spec validation. NTRULPRimeParameters and SmaugTParameters gain a getEncapsulationLength() so the encapsulating side, which holds only a public key, derives the size from the same place the extractor does instead of repeating the expression or reaching for a package-private engine. Note the NTRU+ decapsulator constructs its extractor per call: an NTRUPlusKEMExtractor builds an NTRUPlusEngine, which keeps one SHAKE instance in a field, so sharing one across the concurrent decapsulate calls javax.crypto.KEM permits returned shared secrets that did not match the sender's. NTRU LPRime and SMAUG-T carry no such state and share an extractor. The spec validation added for FrodoKEM and Classic McEliece is now applied by every KEM in the provider except SM9: ML-KEM, HQC, NTRU and SNTRU Prime previously accepted a KDF-less KTSParameterSpec asking for more bits than the mechanism produces and then failed with an ArrayIndexOutOfBoundsException out of encapsulate(), where they now refuse the spec with an InvalidAlgorithmParameterException naming the parameter set and both sizes. SM9 does not take the shared validation, as its own GM/T 0044.4 KDF produces the shared secret at whatever size was requested - there is no fixed session key to bound a KDF-less request against, and a size that is not a whole number of bytes is a legitimate SM9 request where the other KEMs must refuse it - but the checks that do carry over are applied by KEM.SM9-KEM itself: a spec with no key algorithm name or a non-positive key size is rejected when the encapsulator or decapsulator is created, with the same InvalidAlgorithmParameterException, where the null name previously surfaced as a NullPointerException and the non-positive size as the key generator's own IllegalArgumentException out of the KEM operations.</li>
178178
<li>The new org.bouncycastle.x509.CRLDP_protocols property is an optional whitelist of the protocols a CRL Distribution Point may name, applied by the CrlCache behind both the provider's CertPath validator and X509RevocationChecker before any connection is opened, and ahead of the cache, so an entry already held for a distribution point is no way around it. It is a comma separated list matched without regard to case - "http,https,ldap" refuses a distribution point naming ftp, file, jar or anything else the JVM happens to have a URL handler registered for, with a CRLException naming the protocol. Unset or empty, the default, leaves the protocol unrestricted: RFC 5280 sec. 4.2.1.13 requires a distribution point URI to name a protocol but does not restrict which, and BouncyCastle supports http, https, ftp and ldap here, so this is a policy for deployments that want a narrower set rather than a new default. Note the fetch it governs only happens at all where org.bouncycastle.x509.enableCRLDP is set (see Defects Fixed above).</li>
179+
<li>The Gradle build now checks Android compatibility with AnimalSniffer: each published module's base (Java 8) classes are verified against the Android API level 26 (Android 8.0) platform signature, so a reference to a java.* / javax.* API absent from that platform - the class of regression behind the org.bouncycastle.util.BigIntegers.intValueExact NoSuchMethodError seen on older Android (see Defects Fixed above, github #2369) - fails the build rather than reaching a consumer's device as a runtime error. Only the base classes are checked, not the multi-release overlays, since those are selected by JDK version at runtime and never load on Android. A small allow-list covers the references that are intentionally platform-absent: the optional JNDI-based fetchers (javax.naming - the LDAP CRL and certificate stores in bcprov and bcpkix, and the DANE fetcher), which are inert on Android as it ships no JNDI, and the legacy bcmail S/MIME content handlers' java.awt.datatransfer.DataFlavor reference, which cannot be dropped while javax.activation 1.x's ActivationDataFlavor extends it - Android consumers should use bcjmail, which carries no such reference (github #242). Based on the initial implementation in github #336.</li>
179180
</ul>
180181

181182
<h3>2.1.4 Additional Notes</h3>

‎gradle.properties‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,11 @@ release.debug=false
99
org.gradle.java.installations.auto-detect=false
1010
org.gradle.java.installations.auto-download=false
1111
org.gradle.java.installations.fromEnv=BC_JDK8,BC_JDK11,BC_JDK17,BC_JDK21,BC_JDK25
12+
13+
# Android API-level compatibility gate - see gradle/animalsniffer.gradle (github #336).
14+
# API level 26 is Android 8.0 (Oreo); the most recent Android compatibility report
15+
# (github #2369) was against API 29, so 26 is checked with margin to spare.
16+
androidApiLevel=26
17+
androidSignatureVersion=8.0.0_r2
18+
animalSnifferVersion=1.24
19+
animalSnifferAsmVersion=9.7

‎gradle/animalsniffer.gradle‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
// Android API-level compatibility gate (a modernised github #336).
2+
//
3+
// Checks a module's base (--release 8) classes against an Android platform
4+
// signature with AnimalSniffer, failing the build on a reference to a
5+
// java.* / javax.* platform API absent from that API level - the class of
6+
// regression behind the BigIntegers.intValueExact NoSuchMethodError on older
7+
// Android (github #2369). Only the base classes are checked, never the
8+
// multi-release overlays, which are selected by JDK version at runtime and
9+
// never load on Android.
10+
//
11+
// The engine is org.codehaus.mojo:animal-sniffer's SignatureChecker, loaded
12+
// off a dedicated configuration so it never touches the build's own classpath.
13+
// Two per-module knobs configure it:
14+
// ext.androidIgnoredPackages - packages treated as available (the module's
15+
// own code and its bundled runtime dependencies), suppressed at source.
16+
// ext.androidAllowedRefs - substrings of the remaining, intentionally
17+
// platform-absent references that are permitted (e.g. the optional JNDI
18+
// fetchers, or bcmail's legacy java.awt DataFlavor). Anything not covered
19+
// by either fails the build.
20+
21+
configurations {
22+
animalSnifferTool
23+
androidApiSignature
24+
}
25+
26+
dependencies {
27+
animalSnifferTool "org.codehaus.mojo:animal-sniffer:${animalSnifferVersion}"
28+
animalSnifferTool "org.ow2.asm:asm:${animalSnifferAsmVersion}"
29+
androidApiSignature "net.sf.androidscents.signature:android-api-level-${androidApiLevel}:${androidSignatureVersion}@signature"
30+
}
31+
32+
def androidApiCheck = tasks.register('androidApiCheck') {
33+
group = 'verification'
34+
description = "Checks the base classes for Android API level ${androidApiLevel} compatibility"
35+
dependsOn tasks.named('classes')
36+
37+
def toolCp = configurations.animalSnifferTool
38+
def signatureCfg = configurations.androidApiSignature
39+
def classDirs = sourceSets.main.output.classesDirs
40+
def ignoredPackages = (project.findProperty('androidIgnoredPackages') ?: []) as List
41+
def allowedRefs = (project.findProperty('androidAllowedRefs') ?: []) as List
42+
def apiLevel = androidApiLevel
43+
def moduleName = project.name
44+
45+
inputs.files(toolCp, signatureCfg, classDirs)
46+
def marker = layout.buildDirectory.file("animalsniffer/android-api-${androidApiLevel}.ok")
47+
outputs.file(marker)
48+
49+
doLast {
50+
def loader = new URLClassLoader(
51+
toolCp.files.collect { it.toURI().toURL() } as URL[],
52+
(ClassLoader) getClass().classLoader)
53+
def checkerClass = loader.loadClass('org.codehaus.mojo.animal_sniffer.SignatureChecker')
54+
def loggerClass = loader.loadClass('org.codehaus.mojo.animal_sniffer.logging.Logger')
55+
56+
def violations = []
57+
def logger = java.lang.reflect.Proxy.newProxyInstance(loader, [loggerClass] as Class[],
58+
{ proxy, method, args ->
59+
if (method.name == 'error' && args && args[0] instanceof String) {
60+
violations << (String) args[0]
61+
}
62+
return null
63+
} as java.lang.reflect.InvocationHandler)
64+
65+
def ignoreSet = new HashSet<String>(ignoredPackages)
66+
ignoreSet.addAll(['org.bouncycastle.*',
67+
'org.jvnet.animal_sniffer.*',
68+
'org.codehaus.mojo.animal_sniffer.*',
69+
'org.objectweb.*'])
70+
71+
signatureCfg.singleFile.withInputStream { sigIn ->
72+
def checker = checkerClass
73+
.getConstructor(InputStream, Set, loggerClass)
74+
.newInstance(sigIn, ignoreSet, logger)
75+
classDirs.files.each { dir ->
76+
if (dir.isDirectory()) {
77+
checker.getClass().getMethod('process', File).invoke(checker, dir)
78+
}
79+
}
80+
}
81+
82+
def unexpected = violations.findAll { v -> !allowedRefs.any { a -> v.contains(a) } }
83+
.toUnique().sort()
84+
if (!unexpected.isEmpty()) {
85+
throw new GradleException(
86+
"Android API level ${apiLevel} incompatibilities in ${moduleName} (${unexpected.size()}):\n " +
87+
unexpected.take(60).join('\n '))
88+
}
89+
90+
def out = marker.get().asFile
91+
out.parentFile.mkdirs()
92+
out.text = "Android API ${apiLevel}: OK\n"
93+
}
94+
}
95+
96+
tasks.named('check') { dependsOn androidApiCheck }

0 commit comments

Comments
 (0)