From f56f71168e1a1496bbabc86377ee7a479bcf4a12 Mon Sep 17 00:00:00 2001 From: Sven Mitt Date: Wed, 14 Oct 2026 19:43:24 +0300 Subject: [PATCH] feat: add whitelisting to subject certificate policies, add known Estonian production policies as default, add to example test card policies WE2-1308 Signed-off-by: Sven Mitt --- README.md | 59 ++++++- example/README.md | 16 +- .../config/ValidationConfiguration.java | 72 +++++++- .../AuthTokenDTOAuthenticationProvider.java | 21 +++ .../config/TestValidatorConfiguration.java | 14 +- ...uthTokenDTOAuthenticationProviderTest.java | 77 +++++++++ .../SubjectCertificatePolicies.java | 55 +++++- ...rCertificateDisallowedPolicyException.java | 51 +++++- .../AuthTokenValidationConfiguration.java | 68 +++++++- .../validator/AuthTokenValidatorBuilder.java | 64 ++++++- .../validator/AuthTokenValidatorImpl.java | 6 +- .../SubjectCertificatePolicyValidator.java | 108 +++++++++++- .../SubjectCertificatePoliciesTest.java | 41 +++++ .../testutil/AuthTokenValidators.java | 30 +++- .../LegacyMobileIdCertificatePolicies.java | 24 +++ .../validator/AuthTokenCertificateTest.java | 101 +++++++++++ .../AuthTokenValidationConfigurationTest.java | 69 ++++++++ .../AuthTokenValidatorBuilderTest.java | 158 +++++++++++++++++- ...SubjectCertificatePolicyValidatorTest.java | 112 ++++++++++++- 19 files changed, 1098 insertions(+), 48 deletions(-) create mode 100644 example/src/test/java/eu/webeid/example/security/AuthTokenDTOAuthenticationProviderTest.java create mode 100644 src/test/java/eu/webeid/security/certificate/SubjectCertificatePoliciesTest.java create mode 100644 src/test/java/eu/webeid/security/testutil/LegacyMobileIdCertificatePolicies.java diff --git a/README.md b/README.md index f4c5105a..0b00d14f 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ import eu.webeid.security.challenge.ChallengeNonceStore; You must explicitly specify which **intermediate** certificate authorities (CAs) are trusted to issue the eID authentication and OCSP responder certificates. CA certificates can be loaded from either the truststore file, resources or any stream source. We use the [`CertificateLoader`](src/main/java/eu/webeid/security/certificate/CertificateLoader.java) helper class to load CA certificates from resources here, but consider using [the truststore file](example/src/main/java/eu/webeid/example/config/ValidationConfiguration.java) instead. -First, copy the trusted certificates, for example `ESTEID2018.cer`, to `resources/cacerts/`, then load the certificates as follows: +To accept both ID-card generations that are currently in use, copy the `ESTEID2018` intermediate certificate from [SK ID Solutions](https://www.skidsolutions.eu/resources/certificates/) and the `ESTEID2025` intermediate certificate from [Zetes](https://repository.eidpki.ee/crt/) to `resources/cacerts/`, then load both certificates as follows: ```java import java.io.IOException; @@ -111,7 +111,10 @@ import eu.webeid.security.certificate.CertificateLoader; ... private X509Certificate[] trustedIntermediateCACertificates() throws CertificateException, IOException { - return CertificateLoader.loadCertificatesFromResources("cacerts/ESTEID2018.cer"); + return CertificateLoader.loadCertificatesFromResources( + "cacerts/ESTEID2018.cer", + "cacerts/ESTEID2025.crt" + ); } ... ``` @@ -320,7 +323,57 @@ toTitleCase(CertificateData.getSubjectSurname(userCertificate).orElseThrow()); / The default validator uses the platform OCSP implementation to check certificate revocation. A revoked certificate or an unsuccessful revocation check causes authentication to fail. -Use `withDisallowedCertificatePolicies(ASN1ObjectIdentifier... policies)` to add disallowed certificate policies. Estonian Mobile-ID policies are disallowed by default because smart-card authentication must not accept Mobile-ID certificates. +Certificate policy allow-lists are selected by the subject certificate's exact issuer `X500Principal`. At build time, production Estonian identity-document policies from `ESTEID_PRODUCTION_DOCUMENT_POLICIES` are used when both the configured allow-list and deny-list are empty. Allow-lists and deny-lists cannot be configured together. Strict certificate policy validation is enabled by default: a matching issuer must contain one of its configured policy OIDs, and an issuer without an allow-list entry is rejected. Calling `withAllowedCertificatePolicies(issuer)` without policy OIDs removes that issuer's entry. If no allow-list or deny-list entries remain, the Estonian defaults are used. + +Use `withAllowedCertificatePolicies(X500Principal issuer, ASN1ObjectIdentifier... policies)` to define a custom allow-list. Repeated calls configure all supported issuers on the same validator. The following example explicitly configures both Estonian ID-card generations in one builder chain. + +```java +AuthTokenValidator tokenValidator = new AuthTokenValidatorBuilder() + .withSiteOrigin(URI.create("https://example.org")) + .withTrustedCertificateAuthorities(trustedIntermediateCACertificates()) + .withAllowedCertificatePolicies(ESTEID2018_ISSUER, ESTEID_PRODUCTION_DOCUMENT_POLICIES.get(ESTEID2018_ISSUER)) + .withAllowedCertificatePolicies(ESTEID2025_ISSUER, ESTEID_PRODUCTION_DOCUMENT_POLICIES.get(ESTEID2025_ISSUER)) + .build(); +``` + +To accept only identity cards issued to Estonian citizens or European Union citizens, configure the two corresponding policy OIDs for each supported certificate generation: + +```java +AuthTokenValidator tokenValidator = new AuthTokenValidatorBuilder() + .withSiteOrigin(URI.create("https://example.org")) + .withTrustedCertificateAuthorities(trustedIntermediateCACertificates()) + .withAllowedCertificatePolicies( + ESTEID2018_ISSUER, + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.1"), // Identity card of Estonian citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.2") // Identity card of European Union citizens + ) + .withAllowedCertificatePolicies( + ESTEID2025_ISSUER, + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.1"), // Identity card of Estonian citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.2") // Identity card of European Union citizens + ) + .build(); +``` + +For this restriction, trust only the intermediate CAs that issue the supported Estonian ID cards. Other policies from the configured issuers, including digital identity cards, residence permit cards and diplomatic identity cards, are rejected. Certificates from an issuer without an allow-list entry are also rejected. + +For another country, add each supported issuer and its policy OIDs to the same builder chain and provide the corresponding trusted intermediate CAs. + +To retain the previous lenient behaviour, call `allowUnlistedIssuers(true)`. The allow-list then applies only to issuers with a configured entry; other issuers are not restricted by certificate policy. + +To restore the old deny-list behaviour, configure only disallowed policies. Configuring a deny-list prevents the default Estonian allow-list from being applied: +```java +AuthTokenValidator tokenValidator = new AuthTokenValidatorBuilder() + .withSiteOrigin(URI.create("https://example.org")) + .withTrustedCertificateAuthorities(trustedIntermediateCACertificates()) + .withDisallowedCertificatePolicies( + new ASN1ObjectIdentifier("1.3.6.1.4.1.10015.1.3.1"), // ESTEID-SK 2015 Mobile-ID policy v1 + new ASN1ObjectIdentifier("1.3.6.1.4.1.10015.1.3.2"), // ESTEID-SK 2015 Mobile-ID policy v2 + new ASN1ObjectIdentifier("1.3.6.1.4.1.10015.1.3.3"), // ESTEID-SK 2015 Mobile-ID policy v3 + new ASN1ObjectIdentifier("1.3.6.1.4.1.10015.1.3") // ESTEID-SK 2015 Mobile-ID policy + ) + .build(); +``` For more advanced revocation requirements, supply a `CertificateRevocationChecker` with `withCertificateRevocationChecker(...)`. The [OCSP configuration guide](src/main/java/eu/webeid/ocsp/README.md) covers custom implementations, the bundled OCSP checker, custom PKIX checkers, responder selection, HTTP settings, and nonce policies. diff --git a/example/README.md b/example/README.md index f4c9ebbe..3d7f8fce 100644 --- a/example/README.md +++ b/example/README.md @@ -43,7 +43,17 @@ The algorithm, which performs the validation of the Web eID authentication token In case you need to provide your own CA certificates, either add the `.cer` files to the `src/main/resources/certs/{dev,prod}` profile-specific directory or add the certificates to the truststore file. -### 4. Choose either the `dev` or `prod` profile +### 4. Configure allowed certificate policies + +Certificate policy validation is strict by default. The `prod` profile uses the library's built-in Estonian production +identity-document policies, while the `dev` profile registers the Estonian test-card issuers and policies in +`ValidationConfiguration.ESTEID_TEST_DOCUMENT_POLICIES`. + +To support an issuer that is not already listed, add it with +`withAllowedCertificatePolicies(X500Principal issuer, ASN1ObjectIdentifier... policies)`. If policy validation must +remain lenient for unlisted issuers, explicitly call `allowUnlistedIssuers(true)` instead. + +### 5. Choose either the `dev` or `prod` profile If you have a test eID card, use the `dev` profile. In this case access to paid services is not required, but you need to upload the authentication and signing certificates of the test card to the test OCSP responder database as described in section _[Using DigiDoc4j in test mode with the `dev` profile](#using-digidoc4j-in-test-mode-with-the-dev-profile)_ below. The `dev` profile is activated by default. @@ -51,7 +61,7 @@ If you only have a production eID card, use the `prod` profile. You can still te You can specify the profile as a command-line argument to the Maven wrapper command `./mvnw`, for example `./mvnw -Pprod ...`. -### 5. Run the application +### 6. Run the application Spring Boot web applications can be run from the command-line. You need to have the Java Development Kit 17 installed for building the application package and running the application. @@ -134,7 +144,7 @@ The `src/tests` directory contains the application test suite. The most importan ### Configuration -As described in section [_4. Choose either the `dev` or `prod` profile_](#4-choose-either-the-dev-or-prod-profile) above, the application has two different configuration profiles: `dev` profile for running the application in development mode and `prod` profile for production mode. The `dev` profile is activated by default. +As described in section [_5. Choose either the `dev` or `prod` profile_](#5-choose-either-the-dev-or-prod-profile) above, the application has two different configuration profiles: `dev` profile for running the application in development mode and `prod` profile for production mode. The `dev` profile is activated by default. The profile-specific configuration files `src/main/resources/application-{dev,prod}.yaml` contain the `web-eid-auth-token.validation.use-digidoc4j-prod-configuration` setting that configures DigiDoc4j either in test or production mode, and a setting for configuring the origin URL as described in section [_2. Configure the origin URL_](#2-configure-the-origin-url) above. Additionally, the `web-eid-auth-token.validation.truststore-password` setting specifies the truststore password used in the `prod` profile. diff --git a/example/src/main/java/eu/webeid/example/config/ValidationConfiguration.java b/example/src/main/java/eu/webeid/example/config/ValidationConfiguration.java index 188d2df2..73c23af0 100644 --- a/example/src/main/java/eu/webeid/example/config/ValidationConfiguration.java +++ b/example/src/main/java/eu/webeid/example/config/ValidationConfiguration.java @@ -3,6 +3,10 @@ package eu.webeid.example.config; +import java.util.Map; +import java.util.Set; +import javax.security.auth.x500.X500Principal; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectFactory; @@ -42,6 +46,60 @@ public class ValidationConfiguration { private static final String CERTS_RESOURCE_PATH = "/certs/"; public static final String TRUSTED_CERTIFICATES_JKS = "trusted_certificates.jks"; + /** + * Test document policies for Estonian ID cards, digital ID cards, residence permit cards and diplomatic + * identity cards issued under the ESTEID2018 and eID certificate-policy generations, grouped by issuer distinguished name. + * + * @see + * ID.ee certificate policy index for Estonian identity documents + * @see + * IDEMIA-generation certificate policy + * @see + * Thales-generation certificate policy + * @see + * ESTEID2025 certificate profile + */ + public static final Map> ESTEID_TEST_DOCUMENT_POLICIES = Map.of( + new X500Principal( + "CN=TEST of ESTEID2018,2.5.4.97=#0c0e4e545245452d3130373437303133,O=SK ID Solutions AS,C=EE" + ), Set.of( + // https://www.skidsolutions.eu/upload/files/SK-CPR-ESTEID2018-EN-v1_3_20220217.pdf 2.2.3. Certificate Policy + // 1.3.6.1.4.1.51361.1.{1 or 2} - System Sub-OID: production = 1; test = 2 + // Example OID 1:Identity card of Estonian citizen (test): 51361.1.2.1 + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.1"), // Identity card of Estonian citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.2"), // Identity card of European Union citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.3"), // Digital identity card for Estonian residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.4"), // Digital identity card for e-residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.5"), // Residence permit card for long-term residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.6"), // Residence permit card for temporary residents and NATO SOFA + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.7"), // Residence permit card for family members of European Union citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51455.1.2.1"), // Diplomatic identity card + + // Some test ID-cards that have production OID-s + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.1"), // Identity card of Estonian citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.2"), // Identity card of European Union citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.3"), // Digital identity card for Estonian residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.4"), // Digital identity card for e-residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.5"), // Residence permit card for long-term residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.6"), // Residence permit card for temporary residents and NATO SOFA + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.7"), // Residence permit card for family members of European Union citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51455.1.1.1") // Diplomatic identity card + ), + new X500Principal( + "C=EE,O=Zetes Estonia OÜ,2.5.4.97=#0c0e4e545245452d3137303636303439,CN=Test ESTEID2025" + ), Set.of( + // https://www.id.ee/wp-content/uploads/2026/06/eid-cp-v-2.0_04.06.2026_allkirjastatud.pdf Chapter 1.2. Document Name and Identification + // https://repository.eidpki.ee/static/documents/CertificateProfiles-20260520.pdf According to the general practice, the propriotary OIDs for UAT and test certificates will be prefixed with “2.999.“ to differentiate them from the production OID’s. + new ASN1ObjectIdentifier("2.999.1.3.6.1.4.1.51361.2.1.1"), // Identity card of Estonian citizens + new ASN1ObjectIdentifier("2.999.1.3.6.1.4.1.51361.2.1.2"), // Identity card of European Union citizens + new ASN1ObjectIdentifier("2.999.1.3.6.1.4.1.51361.2.1.3"), // Residence permit card for long-term residents + new ASN1ObjectIdentifier("2.999.1.3.6.1.4.1.51361.2.1.4"), // Residence permit card for temporary residents and the right of stay in the Republic of Estonia. + new ASN1ObjectIdentifier("2.999.1.3.6.1.4.1.51361.2.1.5"), // Residence permit card for family members of EU and UK citizens and the right of residence of UK citizens + new ASN1ObjectIdentifier("2.999.1.3.6.1.4.1.51361.2.1.6"), // Digital identity card of e-residents + new ASN1ObjectIdentifier("2.999.1.3.6.1.4.1.51455.2.1.1") // Diplomatic identity card + ) + ); + @Value("${spring.profiles.active}") private String activeProfile; @@ -61,11 +119,17 @@ public ChallengeNonceGenerator generator(ChallengeNonceStore challengeNonceStore @Bean public AuthTokenValidator validator(YAMLConfig yamlConfig) { try { - return new AuthTokenValidatorBuilder() - .withSiteOrigin(URI.create(yamlConfig.getLocalOrigin())) + AuthTokenValidatorBuilder authTokenValidatorBuilder = new AuthTokenValidatorBuilder().withSiteOrigin(URI.create(yamlConfig.getLocalOrigin())) + // For non-EstEID certificates, use withAllowedCertificatePolicies() or explicitly enable + // allowUnlistedIssuers(true). .withTrustedCertificateAuthorities(loadTrustedCACertificatesFromCerFiles()) - .withTrustedCertificateAuthorities(loadTrustedCACertificatesFromTrustStore(yamlConfig)) - .build(); + .withTrustedCertificateAuthorities(loadTrustedCACertificatesFromTrustStore(yamlConfig)); + + if (!activeProfile.equals("prod")) { + ESTEID_TEST_DOCUMENT_POLICIES.forEach(authTokenValidatorBuilder::withAllowedCertificatePolicies); + } + + return authTokenValidatorBuilder.build(); } catch (JceException e) { throw new RuntimeException("Error building the Web eID auth token validator.", e); } diff --git a/example/src/main/java/eu/webeid/example/security/AuthTokenDTOAuthenticationProvider.java b/example/src/main/java/eu/webeid/example/security/AuthTokenDTOAuthenticationProvider.java index 86ed45eb..79912240 100644 --- a/example/src/main/java/eu/webeid/example/security/AuthTokenDTOAuthenticationProvider.java +++ b/example/src/main/java/eu/webeid/example/security/AuthTokenDTOAuthenticationProvider.java @@ -7,8 +7,10 @@ import eu.webeid.security.authtoken.WebEidAuthToken; import eu.webeid.security.challenge.ChallengeNonceStore; import eu.webeid.security.exceptions.AuthTokenException; +import eu.webeid.security.exceptions.UserCertificateDisallowedPolicyException; import eu.webeid.security.validator.AuthTokenValidator; import eu.webeid.security.validator.ValidationInfo; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AuthenticationProvider; @@ -20,6 +22,7 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.stereotype.Component; +import javax.security.auth.x500.X500Principal; import java.security.cert.CertificateEncodingException; import java.util.List; @@ -56,6 +59,9 @@ public Authentication authenticate(Authentication auth) throws AuthenticationExc final String nonce = challengeNonceStore.getAndRemove().getBase64EncodedNonce(); final ValidationInfo validationInfo = tokenValidator.validate(authToken, nonce); return WebEidAuthentication.fromCertificate(validationInfo.subjectCertificate(), authorities); + } catch (UserCertificateDisallowedPolicyException e) { + logAllowedCertificatePolicyConfiguration(e); + throw new AuthenticationServiceException("Web eID token validation failed", e); } catch (AuthTokenException e) { throw new AuthenticationServiceException("Web eID token validation failed", e); } catch (CertificateEncodingException e) { @@ -63,6 +69,21 @@ public Authentication authenticate(Authentication auth) throws AuthenticationExc } } + private static void logAllowedCertificatePolicyConfiguration( + UserCertificateDisallowedPolicyException exception) { + exception.getCertificateIssuer().ifPresent(issuer -> LOG.warn( + "Certificate policy allow-list rejected an unverified certificate. " + + "If this issuer is intentionally supported and its CA is trusted, configure it with " + + "AuthTokenValidatorBuilder.withAllowedCertificatePolicies(...). " + + "issuerRFC2253='{}', certificatePolicyOids={}", + issuer.getName(X500Principal.RFC2253), + exception.getCertificatePolicies().stream() + .map(ASN1ObjectIdentifier::getId) + .sorted() + .toList() + )); + } + @Override public boolean supports(Class authentication) { LOG.info("supports(): {}", authentication); diff --git a/example/src/test/java/eu/webeid/example/config/TestValidatorConfiguration.java b/example/src/test/java/eu/webeid/example/config/TestValidatorConfiguration.java index f838a2da..1c676e17 100644 --- a/example/src/test/java/eu/webeid/example/config/TestValidatorConfiguration.java +++ b/example/src/test/java/eu/webeid/example/config/TestValidatorConfiguration.java @@ -3,6 +3,8 @@ package eu.webeid.example.config; +import static eu.webeid.example.config.ValidationConfiguration.ESTEID_TEST_DOCUMENT_POLICIES; + import eu.webeid.security.exceptions.JceException; import eu.webeid.security.validator.AuthTokenValidator; import eu.webeid.security.validator.AuthTokenValidatorBuilder; @@ -10,6 +12,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; +import javax.security.auth.x500.X500Principal; import java.net.URI; import java.util.List; @@ -26,13 +29,18 @@ public class TestValidatorConfiguration { @Primary AuthTokenValidator validatorWithoutOcspCall(ValidationConfiguration validationConfiguration, YAMLConfig yamlConfig) throws JceException { - return new AuthTokenValidatorBuilder() + AuthTokenValidatorBuilder authTokenValidatorBuilder = new AuthTokenValidatorBuilder() .withSiteOrigin(URI.create(yamlConfig.getLocalOrigin())) + .allowUnlistedIssuers(true) .withTrustedCertificateAuthorities(validationConfiguration.loadTrustedCACertificatesFromCerFiles()) .withTrustedCertificateAuthorities(validationConfiguration.loadTrustedCACertificatesFromTrustStore(yamlConfig)) + // Do not call the real OCSP service in tests. - .withCertificateRevocationChecker((subjectCertificate, issuerCertificate) -> List.of()) - .build(); + .withCertificateRevocationChecker((subjectCertificate, issuerCertificate) -> List.of()); + + ESTEID_TEST_DOCUMENT_POLICIES.forEach(authTokenValidatorBuilder::withAllowedCertificatePolicies); + + return authTokenValidatorBuilder.build(); } } diff --git a/example/src/test/java/eu/webeid/example/security/AuthTokenDTOAuthenticationProviderTest.java b/example/src/test/java/eu/webeid/example/security/AuthTokenDTOAuthenticationProviderTest.java new file mode 100644 index 00000000..f2068094 --- /dev/null +++ b/example/src/test/java/eu/webeid/example/security/AuthTokenDTOAuthenticationProviderTest.java @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: Estonian Information System Authority +// SPDX-License-Identifier: MIT + +package eu.webeid.example.security; + +import eu.webeid.example.security.dto.AuthTokenDTO; +import eu.webeid.example.testutil.ObjectMother; +import eu.webeid.security.challenge.ChallengeNonce; +import eu.webeid.security.challenge.ChallengeNonceStore; +import eu.webeid.security.exceptions.UserCertificateDisallowedPolicyException; +import eu.webeid.security.validator.AuthTokenValidator; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; + +import javax.security.auth.x500.X500Principal; +import java.time.ZonedDateTime; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@ExtendWith(OutputCaptureExtension.class) +class AuthTokenDTOAuthenticationProviderTest { + + private static final X500Principal CERTIFICATE_ISSUER = new X500Principal("CN=Example CA"); + private static final ASN1ObjectIdentifier CERTIFICATE_POLICY = new ASN1ObjectIdentifier("1.2.3"); + + @Test + void whenAllowListRejectsCertificate_thenConfigurationDetailsAreLogged(CapturedOutput output) throws Exception { + final UserCertificateDisallowedPolicyException validationException = + new UserCertificateDisallowedPolicyException(CERTIFICATE_ISSUER, Set.of(CERTIFICATE_POLICY)); + + authenticateWithValidationException(validationException); + + assertThat(output) + .contains("Certificate policy allow-list rejected an unverified certificate") + .contains("AuthTokenValidatorBuilder.withAllowedCertificatePolicies(...)") + .contains("issuerRFC2253='CN=Example CA'") + .contains("certificatePolicyOids=[1.2.3]"); + } + + @Test + void whenDenyListRejectsCertificate_thenConfigurationDetailsAreNotLogged(CapturedOutput output) throws Exception { + authenticateWithValidationException(new UserCertificateDisallowedPolicyException()); + + assertThat(output).doesNotContain("AuthTokenValidatorBuilder.withAllowedCertificatePolicies(...)"); + } + + private static void authenticateWithValidationException( + UserCertificateDisallowedPolicyException validationException) throws Exception { + final AuthTokenValidator tokenValidator = mock(AuthTokenValidator.class); + final ChallengeNonceStore challengeNonceStore = mock(ChallengeNonceStore.class); + final AuthTokenDTO credentials = ObjectMother.mockAuthToken(); + when(challengeNonceStore.getAndRemove()).thenReturn( + new ChallengeNonce("nonce", ZonedDateTime.now().plusMinutes(1)) + ); + when(tokenValidator.validate(any(), eq("nonce"))).thenThrow(validationException); + + final AuthTokenDTOAuthenticationProvider provider = + new AuthTokenDTOAuthenticationProvider(tokenValidator, challengeNonceStore); + + assertThatThrownBy(() -> provider.authenticate( + new UsernamePasswordAuthenticationToken("user", credentials) + )) + .isInstanceOf(AuthenticationServiceException.class) + .hasCause(validationException); + } +} diff --git a/src/main/java/eu/webeid/security/certificate/SubjectCertificatePolicies.java b/src/main/java/eu/webeid/security/certificate/SubjectCertificatePolicies.java index 11ef5442..50e64aff 100644 --- a/src/main/java/eu/webeid/security/certificate/SubjectCertificatePolicies.java +++ b/src/main/java/eu/webeid/security/certificate/SubjectCertificatePolicies.java @@ -5,18 +5,55 @@ import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import javax.security.auth.x500.X500Principal; +import java.util.Map; +import java.util.Set; + public final class SubjectCertificatePolicies { - private static final String ESTEID_SK_2015_MOBILE_ID_POLICY_PREFIX = "1.3.6.1.4.1.10015.1.3"; + public static final X500Principal ESTEID2018_ISSUER = new X500Principal( + "CN=ESTEID2018,2.5.4.97=#0c0e4e545245452d3130373437303133,O=SK ID Solutions AS,C=EE" + ); + public static final X500Principal ESTEID2025_ISSUER = new X500Principal( + "C=EE,O=Zetes Estonia OÜ,2.5.4.97=#0c0e4e545245452d3137303636303439,CN=ESTEID2025" + ); - public static final ASN1ObjectIdentifier ESTEID_SK_2015_MOBILE_ID_POLICY = - new ASN1ObjectIdentifier(ESTEID_SK_2015_MOBILE_ID_POLICY_PREFIX); - public static final ASN1ObjectIdentifier ESTEID_SK_2015_MOBILE_ID_POLICY_V1 = - new ASN1ObjectIdentifier(ESTEID_SK_2015_MOBILE_ID_POLICY_PREFIX + ".1"); - public static final ASN1ObjectIdentifier ESTEID_SK_2015_MOBILE_ID_POLICY_V2 = - new ASN1ObjectIdentifier(ESTEID_SK_2015_MOBILE_ID_POLICY_PREFIX + ".2"); - public static final ASN1ObjectIdentifier ESTEID_SK_2015_MOBILE_ID_POLICY_V3 = - new ASN1ObjectIdentifier(ESTEID_SK_2015_MOBILE_ID_POLICY_PREFIX + ".3"); + /** + * Production document policies for Estonian ID cards, digital ID cards, residence permit cards and diplomatic + * identity cards issued under the ESTEID2018 and eID certificate-policy generations, grouped by issuer distinguished name. + * + * @see + * ID.ee certificate policy index for Estonian identity documents + * @see + * IDEMIA-generation certificate policy + * @see + * Thales-generation certificate policy + * @see + * ESTEID2025 certificate profile + */ + public static final Map> ESTEID_PRODUCTION_DOCUMENT_POLICIES = Map.of( + ESTEID2018_ISSUER, Set.of( + // https://www.id.ee/wp-content/uploads/2026/08/cp_esteid_v4.1_17.08.2026_allkirjastatud.pdf Chapter 1.2. Document Name and Identification + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.1"), // Identity card of Estonian citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.2"), // Identity card of European Union citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.3"), // Digital identity card for Estonian residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.4"), // Digital identity card for e-residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.5"), // Residence permit card for long-term residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.6"), // Residence permit card for temporary residents and NATO SOFA + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.7"), // Residence permit card for family members of European Union citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51455.1.1.1") // Diplomatic identity card + ), + ESTEID2025_ISSUER, Set.of( + // https://www.id.ee/wp-content/uploads/2026/06/eid-cp-v-2.0_04.06.2026_allkirjastatud.pdf Chapter 1.2. Document Name and Identification + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.1"), // Identity card of Estonian citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.2"), // Identity card of European Union citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.3"), // Residence permit card for long-term residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.4"), // Residence permit card for temporary residents and the right of stay in the Republic of Estonia. + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.5"), // Residence permit card for family members of EU and UK citizens and the right of residence of UK citizens + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.6"), // Digital identity card of e-residents + new ASN1ObjectIdentifier("1.3.6.1.4.1.51455.2.1.1") // Diplomatic identity card + ) + ); private SubjectCertificatePolicies() { throw new IllegalStateException("Constants class"); diff --git a/src/main/java/eu/webeid/security/exceptions/UserCertificateDisallowedPolicyException.java b/src/main/java/eu/webeid/security/exceptions/UserCertificateDisallowedPolicyException.java index 1a41cedd..46009d08 100644 --- a/src/main/java/eu/webeid/security/exceptions/UserCertificateDisallowedPolicyException.java +++ b/src/main/java/eu/webeid/security/exceptions/UserCertificateDisallowedPolicyException.java @@ -3,11 +3,60 @@ package eu.webeid.security.exceptions; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; + +import javax.security.auth.x500.X500Principal; +import java.util.Collection; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + /** - * Thrown when any of the configured disallowed policies is present in the user certificate. + * Thrown when the user certificate does not satisfy the configured allowed or disallowed policy restrictions. */ public class UserCertificateDisallowedPolicyException extends AuthTokenException { + + private final transient X500Principal certificateIssuer; + private final transient Set certificatePolicies; + + /** + * Creates an exception without allow-list configuration details. + */ public UserCertificateDisallowedPolicyException() { super("Disallowed user certificate policy"); + certificateIssuer = null; + certificatePolicies = Set.of(); + } + + /** + * Creates an exception with the certificate details that failed allow-list validation. + * + * @param certificateIssuer certificate issuer + * @param certificatePolicies policies presented by the certificate + */ + public UserCertificateDisallowedPolicyException( + X500Principal certificateIssuer, + Collection certificatePolicies) { + super("Disallowed user certificate policy"); + this.certificateIssuer = Objects.requireNonNull(certificateIssuer); + this.certificatePolicies = Set.copyOf(Objects.requireNonNull(certificatePolicies)); + } + + /** + * Returns the certificate issuer for an allow-list validation failure. + * + * @return certificate issuer, or empty when no allow-list details are available + */ + public Optional getCertificateIssuer() { + return Optional.ofNullable(certificateIssuer); + } + + /** + * Returns the policies presented by the certificate during an allow-list validation failure. + * + * @return immutable set of certificate policies, possibly empty + */ + public Set getCertificatePolicies() { + return certificatePolicies; } } diff --git a/src/main/java/eu/webeid/security/validator/AuthTokenValidationConfiguration.java b/src/main/java/eu/webeid/security/validator/AuthTokenValidationConfiguration.java index 4dbfcb54..361faec2 100644 --- a/src/main/java/eu/webeid/security/validator/AuthTokenValidationConfiguration.java +++ b/src/main/java/eu/webeid/security/validator/AuthTokenValidationConfiguration.java @@ -3,18 +3,21 @@ package eu.webeid.security.validator; -import eu.webeid.security.certificate.SubjectCertificatePolicies; import eu.webeid.security.validator.revocationcheck.CertificateRevocationChecker; import eu.webeid.security.validator.revocationcheck.RevocationMode; import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import javax.security.auth.x500.X500Principal; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.security.cert.PKIXRevocationChecker; import java.security.cert.X509Certificate; import java.util.Collection; +import java.util.HashMap; import java.util.HashSet; +import java.util.Map; +import java.util.Objects; import java.util.Set; /** @@ -24,13 +27,10 @@ public final class AuthTokenValidationConfiguration { private URI siteOrigin; private Collection trustedCACertificates = new HashSet<>(); - // Don't allow Estonian Mobile-ID policy by default. - private Collection disallowedSubjectCertificatePolicies = new HashSet<>(Set.of( - SubjectCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY_V1, - SubjectCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY_V2, - SubjectCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY_V3, - SubjectCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY - )); + private Map> allowedSubjectCertificatePolicies = new HashMap<>(); + @Deprecated(since = "4.0.0") + private Collection disallowedSubjectCertificatePolicies = new HashSet<>(); + private boolean allowUnlistedIssuers = false; private boolean isUserCertificateRevocationCheckEnabled = true; private boolean platformOcspNonceEnabled = true; private CertificateRevocationChecker certificateRevocationChecker; @@ -43,7 +43,10 @@ public final class AuthTokenValidationConfiguration { private AuthTokenValidationConfiguration(AuthTokenValidationConfiguration other) { this.siteOrigin = other.siteOrigin; this.trustedCACertificates = Set.copyOf(other.trustedCACertificates); + this.allowedSubjectCertificatePolicies = + copyAllowedSubjectCertificatePolicies(other.allowedSubjectCertificatePolicies); this.disallowedSubjectCertificatePolicies = Set.copyOf(other.disallowedSubjectCertificatePolicies); + this.allowUnlistedIssuers = other.allowUnlistedIssuers; this.isUserCertificateRevocationCheckEnabled = other.isUserCertificateRevocationCheckEnabled; this.platformOcspNonceEnabled = other.platformOcspNonceEnabled; this.certificateRevocationChecker = other.certificateRevocationChecker; @@ -63,10 +66,40 @@ Collection getTrustedCACertificates() { return trustedCACertificates; } + Map> getAllowedSubjectCertificatePolicies() { + return allowedSubjectCertificatePolicies; + } + + void setAllowedSubjectCertificatePolicies( + X500Principal issuer, Collection allowedSubjectCertificatePolicies) { + Objects.requireNonNull(issuer, "Issuer must not be null"); + final Set policies = Set.copyOf(Objects.requireNonNull( + allowedSubjectCertificatePolicies, + "Allowed certificate policies must not be null" + )); + if (policies.isEmpty()) { + this.allowedSubjectCertificatePolicies.remove(issuer); + } else { + this.allowedSubjectCertificatePolicies.put(issuer, policies); + } + } + + /** + * @deprecated Configure allowed certificate policies instead. + */ + @Deprecated(since = "4.0.0") public Collection getDisallowedSubjectCertificatePolicies() { return disallowedSubjectCertificatePolicies; } + boolean allowUnlistedIssuers() { + return allowUnlistedIssuers; + } + + void setAllowUnlistedIssuers(boolean allowUnlistedIssuers) { + this.allowUnlistedIssuers = allowUnlistedIssuers; + } + boolean isUserCertificateRevocationCheckEnabled() { return isUserCertificateRevocationCheckEnabled; } @@ -113,6 +146,7 @@ void validate() { if (trustedCACertificates.isEmpty()) { throw new IllegalArgumentException("At least one trusted certificate authority must be provided"); } + validateCertificatePolicyConfiguration(); validateRevocationConfiguration(); } @@ -120,6 +154,24 @@ AuthTokenValidationConfiguration copy() { return new AuthTokenValidationConfiguration(this); } + private static Map> copyAllowedSubjectCertificatePolicies( + Map> policiesByIssuer) { + final Map> copy = new HashMap<>(); + policiesByIssuer.forEach((issuer, policies) -> copy.put( + Objects.requireNonNull(issuer, "Issuer must not be null"), + Set.copyOf(Objects.requireNonNull(policies, "Allowed certificate policies must not be null")) + )); + return copy; + } + + private void validateCertificatePolicyConfiguration() { + if (!allowedSubjectCertificatePolicies.isEmpty() && !disallowedSubjectCertificatePolicies.isEmpty()) { + throw new IllegalArgumentException( + "Certificate policy allow-list and deny-list cannot be enabled at the same time." + ); + } + } + /** * Validates that the given URI is an origin URL as defined in MDN, * in the form of {@code "://" [ ":" ]}. diff --git a/src/main/java/eu/webeid/security/validator/AuthTokenValidatorBuilder.java b/src/main/java/eu/webeid/security/validator/AuthTokenValidatorBuilder.java index d072979f..582851f0 100644 --- a/src/main/java/eu/webeid/security/validator/AuthTokenValidatorBuilder.java +++ b/src/main/java/eu/webeid/security/validator/AuthTokenValidatorBuilder.java @@ -3,15 +3,19 @@ package eu.webeid.security.validator; +import eu.webeid.security.certificate.SubjectCertificatePolicies; import eu.webeid.security.exceptions.JceException; import eu.webeid.security.validator.revocationcheck.CertificateRevocationChecker; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.security.auth.x500.X500Principal; import java.net.URI; import java.security.cert.PKIXRevocationChecker; import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Collection; import java.util.Collections; /** @@ -60,14 +64,60 @@ public AuthTokenValidatorBuilder withTrustedCertificateAuthorities(X509Certifica return this; } + /** + * Adds or replaces the allowed user certificate policies for the given issuer. When neither allowed nor disallowed + * policies are configured, {@link SubjectCertificatePolicies#ESTEID_PRODUCTION_DOCUMENT_POLICIES} is used by default. + * When the subject certificate's issuer matches a configured issuer, the certificate must contain at least one + * of that issuer's allowed policies. Passing no policies removes the issuer's allow-list entry. + * By default, a certificate is rejected when its issuer has no entry in an active allow-list. + * Allowed and disallowed certificate policies cannot be configured together. + * + * @param issuer exact subject certificate issuer distinguished name + * @param policies allowed user certificate policies for the issuer + * @return the builder instance for method chaining + */ + public AuthTokenValidatorBuilder withAllowedCertificatePolicies( + X500Principal issuer, ASN1ObjectIdentifier... policies) { + return withAllowedCertificatePolicies(issuer, Arrays.asList(policies)); + } + + /** + * Adds or replaces the allowed user certificate policies for the given issuer. + * + * @param issuer exact subject certificate issuer distinguished name + * @param policies allowed user certificate policies for the issuer + * @return the builder instance for method chaining + */ + public AuthTokenValidatorBuilder withAllowedCertificatePolicies( + X500Principal issuer, Collection policies) { + configuration.setAllowedSubjectCertificatePolicies(issuer, policies); + LOG.debug("Allowed subject certificate policies set to {}", configuration.getAllowedSubjectCertificatePolicies()); + return this; + } + + /** + * Allows certificates from issuers that have no entry in the active certificate policy allow-list. + * By default, certificates from issuers without an allow-list entry are rejected. + * + * @param allowUnlistedIssuers whether to allow certificates from issuers without an allow-list entry + * @return the builder instance for method chaining + */ + public AuthTokenValidatorBuilder allowUnlistedIssuers(boolean allowUnlistedIssuers) { + configuration.setAllowUnlistedIssuers(allowUnlistedIssuers); + return this; + } + /** * Adds the given policies to the list of disallowed user certificate policies. - * In order for the user certificate to be considered valid, it must not contain any policies - * present in this list. + * The certificate must not contain any policy present in this list. Configuring a disallowed policy prevents + * the default allowed policies from being applied. Allowed and disallowed certificate policies cannot be + * configured together. * * @param policies disallowed user certificate policies * @return the builder instance for method chaining + * @deprecated Use {@link #withAllowedCertificatePolicies(X500Principal, ASN1ObjectIdentifier...)} instead. */ + @Deprecated(since = "4.0.0") public AuthTokenValidatorBuilder withDisallowedCertificatePolicies(ASN1ObjectIdentifier... policies) { Collections.addAll(configuration.getDisallowedSubjectCertificatePolicies(), policies); LOG.debug("Disallowed subject certificate policies set to {}", configuration.getDisallowedSubjectCertificatePolicies()); @@ -147,8 +197,14 @@ public AuthTokenValidatorBuilder withPKIXRevocationChecker(PKIXRevocationChecker * @throws JceException when JCE configuration is invalid */ public AuthTokenValidator build() throws IllegalArgumentException, JceException { - configuration.validate(); - return new AuthTokenValidatorImpl(configuration); + final AuthTokenValidationConfiguration configurationSnapshot = configuration.copy(); + if (configurationSnapshot.getAllowedSubjectCertificatePolicies().isEmpty() + && configurationSnapshot.getDisallowedSubjectCertificatePolicies().isEmpty()) { + configurationSnapshot.getAllowedSubjectCertificatePolicies() + .putAll(SubjectCertificatePolicies.ESTEID_PRODUCTION_DOCUMENT_POLICIES); + } + configurationSnapshot.validate(); + return new AuthTokenValidatorImpl(configurationSnapshot); } } diff --git a/src/main/java/eu/webeid/security/validator/AuthTokenValidatorImpl.java b/src/main/java/eu/webeid/security/validator/AuthTokenValidatorImpl.java index 1752387f..0f82f7e0 100644 --- a/src/main/java/eu/webeid/security/validator/AuthTokenValidatorImpl.java +++ b/src/main/java/eu/webeid/security/validator/AuthTokenValidatorImpl.java @@ -54,7 +54,11 @@ final class AuthTokenValidatorImpl implements AuthTokenValidator { trustedCACertificateAnchors = CertificateValidator.buildTrustAnchorsFromCertificates(configuration.getTrustedCACertificates()); trustedCACertificateCertStore = CertificateValidator.buildCertStoreFromCertificates(configuration.getTrustedCACertificates()); - subjectCertificatePolicyValidator = new SubjectCertificatePolicyValidator(configuration.getDisallowedSubjectCertificatePolicies()); + subjectCertificatePolicyValidator = new SubjectCertificatePolicyValidator( + this.configuration.getAllowedSubjectCertificatePolicies(), + this.configuration.getDisallowedSubjectCertificatePolicies(), + this.configuration.allowUnlistedIssuers() + ); authTokenSignatureValidator = new AuthTokenSignatureValidator(configuration.getSiteOrigin()); } diff --git a/src/main/java/eu/webeid/security/validator/certvalidators/SubjectCertificatePolicyValidator.java b/src/main/java/eu/webeid/security/validator/certvalidators/SubjectCertificatePolicyValidator.java index f05109b2..ae21e9f3 100644 --- a/src/main/java/eu/webeid/security/validator/certvalidators/SubjectCertificatePolicyValidator.java +++ b/src/main/java/eu/webeid/security/validator/certvalidators/SubjectCertificatePolicyValidator.java @@ -4,44 +4,105 @@ package eu.webeid.security.validator.certvalidators; import eu.webeid.security.exceptions.AuthTokenException; +import eu.webeid.security.exceptions.UserCertificateDisallowedPolicyException; +import eu.webeid.security.exceptions.UserCertificateParseException; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.x509.CertificatePolicies; import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.PolicyInformation; import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; -import eu.webeid.security.exceptions.UserCertificateDisallowedPolicyException; -import eu.webeid.security.exceptions.UserCertificateParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.security.auth.x500.X500Principal; import java.io.IOException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; public final class SubjectCertificatePolicyValidator { private static final Logger LOG = LoggerFactory.getLogger(SubjectCertificatePolicyValidator.class); + private final Map> allowedSubjectCertificatePolicies; private final Collection disallowedSubjectCertificatePolicies; + private final boolean allowUnlistedIssuers; + /** + * @deprecated Configure both allowed and fallback disallowed policies with + * {@link #SubjectCertificatePolicyValidator(Map, Collection)}. + */ + @Deprecated(since = "4.0.0") public SubjectCertificatePolicyValidator(Collection disallowedSubjectCertificatePolicies) { - this.disallowedSubjectCertificatePolicies = disallowedSubjectCertificatePolicies; + this(Map.of(), disallowedSubjectCertificatePolicies, false); + } + + /** + * Creates a validator with strict allow-list validation enabled. + * + * @param allowedSubjectCertificatePolicies allowed policies grouped by exact certificate issuer + * @param disallowedSubjectCertificatePolicies fallback disallowed policies + * @throws IllegalArgumentException if a listed issuer has no allowed policies + */ + public SubjectCertificatePolicyValidator( + Map> allowedSubjectCertificatePolicies, + Collection disallowedSubjectCertificatePolicies) { + this(allowedSubjectCertificatePolicies, disallowedSubjectCertificatePolicies, false); + } + + /** + * @param allowedSubjectCertificatePolicies allowed policies grouped by exact certificate issuer + * @param disallowedSubjectCertificatePolicies fallback disallowed policies + * @param allowUnlistedIssuers whether an active allow-list accepts unlisted issuers + * @throws IllegalArgumentException if a listed issuer has no allowed policies + */ + public SubjectCertificatePolicyValidator( + Map> allowedSubjectCertificatePolicies, + Collection disallowedSubjectCertificatePolicies, + boolean allowUnlistedIssuers) { + this.allowedSubjectCertificatePolicies = copyAllowedSubjectCertificatePolicies(allowedSubjectCertificatePolicies); + this.disallowedSubjectCertificatePolicies = Set.copyOf(disallowedSubjectCertificatePolicies); + this.allowUnlistedIssuers = allowUnlistedIssuers; } /** - * Rejects any configured disallowed policy present in the certificate policies extension. - * A certificate without the certificate policies extension does not contain disallowed policies and passes validation. + * Requires a configured allowed policy when the certificate issuer has an allow-list entry. In strict mode, + * a certificate is also rejected when an allow-list exists but its issuer has no entry. + * Otherwise, rejects any configured disallowed policy present in the certificate policies extension. + * A certificate without the certificate policies extension passes only when its issuer is not subject to + * allow-list validation. * * @param subjectCertificate user certificate to be validated - * @throws UserCertificateDisallowedPolicyException when a disallowed policy is present. + * @throws UserCertificateDisallowedPolicyException when no allowed policy is present or a disallowed policy is present. * @throws UserCertificateParseException when the certificate policies extension is invalid. */ public void validateCertificatePolicies(X509Certificate subjectCertificate) throws AuthTokenException { + final X500Principal issuer = subjectCertificate.getIssuerX500Principal(); + final Optional> issuerAllowedPolicies = + Optional.ofNullable(allowedSubjectCertificatePolicies.get(issuer)); + if (!allowUnlistedIssuers + && !allowedSubjectCertificatePolicies.isEmpty() + && issuerAllowedPolicies.isEmpty()) { + LOG.debug("User certificate issuer '{}' does not have an allow-list entry.", issuer); + throw new UserCertificateDisallowedPolicyException(issuer, Set.of()); + } final byte[] extensionValue = subjectCertificate.getExtensionValue(Extension.certificatePolicies.getId()); + if (extensionValue == null) { + if (issuerAllowedPolicies.isPresent()) { + LOG.debug("User certificate does not contain the certificate policies extension, hence it does not contain an allowed policy."); + throw new UserCertificateDisallowedPolicyException(issuer, Set.of()); + } LOG.debug("User certificate does not contain the certificate policies extension, hence it does not contain disallowed policies."); return; } + try { final CertificatePolicies policies = CertificatePolicies.getInstance( JcaX509ExtensionUtils.parseExtensionValue(extensionValue) @@ -49,9 +110,24 @@ public void validateCertificatePolicies(X509Certificate subjectCertificate) thro if (policies == null) { throw new IllegalArgumentException("Certificate policies extension is empty"); } + if (issuerAllowedPolicies.isPresent()) { + final Set allowedPolicies = issuerAllowedPolicies.get(); + if (Arrays.stream(policies.getPolicyInformation()) + .noneMatch(policyInformation -> + allowedPolicies.contains(policyInformation.getPolicyIdentifier()))) { + throw new UserCertificateDisallowedPolicyException( + issuer, + Arrays.stream(policies.getPolicyInformation()) + .map(PolicyInformation::getPolicyIdentifier) + .collect(Collectors.toUnmodifiableSet()) + ); + } + LOG.debug("User certificate contains a policy allowed for issuer '{}'.", issuer); + return; + } if (Arrays.stream(policies.getPolicyInformation()) .anyMatch(policyInformation -> - disallowedSubjectCertificatePolicies.contains(policyInformation.getPolicyIdentifier()))) { + disallowedSubjectCertificatePolicies.contains(policyInformation.getPolicyIdentifier()))) { throw new UserCertificateDisallowedPolicyException(); } } catch (IOException | IllegalArgumentException e) { @@ -59,4 +135,22 @@ public void validateCertificatePolicies(X509Certificate subjectCertificate) thro } LOG.debug("User certificate does not contain disallowed policies."); } + + private static Map> copyAllowedSubjectCertificatePolicies( + Map> policiesByIssuer) { + final Map> copy = new HashMap<>(); + policiesByIssuer.forEach((issuer, policies) -> { + Objects.requireNonNull(issuer, "Issuer must not be null"); + final Set allowedPolicies = Set.copyOf( + Objects.requireNonNull(policies, "Allowed certificate policies must not be null") + ); + if (allowedPolicies.isEmpty()) { + throw new IllegalArgumentException( + "At least one allowed certificate policy is required for issuer " + issuer.getName() + ); + } + copy.put(issuer, allowedPolicies); + }); + return Map.copyOf(copy); + } } diff --git a/src/test/java/eu/webeid/security/certificate/SubjectCertificatePoliciesTest.java b/src/test/java/eu/webeid/security/certificate/SubjectCertificatePoliciesTest.java new file mode 100644 index 00000000..4c9394f7 --- /dev/null +++ b/src/test/java/eu/webeid/security/certificate/SubjectCertificatePoliciesTest.java @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Estonian Information System Authority +// SPDX-License-Identifier: MIT + +package eu.webeid.security.certificate; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.junit.jupiter.api.Test; + +import static eu.webeid.security.certificate.SubjectCertificatePolicies.ESTEID2018_ISSUER; +import static eu.webeid.security.certificate.SubjectCertificatePolicies.ESTEID2025_ISSUER; +import static org.assertj.core.api.Assertions.assertThat; + +class SubjectCertificatePoliciesTest { + + @Test + void esteidProductionDocumentPoliciesContainExpectedPolicies() { + assertThat(SubjectCertificatePolicies.ESTEID_PRODUCTION_DOCUMENT_POLICIES) + .containsOnlyKeys(ESTEID2018_ISSUER, ESTEID2025_ISSUER); + assertThat(SubjectCertificatePolicies.ESTEID_PRODUCTION_DOCUMENT_POLICIES.get(ESTEID2018_ISSUER)) + .containsExactlyInAnyOrder( + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.1"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.2"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.3"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.4"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.5"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.6"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.7"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51455.1.1.1") + ); + assertThat(SubjectCertificatePolicies.ESTEID_PRODUCTION_DOCUMENT_POLICIES.get(ESTEID2025_ISSUER)) + .containsExactlyInAnyOrder( + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.1"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.2"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.3"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.4"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.5"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.6"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51455.2.1.1") + ); + } +} diff --git a/src/test/java/eu/webeid/security/testutil/AuthTokenValidators.java b/src/test/java/eu/webeid/security/testutil/AuthTokenValidators.java index fd7348e2..d37800af 100644 --- a/src/test/java/eu/webeid/security/testutil/AuthTokenValidators.java +++ b/src/test/java/eu/webeid/security/testutil/AuthTokenValidators.java @@ -14,10 +14,16 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; +import static eu.webeid.security.testutil.LegacyMobileIdCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY; +import static eu.webeid.security.testutil.LegacyMobileIdCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY_V1; +import static eu.webeid.security.testutil.LegacyMobileIdCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY_V2; +import static eu.webeid.security.testutil.LegacyMobileIdCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY_V3; + public final class AuthTokenValidators { private static final String TOKEN_ORIGIN_URL = "https://ria.ee"; - private static final ASN1ObjectIdentifier EST_IDEMIA_POLICY = new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.1"); + private static final ASN1ObjectIdentifier EST_IDEMIA_TEST_POLICY = + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.1"); public static AuthTokenValidator getAuthTokenValidator() throws CertificateException, JceException, IOException { return getAuthTokenValidator(TOKEN_ORIGIN_URL); @@ -49,8 +55,10 @@ public static AuthTokenValidator getAuthTokenValidatorWithJuly2024ExpiredUnrelat } public static AuthTokenValidator getAuthTokenValidatorWithDisallowedESTEIDPolicy() throws CertificateException, JceException, IOException { - return getAuthTokenValidatorBuilder(TOKEN_ORIGIN_URL, getCACertificates()) - .withDisallowedCertificatePolicies(EST_IDEMIA_POLICY) + return new AuthTokenValidatorBuilder() + .withSiteOrigin(URI.create(TOKEN_ORIGIN_URL)) + .withTrustedCertificateAuthorities(getCACertificates()) + .withDisallowedCertificatePolicies(EST_IDEMIA_TEST_POLICY) .withoutUserCertificateRevocationCheck() .build(); } @@ -73,7 +81,23 @@ public static AuthTokenValidatorBuilder getDefaultAuthTokenValidatorBuilder() th return getAuthTokenValidatorBuilder(TOKEN_ORIGIN_URL, getCACertificates()); } + public static AuthTokenValidatorBuilder getAuthTokenValidatorBuilderWithoutConfiguredCertificatePolicies() + throws CertificateException, IOException { + return getBaseAuthTokenValidatorBuilder(TOKEN_ORIGIN_URL, getCACertificates()); + } + private static AuthTokenValidatorBuilder getAuthTokenValidatorBuilder(String uri, X509Certificate[] certificates) { + return getBaseAuthTokenValidatorBuilder(uri, certificates) + .withDisallowedCertificatePolicies( + ESTEID_SK_2015_MOBILE_ID_POLICY_V1, + ESTEID_SK_2015_MOBILE_ID_POLICY_V2, + ESTEID_SK_2015_MOBILE_ID_POLICY_V3, + ESTEID_SK_2015_MOBILE_ID_POLICY + ); + } + + private static AuthTokenValidatorBuilder getBaseAuthTokenValidatorBuilder( + String uri, X509Certificate[] certificates) { return new AuthTokenValidatorBuilder() .withSiteOrigin(URI.create(uri)) .withTrustedCertificateAuthorities(certificates); diff --git a/src/test/java/eu/webeid/security/testutil/LegacyMobileIdCertificatePolicies.java b/src/test/java/eu/webeid/security/testutil/LegacyMobileIdCertificatePolicies.java new file mode 100644 index 00000000..5fa5a47d --- /dev/null +++ b/src/test/java/eu/webeid/security/testutil/LegacyMobileIdCertificatePolicies.java @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: Estonian Information System Authority +// SPDX-License-Identifier: MIT + +package eu.webeid.security.testutil; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; + +public final class LegacyMobileIdCertificatePolicies { + + private static final String POLICY_PREFIX = "1.3.6.1.4.1.10015.1.3"; + + public static final ASN1ObjectIdentifier ESTEID_SK_2015_MOBILE_ID_POLICY = + new ASN1ObjectIdentifier(POLICY_PREFIX); + public static final ASN1ObjectIdentifier ESTEID_SK_2015_MOBILE_ID_POLICY_V1 = + new ASN1ObjectIdentifier(POLICY_PREFIX + ".1"); + public static final ASN1ObjectIdentifier ESTEID_SK_2015_MOBILE_ID_POLICY_V2 = + new ASN1ObjectIdentifier(POLICY_PREFIX + ".2"); + public static final ASN1ObjectIdentifier ESTEID_SK_2015_MOBILE_ID_POLICY_V3 = + new ASN1ObjectIdentifier(POLICY_PREFIX + ".3"); + + private LegacyMobileIdCertificatePolicies() { + throw new IllegalStateException("Constants class"); + } +} diff --git a/src/test/java/eu/webeid/security/validator/AuthTokenCertificateTest.java b/src/test/java/eu/webeid/security/validator/AuthTokenCertificateTest.java index 9f6c6f2d..059d1391 100644 --- a/src/test/java/eu/webeid/security/validator/AuthTokenCertificateTest.java +++ b/src/test/java/eu/webeid/security/validator/AuthTokenCertificateTest.java @@ -18,23 +18,38 @@ import eu.webeid.security.testutil.AbstractTestWithValidator; import eu.webeid.security.testutil.AuthTokenValidators; import eu.webeid.security.util.DateAndTime; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; +import javax.security.auth.x500.X500Principal; import java.security.cert.CertificateException; import java.util.Base64; import static eu.webeid.security.testutil.Certificates.getCertificateWithoutCertificatePolicies; import static eu.webeid.security.testutil.DateMocker.mockDate; +import static eu.webeid.security.testutil.LegacyMobileIdCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY; +import static eu.webeid.security.testutil.LegacyMobileIdCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY_V1; +import static eu.webeid.security.testutil.LegacyMobileIdCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY_V2; +import static eu.webeid.security.testutil.LegacyMobileIdCertificatePolicies.ESTEID_SK_2015_MOBILE_ID_POLICY_V3; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mockStatic; class AuthTokenCertificateTest extends AbstractTestWithValidator { + private static final X500Principal ESTEID2018_TEST_ISSUER = new X500Principal( + "CN=TEST of ESTEID2018,2.5.4.97=#0c0e4e545245452d3130373437303133,O=SK ID Solutions AS,C=EE" + ); + private static final ASN1ObjectIdentifier ESTEID2018_TEST_POLICY = + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.1"); + + private static final ASN1ObjectIdentifier UNRELATED_POLICY = new ASN1ObjectIdentifier("1.2.3"); + private static final X500Principal UNRELATED_ISSUER = new X500Principal("CN=Another CA"); + private static final String AUTH_TOKEN = "{\"algorithm\":\"ES384\"," + "\"unverifiedCertificate\":\"X5C\"," + "\"appVersion\":\"https://web-eid.eu/web-eid-app/releases/2.0.0+0\"," + @@ -176,6 +191,55 @@ void whenCertificatePolicyIsDisallowed_thenValidationFails() throws Exception { .isInstanceOf(UserCertificateDisallowedPolicyException.class); } + @Test + void whenCertificatePolicyIsAllowed_thenValidationSucceeds() throws Exception { + final AuthTokenValidator validatorWithAllowedESTEIDPolicy = AuthTokenValidators + .getAuthTokenValidatorBuilderWithoutConfiguredCertificatePolicies() + .withAllowedCertificatePolicies(ESTEID2018_TEST_ISSUER, ESTEID2018_TEST_POLICY) + .withoutUserCertificateRevocationCheck() + .build(); + + assertThatCode(() -> validatorWithAllowedESTEIDPolicy.validate(validAuthToken, VALID_CHALLENGE_NONCE)) + .doesNotThrowAnyException(); + } + + @Test + void whenCertificatePolicyIsNotAllowed_thenValidationFails() throws Exception { + final AuthTokenValidator validatorWithUnrelatedAllowedPolicy = AuthTokenValidators + .getAuthTokenValidatorBuilderWithoutConfiguredCertificatePolicies() + .withAllowedCertificatePolicies(ESTEID2018_TEST_ISSUER, UNRELATED_POLICY) + .withoutUserCertificateRevocationCheck() + .build(); + + assertThatThrownBy(() -> validatorWithUnrelatedAllowedPolicy.validate(validAuthToken, VALID_CHALLENGE_NONCE)) + .isInstanceOf(UserCertificateDisallowedPolicyException.class); + } + + @Test + void whenCertificateIssuerIsNotAllowedAndValidationIsStrict_thenValidationFails() throws Exception { + final AuthTokenValidator validatorWithUnrelatedAllowedIssuer = AuthTokenValidators + .getAuthTokenValidatorBuilderWithoutConfiguredCertificatePolicies() + .withAllowedCertificatePolicies(UNRELATED_ISSUER, UNRELATED_POLICY) + .withoutUserCertificateRevocationCheck() + .build(); + + assertThatThrownBy(() -> validatorWithUnrelatedAllowedIssuer.validate(validAuthToken, VALID_CHALLENGE_NONCE)) + .isInstanceOf(UserCertificateDisallowedPolicyException.class); + } + + @Test + void whenCertificateIssuerIsNotAllowedAndValidationIsLenient_thenValidationSucceeds() throws Exception { + final AuthTokenValidator validatorWithUnrelatedAllowedIssuer = AuthTokenValidators + .getAuthTokenValidatorBuilderWithoutConfiguredCertificatePolicies() + .withAllowedCertificatePolicies(UNRELATED_ISSUER, UNRELATED_POLICY) + .allowUnlistedIssuers(true) + .withoutUserCertificateRevocationCheck() + .build(); + + assertThatCode(() -> validatorWithUnrelatedAllowedIssuer.validate(validAuthToken, VALID_CHALLENGE_NONCE)) + .doesNotThrowAnyException(); + } + @Test void whenUsingOldMobileIdCertificate_thenValidationFails() throws AuthTokenException { mockDate("2021-03-01", mockedClock); @@ -185,6 +249,25 @@ void whenUsingOldMobileIdCertificate_thenValidationFails() throws AuthTokenExcep .isInstanceOf(UserCertificateDisallowedPolicyException.class); } + @Test + void whenUsingOldMobileIdCertificateWithLegacyDenyList_thenPolicyValidationFails() throws Exception { + mockDate("2021-03-01", mockedClock); + final AuthTokenValidator validatorWithLegacyDenyList = AuthTokenValidators + .getAuthTokenValidatorBuilderWithoutConfiguredCertificatePolicies() + .withDisallowedCertificatePolicies( + ESTEID_SK_2015_MOBILE_ID_POLICY_V1, + ESTEID_SK_2015_MOBILE_ID_POLICY_V2, + ESTEID_SK_2015_MOBILE_ID_POLICY_V3, + ESTEID_SK_2015_MOBILE_ID_POLICY + ) + .withoutUserCertificateRevocationCheck() + .build(); + final WebEidAuthToken token = replaceTokenField(AUTH_TOKEN, "X5C", OLD_MOBILE_ID_CERT); + + assertThatThrownBy(() -> validatorWithLegacyDenyList.validate(token, VALID_CHALLENGE_NONCE)) + .isInstanceOf(UserCertificateDisallowedPolicyException.class); + } + @Test void whenUsingNewMobileIdCertificate_thenValidationFails() throws AuthTokenException { final WebEidAuthToken token = replaceTokenField(AUTH_TOKEN, "X5C", NEW_MOBILE_ID_CERT); @@ -193,6 +276,24 @@ void whenUsingNewMobileIdCertificate_thenValidationFails() throws AuthTokenExcep .isInstanceOf(UserCertificateDisallowedPolicyException.class); } + @Test + void whenUsingNewMobileIdCertificateWithLegacyDenyList_thenPolicyValidationFails() throws Exception { + final AuthTokenValidator validatorWithLegacyDenyList = AuthTokenValidators + .getAuthTokenValidatorBuilderWithoutConfiguredCertificatePolicies() + .withDisallowedCertificatePolicies( + ESTEID_SK_2015_MOBILE_ID_POLICY_V1, + ESTEID_SK_2015_MOBILE_ID_POLICY_V2, + ESTEID_SK_2015_MOBILE_ID_POLICY_V3, + ESTEID_SK_2015_MOBILE_ID_POLICY + ) + .withoutUserCertificateRevocationCheck() + .build(); + final WebEidAuthToken token = replaceTokenField(AUTH_TOKEN, "X5C", NEW_MOBILE_ID_CERT); + + assertThatThrownBy(() -> validatorWithLegacyDenyList.validate(token, VALID_CHALLENGE_NONCE)) + .isInstanceOf(UserCertificateDisallowedPolicyException.class); + } + @Test void whenCertificateIsExpiredRsa_thenValidationFails() throws Exception { mockDate("2099-01-01", mockedClock); diff --git a/src/test/java/eu/webeid/security/validator/AuthTokenValidationConfigurationTest.java b/src/test/java/eu/webeid/security/validator/AuthTokenValidationConfigurationTest.java index f70eae22..31874329 100644 --- a/src/test/java/eu/webeid/security/validator/AuthTokenValidationConfigurationTest.java +++ b/src/test/java/eu/webeid/security/validator/AuthTokenValidationConfigurationTest.java @@ -22,20 +22,89 @@ package eu.webeid.security.validator; +import eu.webeid.security.certificate.SubjectCertificatePolicies; import eu.webeid.security.testutil.Certificates; import eu.webeid.security.validator.revocationcheck.CertificateRevocationChecker; import eu.webeid.security.validator.revocationcheck.RevocationMode; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.junit.jupiter.api.Test; +import javax.security.auth.x500.X500Principal; import java.net.URI; import java.security.cert.PKIXRevocationChecker; +import java.util.ArrayList; import java.util.List; +import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; import static org.mockito.Mockito.mock; class AuthTokenValidationConfigurationTest { + private static final ASN1ObjectIdentifier ALLOWED_POLICY = new ASN1ObjectIdentifier("1.2.3"); + private static final X500Principal ISSUER = new X500Principal("CN=Example CA"); + + @Test + void allowedPoliciesAreEmptyByDefault() { + final AuthTokenValidationConfiguration configuration = new AuthTokenValidationConfiguration(); + + assertThat(configuration.getAllowedSubjectCertificatePolicies()) + .isEmpty(); + } + + @Test + void copyRetainsAllowedPoliciesIndependently() { + final AuthTokenValidationConfiguration configuration = new AuthTokenValidationConfiguration(); + configuration.setAllowedSubjectCertificatePolicies(ISSUER, List.of(ALLOWED_POLICY)); + + final AuthTokenValidationConfiguration copy = configuration.copy(); + configuration.getAllowedSubjectCertificatePolicies().clear(); + + assertThat(copy.getAllowedSubjectCertificatePolicies()) + .containsEntry(ISSUER, Set.of(ALLOWED_POLICY)); + } + + @Test + void setAllowedPoliciesCopiesInputCollection() { + final List policies = new ArrayList<>(List.of(ALLOWED_POLICY)); + final AuthTokenValidationConfiguration configuration = new AuthTokenValidationConfiguration(); + + configuration.setAllowedSubjectCertificatePolicies(ISSUER, policies); + policies.clear(); + + assertThat(configuration.getAllowedSubjectCertificatePolicies()) + .containsOnly(entry(ISSUER, Set.of(ALLOWED_POLICY))); + } + + @Test + void subsequentAllowedPolicyConfigurationAddsAnotherIssuer() { + final X500Principal anotherIssuer = new X500Principal("CN=Another CA"); + final ASN1ObjectIdentifier anotherPolicy = new ASN1ObjectIdentifier("1.2.4"); + final AuthTokenValidationConfiguration configuration = new AuthTokenValidationConfiguration(); + + configuration.setAllowedSubjectCertificatePolicies(ISSUER, List.of(ALLOWED_POLICY)); + configuration.setAllowedSubjectCertificatePolicies(anotherIssuer, List.of(anotherPolicy)); + + assertThat(configuration.getAllowedSubjectCertificatePolicies()) + .containsOnly( + entry(ISSUER, Set.of(ALLOWED_POLICY)), + entry(anotherIssuer, Set.of(anotherPolicy)) + ); + } + + @Test + void settingNoAllowedPoliciesRemovesIssuerEntry() { + final X500Principal defaultIssuer = SubjectCertificatePolicies.ESTEID_PRODUCTION_DOCUMENT_POLICIES + .keySet().iterator().next(); + final AuthTokenValidationConfiguration configuration = new AuthTokenValidationConfiguration(); + + configuration.setAllowedSubjectCertificatePolicies(defaultIssuer, List.of()); + + assertThat(configuration.getAllowedSubjectCertificatePolicies()) + .doesNotContainKey(defaultIssuer); + } + @Test void whenNoCustomCheckerProvided_thenRevocationModeIsPlatformOcsp() throws Exception { final AuthTokenValidationConfiguration configuration = getValidConfiguration(); diff --git a/src/test/java/eu/webeid/security/validator/AuthTokenValidatorBuilderTest.java b/src/test/java/eu/webeid/security/validator/AuthTokenValidatorBuilderTest.java index 5aa9e0dc..b14e0c20 100644 --- a/src/test/java/eu/webeid/security/validator/AuthTokenValidatorBuilderTest.java +++ b/src/test/java/eu/webeid/security/validator/AuthTokenValidatorBuilderTest.java @@ -4,25 +4,36 @@ package eu.webeid.security.validator; import eu.webeid.security.certificate.CertificateValidator; +import eu.webeid.security.certificate.SubjectCertificatePolicies; import eu.webeid.security.testutil.AuthTokenValidators; import eu.webeid.security.validator.revocationcheck.CertificateRevocationChecker; import eu.webeid.security.validator.revocationcheck.RevocationMode; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; +import javax.security.auth.x500.X500Principal; import java.net.URI; import java.security.cert.PKIXRevocationChecker; +import java.security.cert.X509Certificate; import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; import static eu.webeid.security.testutil.AbstractTestWithValidator.VALID_AUTH_TOKEN; import static eu.webeid.security.testutil.AbstractTestWithValidator.VALID_CHALLENGE_NONCE; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; @@ -137,6 +148,151 @@ void whenPlatformOcspNonceSettingChanges_thenBuiltValidatorsRetainTheirSetting() } } + @Test + void whenAllowedPoliciesAreEmpty_thenBuildUsesEsteidDefaults() throws Exception { + final AuthTokenValidationConfiguration builtConfiguration = captureBuiltConfiguration(validBuilder()); + + assertThat(builtConfiguration.getAllowedSubjectCertificatePolicies()) + .isEqualTo(SubjectCertificatePolicies.ESTEID_PRODUCTION_DOCUMENT_POLICIES); + } + + @Test + void whenAllowedPoliciesAreConfigured_thenBuildUsesOnlyConfiguredPolicies() throws Exception { + final X500Principal issuer = new X500Principal("CN=Example CA"); + final ASN1ObjectIdentifier policy = new ASN1ObjectIdentifier("1.2.3"); + + final AuthTokenValidationConfiguration builtConfiguration = captureBuiltConfiguration( + validBuilder().withAllowedCertificatePolicies(issuer, policy) + ); + + assertThat(builtConfiguration.getAllowedSubjectCertificatePolicies()) + .containsOnly(entry(issuer, Set.of(policy))); + } + + @Test + void whenAllowingUnlistedIssuersIsConfigured_thenBuildRetainsSetting() throws Exception { + final AuthTokenValidationConfiguration defaultConfiguration = captureBuiltConfiguration(validBuilder()); + final AuthTokenValidationConfiguration allowedConfiguration = captureBuiltConfiguration( + validBuilder().allowUnlistedIssuers(true) + ); + final AuthTokenValidationConfiguration rejectedConfiguration = captureBuiltConfiguration( + validBuilder().allowUnlistedIssuers(false) + ); + + assertThat(defaultConfiguration.allowUnlistedIssuers()).isFalse(); + assertThat(allowedConfiguration.allowUnlistedIssuers()).isTrue(); + assertThat(rejectedConfiguration.allowUnlistedIssuers()).isFalse(); + } + + @Test + void whenOnlyEstonianAndEuCitizenIdCardsAreSupported_thenOnlyTheirPoliciesAreAllowed() throws Exception { + final AuthTokenValidationConfiguration builtConfiguration = captureBuiltConfiguration( + validBuilder() + .withAllowedCertificatePolicies( + SubjectCertificatePolicies.ESTEID2018_ISSUER, + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.1"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.2") + ) + .withAllowedCertificatePolicies( + SubjectCertificatePolicies.ESTEID2025_ISSUER, + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.1"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.2") + ) + ); + + assertThat(builtConfiguration.getAllowedSubjectCertificatePolicies()) + .containsOnly( + entry( + SubjectCertificatePolicies.ESTEID2018_ISSUER, + Set.of( + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.1"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.1.2") + ) + ), + entry( + SubjectCertificatePolicies.ESTEID2025_ISSUER, + Set.of( + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.1"), + new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.2.1.2") + ) + ) + ); + } + + @Test + @SuppressWarnings("deprecation") + void whenNoDisallowedPoliciesAreProvidedBeforeAllowedPolicies_thenBuildUsesAllowedPolicies() throws Exception { + final X500Principal issuer = new X500Principal("CN=Example CA"); + final ASN1ObjectIdentifier policy = new ASN1ObjectIdentifier("1.2.3"); + + final AuthTokenValidationConfiguration builtConfiguration = captureBuiltConfiguration( + validBuilder() + .withDisallowedCertificatePolicies() + .withAllowedCertificatePolicies(issuer, policy) + ); + + assertThat(builtConfiguration.getAllowedSubjectCertificatePolicies()) + .containsOnly(entry(issuer, Set.of(policy))); + assertThat(builtConfiguration.getDisallowedSubjectCertificatePolicies()).isEmpty(); + } + + @Test + @SuppressWarnings("deprecation") + void whenDisallowedPoliciesAreConfiguredInMultipleCalls_thenPoliciesAreAdded() throws Exception { + final ASN1ObjectIdentifier firstPolicy = new ASN1ObjectIdentifier("1.2.3"); + final ASN1ObjectIdentifier secondPolicy = new ASN1ObjectIdentifier("1.2.4"); + + final AuthTokenValidationConfiguration builtConfiguration = captureBuiltConfiguration( + validBuilder() + .withDisallowedCertificatePolicies(firstPolicy) + .withDisallowedCertificatePolicies(secondPolicy) + ); + + assertThat(builtConfiguration.getDisallowedSubjectCertificatePolicies()) + .containsExactlyInAnyOrder(firstPolicy, secondPolicy); + } + + @Test + @SuppressWarnings("deprecation") + void whenAllowedAndDisallowedPoliciesAreConfigured_thenBuildFailsRegardlessOfCallOrder() { + final X500Principal issuer = new X500Principal("CN=Example CA"); + final ASN1ObjectIdentifier allowedPolicy = new ASN1ObjectIdentifier("1.2.3"); + final ASN1ObjectIdentifier disallowedPolicy = new ASN1ObjectIdentifier("1.2.4"); + + assertThatThrownBy(() -> validBuilder() + .withAllowedCertificatePolicies(issuer, allowedPolicy) + .withDisallowedCertificatePolicies(disallowedPolicy) + .build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Certificate policy allow-list and deny-list cannot be enabled at the same time."); + + assertThatThrownBy(() -> validBuilder() + .withDisallowedCertificatePolicies(disallowedPolicy) + .withAllowedCertificatePolicies(issuer, allowedPolicy) + .build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Certificate policy allow-list and deny-list cannot be enabled at the same time."); + } + + private static AuthTokenValidationConfiguration captureBuiltConfiguration( + AuthTokenValidatorBuilder builder) throws Exception { + final AtomicReference capturedConfiguration = new AtomicReference<>(); + try (MockedConstruction ignored = mockConstruction( + AuthTokenValidatorImpl.class, + (mock, context) -> capturedConfiguration.set( + (AuthTokenValidationConfiguration) context.arguments().get(0) + ))) { + builder.build(); + } + return capturedConfiguration.get(); + } + + private static AuthTokenValidatorBuilder validBuilder() { + return new AuthTokenValidatorBuilder() + .withSiteOrigin(URI.create("https://ria.ee")) + .withTrustedCertificateAuthorities(mock(X509Certificate.class)); + } + private static CertificateRevocationChecker getNoopChecker() { return (subjectCertificate, issuerCertificate) -> List.of(); } diff --git a/src/test/java/eu/webeid/security/validator/certvalidators/SubjectCertificatePolicyValidatorTest.java b/src/test/java/eu/webeid/security/validator/certvalidators/SubjectCertificatePolicyValidatorTest.java index 4dd7fe40..eb47c8e2 100644 --- a/src/test/java/eu/webeid/security/validator/certvalidators/SubjectCertificatePolicyValidatorTest.java +++ b/src/test/java/eu/webeid/security/validator/certvalidators/SubjectCertificatePolicyValidatorTest.java @@ -10,14 +10,19 @@ import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.x509.Extension; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.security.cert.X509Certificate; import java.util.List; +import java.util.Map; import java.util.Set; +import javax.security.auth.x500.X500Principal; + import static eu.webeid.security.testutil.Certificates.getCertificateWithoutCertificatePolicies; import static eu.webeid.security.testutil.Certificates.getJaakKristjanEsteid2018Cert; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -28,15 +33,27 @@ class SubjectCertificatePolicyValidatorTest { private static final ASN1ObjectIdentifier ESTEID2018_POLICY = new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.1"); private static final ASN1ObjectIdentifier UNRELATED_POLICY = new ASN1ObjectIdentifier("1.3.6.1.4.1.51361.1.2.2"); + private static final X500Principal ESTEID2018_TEST_ISSUER = new X500Principal( + "CN=TEST of ESTEID2018,2.5.4.97=#0c0e4e545245452d3130373437303133,O=SK ID Solutions AS,C=EE" + ); private final X509Certificate certificate = mock(X509Certificate.class); private final SubjectCertificatePolicyValidator validator = new SubjectCertificatePolicyValidator(Set.of()); + @BeforeEach + void setUpCertificateIssuer() { + when(certificate.getIssuerX500Principal()).thenReturn(new X500Principal("CN=Unconfigured CA")); + } + @Test void whenCertificateContainsDisallowedPolicy_thenValidationFails() throws Exception { final SubjectCertificatePolicyValidator validator = new SubjectCertificatePolicyValidator(List.of(ESTEID2018_POLICY)); assertThatExceptionOfType(UserCertificateDisallowedPolicyException.class) - .isThrownBy(() -> validator.validateCertificatePolicies(getJaakKristjanEsteid2018Cert())); + .isThrownBy(() -> validator.validateCertificatePolicies(getJaakKristjanEsteid2018Cert())) + .satisfies(exception -> { + assertThat(exception.getCertificateIssuer()).isEmpty(); + assertThat(exception.getCertificatePolicies()).isEmpty(); + }); } @Test @@ -46,6 +63,80 @@ void whenCertificateDoesNotContainDisallowedPolicies_thenValidationSucceeds() th .doesNotThrowAnyException(); } + @Test + void whenCertificateContainsAllowedPolicy_thenValidationSucceeds() throws Exception { + final SubjectCertificatePolicyValidator validator = + new SubjectCertificatePolicyValidator(allowedPolicies(ESTEID2018_POLICY), Set.of()); + assertThatCode(() -> validator.validateCertificatePolicies(getJaakKristjanEsteid2018Cert())) + .doesNotThrowAnyException(); + } + + @Test + void whenCertificateDoesNotContainAllowedPolicy_thenValidationFails() throws Exception { + final SubjectCertificatePolicyValidator validator = + new SubjectCertificatePolicyValidator(allowedPolicies(UNRELATED_POLICY), Set.of()); + assertThatExceptionOfType(UserCertificateDisallowedPolicyException.class) + .isThrownBy(() -> validator.validateCertificatePolicies(getJaakKristjanEsteid2018Cert())) + .satisfies(exception -> { + assertThat(exception.getCertificateIssuer()).contains(ESTEID2018_TEST_ISSUER); + assertThat(exception.getCertificatePolicies()).contains(ESTEID2018_POLICY); + }); + } + + @Test + void whenPolicyIsBothAllowedAndDisallowed_thenAllowListTakesPrecedence() throws Exception { + final SubjectCertificatePolicyValidator validator = + new SubjectCertificatePolicyValidator( + allowedPolicies(ESTEID2018_POLICY), + List.of(ESTEID2018_POLICY) + ); + assertThatCode(() -> validator.validateCertificatePolicies(getJaakKristjanEsteid2018Cert())) + .doesNotThrowAnyException(); + } + + @Test + void whenIssuerHasNoAllowListEntryAndValidationIsStrict_thenValidationFails() { + final SubjectCertificatePolicyValidator validator = new SubjectCertificatePolicyValidator( + Map.of(new X500Principal("CN=Another CA"), Set.of(ESTEID2018_POLICY)), + Set.of() + ); + + assertThatExceptionOfType(UserCertificateDisallowedPolicyException.class) + .isThrownBy(() -> validator.validateCertificatePolicies(getJaakKristjanEsteid2018Cert())) + .satisfies(exception -> { + assertThat(exception.getCertificateIssuer()).contains(ESTEID2018_TEST_ISSUER); + assertThat(exception.getCertificatePolicies()).isEmpty(); + }); + } + + @Test + void whenIssuerHasNoAllowListEntryAndValidationIsLenient_thenValidationFallsBackToDisallowedPolicies() + throws Exception { + final SubjectCertificatePolicyValidator validator = new SubjectCertificatePolicyValidator( + Map.of(new X500Principal("CN=Another CA"), Set.of(ESTEID2018_POLICY)), + List.of(ESTEID2018_POLICY), + true + ); + + assertThatExceptionOfType(UserCertificateDisallowedPolicyException.class) + .isThrownBy(() -> validator.validateCertificatePolicies(getJaakKristjanEsteid2018Cert())) + .satisfies(exception -> { + assertThat(exception.getCertificateIssuer()).isEmpty(); + assertThat(exception.getCertificatePolicies()).isEmpty(); + }); + } + + @Test + void whenIssuerAllowListIsEmpty_thenConstructionFails() { + assertThatThrownBy(() -> new SubjectCertificatePolicyValidator( + Map.of(ESTEID2018_TEST_ISSUER, Set.of()), + List.of(ESTEID2018_POLICY) + )) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("At least one allowed certificate policy is required for issuer " + + ESTEID2018_TEST_ISSUER.getName()); + } + @Test void whenCertificateDoesNotContainCertificatePoliciesExtension_thenValidationSucceeds() throws Exception { final SubjectCertificatePolicyValidator validator = new SubjectCertificatePolicyValidator(List.of(ESTEID2018_POLICY)); @@ -53,6 +144,20 @@ void whenCertificateDoesNotContainCertificatePoliciesExtension_thenValidationSuc .doesNotThrowAnyException(); } + @Test + void whenAllowListIsConfiguredAndCertificatePoliciesExtensionIsMissing_thenValidationFails() throws Exception { + when(certificate.getIssuerX500Principal()) + .thenReturn(ESTEID2018_TEST_ISSUER); + final SubjectCertificatePolicyValidator validator = + new SubjectCertificatePolicyValidator(allowedPolicies(ESTEID2018_POLICY), Set.of()); + assertThatExceptionOfType(UserCertificateDisallowedPolicyException.class) + .isThrownBy(() -> validator.validateCertificatePolicies(certificate)) + .satisfies(exception -> { + assertThat(exception.getCertificateIssuer()).contains(ESTEID2018_TEST_ISSUER); + assertThat(exception.getCertificatePolicies()).isEmpty(); + }); + } + @Test void whenPoliciesHaveInvalidEncoding_thenPreservesParsingFailure() { when(certificate.getExtensionValue(Extension.certificatePolicies.getId())).thenReturn(new byte[] {4, 2, 4, 5}); @@ -81,4 +186,9 @@ void whenPoliciesHaveWrongAsn1Type_thenPreservesParsingFailure() throws Exceptio .isInstanceOf(UserCertificateParseException.class) .hasCauseInstanceOf(IllegalArgumentException.class); } + + private static Map> allowedPolicies( + ASN1ObjectIdentifier... policies) { + return Map.of(ESTEID2018_TEST_ISSUER, Set.of(policies)); + } }