001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.auth.saml;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.io.*;
022import java.security.*;
023import java.time.*;
024import java.util.*;
025import java.util.logging.*;
026
027import javax.xml.parsers.*;
028import org.apache.juneau.commons.concurrent.*;
029import org.apache.juneau.rest.server.auth.*;
030import org.opensaml.core.criterion.*;
031import org.opensaml.core.xml.io.*;
032import org.opensaml.saml.common.xml.*;
033import org.opensaml.saml.criterion.*;
034import org.opensaml.saml.metadata.resolver.*;
035import org.opensaml.saml.saml2.core.*;
036import org.opensaml.saml.saml2.encryption.Decrypter;
037import org.opensaml.saml.saml2.metadata.*;
038import org.opensaml.saml.security.impl.*;
039import org.opensaml.security.credential.*;
040import org.opensaml.security.x509.*;
041import org.opensaml.xmlsec.encryption.support.*;
042import org.opensaml.xmlsec.keyinfo.*;
043import org.opensaml.xmlsec.keyinfo.impl.*;
044import org.opensaml.xmlsec.signature.*;
045import org.opensaml.xmlsec.signature.support.*;
046import org.opensaml.xmlsec.signature.support.SignatureException;
047import org.w3c.dom.*;
048
049import net.shibboleth.shared.resolver.*;
050
051/**
052 * Validates a SAML 2.0 {@code <samlp:Response>} document and produces a {@link ClaimsPrincipal} marked
053 * with {@code issuerType=SAML}.
054 *
055 * <p>
056 * Wraps OpenSAML 5.x's parser, unmarshaller, signature validator, and (optionally) assertion decrypter.
057 * The validator enforces:
058 *
059 * <ul>
060 *    <li><b>Mandatory assertion signature</b> &mdash; every assertion must carry its own enveloped signature.
061 *       A response that signs only the {@code <Response>} envelope (and not the assertion) is rejected as
062 *       unsigned; response-envelope-level signatures are not supported.
063 *    <li><b>Strict signature-algorithm allowlist</b> &mdash; only {@code rsa-sha256} and
064 *       {@code ecdsa-sha256} are accepted out of the box.  SHA-1 is permanently rejected.  The reference
065 *       {@code DigestMethod} is separately allowlisted (SHA-256/384/512), so a SHA-1 digest is rejected even
066 *       under a SHA-256 signature.
067 *    <li><b>Response status</b> &mdash; the {@code <samlp:Status>} must report the {@code Success} status code.
068 *    <li><b>Clock skew</b> &mdash; defaults to 60 seconds tolerance on {@code NotBefore} /
069 *       {@code NotOnOrAfter}; capped at 300 seconds.
070 *    <li><b>Audience restriction</b> &mdash; {@code <AudienceRestriction>} must list the configured SP entity ID.
071 *    <li><b>Bearer subject confirmation</b> &mdash; always enforced.  The ACS URL configured with
072 *       {@link Builder#recipient(String)} is required, and the assertion must carry a {@code bearer}
073 *       {@code <SubjectConfirmation>} whose {@code <SubjectConfirmationData>} names exactly that {@code Recipient},
074 *       is within its {@code NotBefore}/{@code NotOnOrAfter} window (the {@code NotOnOrAfter} is mandatory), and
075 *       satisfies the configured {@code Address} expectation.  The recipient is never taken from the request.
076 *       When the response carries a {@code Destination}, it must equal the configured ACS URL.
077 *    <li><b>Request binding</b> &mdash; a confirmation carrying {@code InResponseTo} must reference an
078 *       authentication request ID previously registered with {@link #rememberAuthnRequest(String)}; each ID is
079 *       accepted once.  A confirmation with no {@code InResponseTo} (an IdP-initiated response) is rejected unless
080 *       {@link Builder#allowIdpInitiated()} was set.
081 *    <li><b>One-time use</b> &mdash; each assertion ID is recorded in a {@link ReplayCache} and a second
082 *       presentation of the same ID is rejected.  The check is fail-closed: if the cache cannot answer, the
083 *       assertion is rejected.  An assertion whose validity window is unbounded &mdash; carrying neither a
084 *       {@code Conditions/NotOnOrAfter} nor a bearer {@code SubjectConfirmationData/NotOnOrAfter} &mdash; is
085 *       rejected outright, and the cache record is retained until the resolved {@code NotOnOrAfter} (plus clock
086 *       skew) rather than a short default window that would later expire and re-open replay.
087 *    <li><b>Encrypted assertions</b> &mdash; if the response contains
088 *       {@code <EncryptedAssertion>}, a {@code decryptionCredential} must be configured.  Only RSA-OAEP key
089 *       transport and AES-GCM content encryption are accepted, and every decryption problem is reported with the
090 *       same generic error.
091 * </ul>
092 *
093 * <h2 class='topic'>Marker claim</h2>
094 * <p>
095 * The returned {@link ClaimsPrincipal} is annotated with {@code issuerType=SAML} so downstream code
096 * can distinguish SAML-derived principals from JWT-derived principals without resorting to a subclass:
097 *
098 * <p class='bjava'>
099 *    <jk>if</jk> (<js>"SAML"</js>.equals(<jv>principal</jv>.getClaim(<js>"issuerType"</js>, String.<jk>class</jk>).orElse(<jk>null</jk>))) {
100 *       <jc>// SAML-issued principal</jc>
101 *    }
102 * </p>
103 *
104 * <h2 class='topic'>Builder usage</h2>
105 *
106 * <p>
107 * The ACS URL is mandatory.  Register each outgoing authentication request ID with
108 * {@link #rememberAuthnRequest(String)} so the response can be bound to it.
109 *
110 * <p class='bjava'>
111 *    <jk>var</jk> validator = SamlAssertionValidator.<jsm>create</jsm>()
112 *       .metadataResolver(SamlMetadataResolvers.<jsm>url</jsm>(<js>"https://idp.example.com/metadata"</js>))
113 *       .spEntityId(<js>"https://sp.example.com"</js>)
114 *       .expectedIssuer(<js>"https://idp.example.com"</js>)
115 *       .recipient(<js>"https://sp.example.com/saml/acs"</js>)
116 *       .build();
117 * </p>
118 *
119 * <h2 class='section'>See Also:</h2>
120 * <ul>
121 *    <li class='jc'>{@link SamlAuthFilter}
122 *    <li class='jc'>{@link SamlMetadataResolvers}
123 *    <li class='link'><a class="doclink" href="https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf">SAML 2.0 Core (OASIS)</a>
124 * </ul>
125 *
126 * @since 10.0.0
127 */
128@SuppressWarnings({
129   "java:S1192", // Duplicate string literals are SAML protocol claim names and JWT-style field keys; intentional
130   "java:S6539" // Monolithic class: validator is a single end-to-end pipeline.
131})
132public class SamlAssertionValidator {
133
134   private static final Logger LOG = Logger.getLogger(SamlAssertionValidator.class.getName());
135
136   /** Marker claim name on the returned {@link ClaimsPrincipal}. */
137   public static final String ISSUER_TYPE_CLAIM = "issuerType";
138
139   /** Marker claim value identifying the principal as SAML-issued. */
140   public static final String ISSUER_TYPE_SAML = "SAML";
141
142   /** Maximum clock-skew tolerance the builder will accept (5 minutes). */
143   private static final Duration MAX_CLOCK_SKEW = Duration.ofSeconds(300);
144
145   /** XML-DSig namespace URI, used when scanning the signature DOM for reference digest methods. */
146   private static final String XMLSIG_NS = "http://www.w3.org/2000/09/xmldsig#";
147
148   /** Default allowlist of XML signature algorithms. */
149   private static final Set<String> DEFAULT_ALGORITHMS = Set.of(
150      SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256,
151      SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA256
152   );
153
154   /** Decryption allowlist: RSA-OAEP key transport and AES-GCM content encryption only. */
155   private static final Set<String> DECRYPTION_ALGORITHMS = Set.of(
156      EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP,
157      EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP11,
158      EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM,
159      EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM,
160      EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM,
161      // RSA-OAEP parameters: the OAEP digest (SHA-1 is the OAEP default and is not collision-sensitive there) and MGF1.
162      SignatureConstants.ALGO_ID_DIGEST_SHA1,
163      SignatureConstants.ALGO_ID_DIGEST_SHA256,
164      SignatureConstants.ALGO_ID_DIGEST_SHA384,
165      SignatureConstants.ALGO_ID_DIGEST_SHA512,
166      EncryptionConstants.ALGO_ID_MGF1_SHA1,
167      EncryptionConstants.ALGO_ID_MGF1_SHA256,
168      EncryptionConstants.ALGO_ID_MGF1_SHA384,
169      EncryptionConstants.ALGO_ID_MGF1_SHA512
170   );
171
172   /** Default allowlist of XML reference digest algorithms.  SHA-1 is deliberately excluded. */
173   private static final Set<String> DEFAULT_DIGEST_ALGORITHMS = Set.of(
174      SignatureConstants.ALGO_ID_DIGEST_SHA256,
175      SignatureConstants.ALGO_ID_DIGEST_SHA384,
176      SignatureConstants.ALGO_ID_DIGEST_SHA512
177   );
178
179   /**
180    * Static creator.
181    *
182    * @return A new builder.
183    */
184   public static Builder create() {
185      return new Builder();
186   }
187
188   /**
189    * Builder for {@link SamlAssertionValidator}.
190    */
191   public static class Builder {
192      private MetadataResolver metadataResolver;
193      private Credential signingCredential;
194      private Credential decryptionCredential;
195      private String spEntityId;
196      private String expectedIssuer;
197      private String recipient;
198      private String expectedInResponseTo;
199      private String expectedAddress;
200      private Set<String> algorithms = new LinkedHashSet<>(DEFAULT_ALGORITHMS);
201      private Set<String> digestAlgorithms = new LinkedHashSet<>(DEFAULT_DIGEST_ALGORITHMS);
202      private Duration clockSkew = Duration.ofSeconds(60);
203      private Clock clock = Clock.systemUTC();
204      private ReplayCache replayCache;
205      private AuthnRequestStore authnRequestStore;
206      private boolean allowIdpInitiated;
207      private Duration authnRequestTtl = Duration.ofMinutes(10);
208
209      /** Constructor. */
210      protected Builder() {}
211
212      /**
213       * Sets the {@link MetadataResolver} used to resolve the IdP's signing credential at validation time.
214       *
215       * <p>
216       * Mutually exclusive with {@link #signingCredential(Credential)}.
217       *
218       * <p>
219       * The metadata supplies the trust anchor, so prefer a resolver whose metadata signature is verified against
220       * a pinned certificate, e.g. {@link SamlMetadataResolvers#url(String, java.security.cert.X509Certificate)}.
221       * Unsigned metadata is only as trustworthy as the transport it was fetched over.
222       *
223       * @param value The metadata resolver.  Must not be <jk>null</jk>.
224       * @return This object.
225       */
226      public Builder metadataResolver(MetadataResolver value) {
227         metadataResolver = reqnn("value", value);
228         return this;
229      }
230
231      /**
232       * Sets a static IdP signing credential.  Useful when metadata is not available.
233       *
234       * <p>
235       * Mutually exclusive with {@link #metadataResolver(MetadataResolver)}.
236       *
237       * @param value The IdP signing credential.  Must not be <jk>null</jk>.
238       * @return This object.
239       */
240      public Builder signingCredential(Credential value) {
241         signingCredential = reqnn("value", value);
242         return this;
243      }
244
245      /**
246       * Sets the credential used to decrypt {@code <EncryptedAssertion>} elements.
247       *
248       * <p>
249       * If the response contains encrypted assertions and no decryption credential is configured,
250       * validation fails with {@link AuthenticationException}.
251       *
252       * @param value The SP decryption credential.  Must not be <jk>null</jk>.
253       * @return This object.
254       */
255      public Builder decryptionCredential(Credential value) {
256         decryptionCredential = reqnn("value", value);
257         return this;
258      }
259
260      /**
261       * Sets the Service Provider entity ID used to validate {@code <AudienceRestriction>}.
262       *
263       * @param value The SP entity ID.  Must not be <jk>null</jk> or blank.
264       * @return This object.
265       */
266      public Builder spEntityId(String value) {
267         spEntityId = reqnb("value", value);
268         return this;
269      }
270
271      /**
272       * Sets the expected IdP issuer (the {@code <Issuer>} element).  Required.
273       *
274       * @param value The expected IdP entity ID.  Must not be <jk>null</jk> or blank.
275       * @return This object.
276       */
277      public Builder expectedIssuer(String value) {
278         expectedIssuer = reqnb("value", value);
279         return this;
280      }
281
282      /**
283       * Replaces the default signature-algorithm allowlist with the supplied URIs.
284       *
285       * <p>
286       * SHA-1 algorithms are silently filtered out (permanent rejection).
287       *
288       * @param values The XML-DSig algorithm URIs to allow.  Must contain at least one non-SHA-1 entry.
289       * @return This object.
290       */
291      public Builder algorithms(String... values) {
292         reqnn("values", values);
293         if (values.length == 0)
294            throw iaex("algorithms allowlist must be non-empty");
295         var next = new LinkedHashSet<String>();
296         for (var a : values) {
297            reqnn("algorithm", a);
298            if (a.toLowerCase(Locale.ROOT).contains("sha1"))
299               throw iaex("SHA-1 algorithms are permanently rejected: %s", a);
300            next.add(a);
301         }
302         algorithms = next;
303         return this;
304      }
305
306      /**
307       * Replaces the default reference-digest allowlist with the supplied URIs.
308       *
309       * <p>
310       * The reference {@code DigestMethod} of the enveloped signature must appear in this set.  SHA-1
311       * algorithms are silently filtered out (permanent rejection), mirroring {@link #algorithms(String...)}.
312       *
313       * @param values The XML-DSig digest algorithm URIs to allow.  Must contain at least one non-SHA-1 entry.
314       * @return This object.
315       */
316      public Builder digestAlgorithms(String... values) {
317         reqnn("values", values);
318         if (values.length == 0)
319            throw iaex("digest allowlist must be non-empty");
320         var next = new LinkedHashSet<String>();
321         for (var a : values) {
322            reqnn("digestAlgorithm", a);
323            if (a.toLowerCase(Locale.ROOT).contains("sha1"))
324               throw iaex("SHA-1 digest algorithms are permanently rejected: %s", a);
325            next.add(a);
326         }
327         digestAlgorithms = next;
328         return this;
329      }
330
331      /**
332       * Sets the expected {@code Recipient} (this SP's Assertion Consumer Service URL).  Required.
333       *
334       * <p>
335       * Every validated assertion must carry a {@code bearer} {@code <SubjectConfirmation>} whose
336       * {@code <SubjectConfirmationData>} names this exact {@code Recipient}, is within its
337       * {@code NotBefore}/{@code NotOnOrAfter} window, and satisfies the {@link #subjectAddress(String)}
338       * expectation.  A response carrying a {@code Destination} must name this URL as well.
339       *
340       * @param value The expected ACS URL.  Must not be <jk>null</jk> or blank.
341       * @return This object.
342       */
343      public Builder recipient(String value) {
344         recipient = reqnb("value", value);
345         return this;
346      }
347
348      /**
349       * Pins the request ID a bearer {@code <SubjectConfirmationData>} must echo in its {@code InResponseTo}
350       * attribute.
351       *
352       * <p>
353       * When set, the confirmation's {@code InResponseTo} must equal this value.  When left unset (the default),
354       * a present {@code InResponseTo} must reference an ID registered with
355       * {@link SamlAssertionValidator#rememberAuthnRequest(String)}.
356       *
357       * @param value The expected request ID.  Must not be <jk>null</jk> or blank.
358       * @return This object.
359       */
360      public Builder expectedInResponseTo(String value) {
361         expectedInResponseTo = reqnb("value", value);
362         return this;
363      }
364
365      /**
366       * Sets the client address a bearer {@code <SubjectConfirmationData>} must name in its {@code Address}
367       * attribute.
368       *
369       * <p>
370       * When set, the confirmation's
371       * {@code Address} must equal this value; when unset (the default) the {@code Address} attribute is not
372       * checked.
373       *
374       * @param value The expected client address.  Must not be <jk>null</jk> or blank.
375       * @return This object.
376       */
377      public Builder subjectAddress(String value) {
378         expectedAddress = reqnb("value", value);
379         return this;
380      }
381
382      /**
383       * Overrides the {@link ReplayCache} used to enforce one-time use of each assertion ID.
384       *
385       * <p>
386       * Defaults to a per-process {@link InMemoryReplayCache}, which enforces single-use within one JVM; a
387       * warning is logged when the default is used.
388       * Multi-node deployments should inject a {@link ReplayCache} backed by a store shared across every node
389       * so an assertion consumed against one node cannot be replayed against another.  The check is always
390       * fail-closed: a cache that cannot answer causes the assertion to be rejected.
391       *
392       * @param value The replay cache.  Must not be <jk>null</jk>.
393       * @return This object.
394       */
395      public Builder replayCache(ReplayCache value) {
396         replayCache = reqnn("value", value);
397         return this;
398      }
399
400      /**
401       * Allows IdP-initiated responses, i.e. a bearer confirmation that carries no {@code InResponseTo}.
402       *
403       * <p>
404       * Off by default.  An unsolicited response cannot be bound to a request this SP made, so enable it only
405       * when the IdP starts the login flow.
406       *
407       * @return This object.
408       */
409      public Builder allowIdpInitiated() {
410         allowIdpInitiated = true;
411         return this;
412      }
413
414      /**
415       * Overrides the {@link AuthnRequestStore} that tracks outstanding authentication request IDs.
416       *
417       * <p>
418       * Defaults to a per-process {@link InMemoryAuthnRequestStore}, which holds up to
419       * {@link InMemoryAuthnRequestStore#DEFAULT_MAX_ENTRIES} IDs and is not shared between nodes; a warning is
420       * logged when the default is used.  Multi-node deployments should inject a store shared across every node.
421       *
422       * @param value The store.  Must not be <jk>null</jk>.
423       * @return This object.
424       */
425      public Builder authnRequestStore(AuthnRequestStore value) {
426         authnRequestStore = reqnn("value", value);
427         return this;
428      }
429
430      /**
431       * Sets how long a request ID registered with {@link SamlAssertionValidator#rememberAuthnRequest(String)}
432       * stays valid.  Defaults to 10 minutes.
433       *
434       * @param value The lifetime.  Must be positive.
435       * @return This object.
436       */
437      public Builder authnRequestTtl(Duration value) {
438         reqnn("value", value);
439         if (value.isNegative() || value.isZero())
440            throw iaex("authnRequestTtl must be positive");
441         authnRequestTtl = value;
442         return this;
443      }
444
445      /**
446       * Sets the clock-skew tolerance for {@code NotBefore} / {@code NotOnOrAfter} validation.
447       *
448       * @param value The tolerance.  Must be non-negative and not exceed 5 minutes.
449       * @return This object.
450       */
451      public Builder clockSkew(Duration value) {
452         reqnn("value", value);
453         if (value.isNegative())
454            throw iaex("clockSkew must be non-negative");
455         if (value.compareTo(MAX_CLOCK_SKEW) > 0)
456            throw iaex("clockSkew must not exceed 5 minutes (was %s)", value);
457         clockSkew = value;
458         return this;
459      }
460
461      /**
462       * Overrides the {@link Clock} used for timestamp validation.  Useful in tests.
463       *
464       * @param value The clock.  Must not be <jk>null</jk>.
465       * @return This object.
466       */
467      public Builder clock(Clock value) {
468         clock = reqnn("value", value);
469         return this;
470      }
471
472      /**
473       * Builds the validator.
474       *
475       * @return A new {@link SamlAssertionValidator}.
476       */
477      public SamlAssertionValidator build() {
478         if (spEntityId == null)
479            throw new IllegalStateException("SamlAssertionValidator requires spEntityId(...)");
480         if (expectedIssuer == null)
481            throw new IllegalStateException("SamlAssertionValidator requires expectedIssuer(...)");
482         if (metadataResolver == null && signingCredential == null)
483            throw new IllegalStateException("SamlAssertionValidator requires either metadataResolver(...) or signingCredential(...)");
484         if (metadataResolver != null && signingCredential != null)
485            throw new IllegalStateException("SamlAssertionValidator: metadataResolver(...) and signingCredential(...) are mutually exclusive");
486         if (recipient == null)
487            throw new IllegalStateException("SamlAssertionValidator requires recipient(...) (the SP assertion consumer service URL)");
488         if (replayCache == null) {
489            LOG.warning("SamlAssertionValidator is using the default in-memory replay cache, which is not shared between nodes; configure replayCache(...) for multi-node deployments.");
490            replayCache = new InMemoryReplayCache();
491         }
492         if (authnRequestStore == null) {
493            LOG.warning("SamlAssertionValidator is using the default in-memory authentication request store, which is not shared between nodes; configure authnRequestStore(...) for multi-node deployments.");
494            authnRequestStore = new InMemoryAuthnRequestStore();
495         }
496         return new SamlAssertionValidator(this);
497      }
498   }
499
500   private final MetadataResolver metadataResolver;
501   private final Credential signingCredential;
502   private final Credential decryptionCredential;
503   private final String spEntityId;
504   private final String expectedIssuer;
505   private final String recipient;
506   private final String expectedInResponseTo;
507   private final String expectedAddress;
508   private final Set<String> algorithms;
509   private final Set<String> digestAlgorithms;
510   private final Duration clockSkew;
511   private final Clock clock;
512   private final ReplayCache replayCache;
513   private final boolean allowIdpInitiated;
514   private final Duration authnRequestTtl;
515   private final AuthnRequestStore authnRequestStore;
516
517   /** Attribute names that cannot replace the validator-set claims. */
518   private static final Set<String> RESERVED_CLAIMS = Set.of(ISSUER_TYPE_CLAIM, "iss", "aud");
519
520   /**
521    * Constructor.
522    *
523    * @param b The builder to read configuration from.
524    */
525   protected SamlAssertionValidator(Builder b) {
526      OpenSamlBootstrap.ensureInitialized();
527      this.metadataResolver = b.metadataResolver;
528      this.signingCredential = b.signingCredential;
529      this.decryptionCredential = b.decryptionCredential;
530      this.spEntityId = b.spEntityId;
531      this.expectedIssuer = b.expectedIssuer;
532      this.recipient = b.recipient;
533      this.expectedInResponseTo = b.expectedInResponseTo;
534      this.expectedAddress = b.expectedAddress;
535      this.algorithms = u(cp(b.algorithms));
536      this.digestAlgorithms = u(cp(b.digestAlgorithms));
537      this.clockSkew = b.clockSkew;
538      this.clock = b.clock;
539      this.replayCache = b.replayCache;
540      this.authnRequestStore = b.authnRequestStore;
541      this.allowIdpInitiated = b.allowIdpInitiated;
542      this.authnRequestTtl = b.authnRequestTtl;
543   }
544
545   /**
546    * Returns the SP entity ID this validator enforces in {@code <AudienceRestriction>}.
547    *
548    * @return The configured SP entity ID.
549    */
550   public String getSpEntityId() {
551      return spEntityId;
552   }
553
554   /**
555    * Returns the expected IdP {@code <Issuer>} value.
556    *
557    * @return The expected issuer.
558    */
559   public String getExpectedIssuer() {
560      return expectedIssuer;
561   }
562
563   /**
564    * Returns the configured signature algorithm allowlist.
565    *
566    * @return The unmodifiable allowlist.
567    */
568   public Set<String> getAlgorithms() {
569      return algorithms;
570   }
571
572   /**
573    * Returns the configured clock-skew tolerance.
574    *
575    * @return The clock skew.
576    */
577   public Duration getClockSkew() {
578      return clockSkew;
579   }
580
581   /**
582    * Registers the ID of an authentication request this SP sent, so a response answering it can be accepted.
583    *
584    * <p>
585    * Each registered ID is accepted once and expires after the configured request lifetime.  The registry is the
586    * {@link AuthnRequestStore} supplied to {@link Builder#authnRequestStore(AuthnRequestStore)} (in-memory by default).
587    *
588    * @param id The {@code ID} attribute of the outgoing {@code <AuthnRequest>}.  Must not be <jk>null</jk> or blank.
589    * @throws IllegalStateException If the store cannot accept more outstanding requests.
590    */
591   public void rememberAuthnRequest(String id) {
592      reqnb("id", id);
593      var now = clock.millis();
594      authnRequestStore.remember(id, now + authnRequestTtl.toMillis(), now);
595   }
596
597   private boolean consumeAuthnRequest(String id) {
598      return authnRequestStore.consume(id, clock.millis());
599   }
600
601   /**
602    * Validates the supplied SAML 2.0 {@code <samlp:Response>} XML and returns the resolved principal.
603    *
604    * @param xml The full XML payload (already base64-decoded; already URL-decoded and inflated for the
605    *    REDIRECT binding).  Must be a {@code <samlp:Response>} envelope.
606    * @return A {@link ClaimsPrincipal} carrying the IdP-supplied claims plus the {@code issuerType=SAML}
607    *    marker.
608    * @throws AuthenticationException If the response cannot be parsed or validation fails.
609    */
610   public Principal validate(String xml) throws AuthenticationException {
611      reqnb("xml", xml);
612      var response = parseResponse(xml);
613      validateStatus(response);
614      validateDestination(response);
615      var assertion = extractAndDecryptAssertion(response);
616      verifySignature(assertion);
617      var claims = buildClaims(response, assertion);
618      validateSubjectConfirmation(assertion);
619      recordSingleUse(assertion);
620      var subject = nameId(assertion);
621      return new ClaimsPrincipal(subject, claims);
622   }
623
624   private void validateDestination(Response response) throws AuthenticationException {
625      var destination = response.getDestination();
626      if (destination != null && neq(recipient, destination))
627         throw new AuthenticationException("SAML response <Destination> does not match the expected ACS URL")
628            .wwwAuthenticate("SAML error=\"invalid_response\"");
629   }
630
631   private void validateStatus(Response response) throws AuthenticationException {
632      var status = response.getStatus();
633      var code = status == null ? null : status.getStatusCode();
634      var value = code == null ? null : code.getValue();
635      if (! StatusCode.SUCCESS.equals(value))
636         throw new AuthenticationException("SAML response status is not Success: " + value)
637            .wwwAuthenticate("SAML error=\"invalid_response\"");
638   }
639
640   private Response parseResponse(String xml) throws AuthenticationException {
641      try {
642         var doc = SamlXml.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes(java.nio.charset.StandardCharsets.UTF_8)));
643         Element root = doc.getDocumentElement();
644         var registry = org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
645         var unmarshaller = registry.getUnmarshaller(root);
646         if (unmarshaller == null)
647            throw new AuthenticationException("Unknown SAML element: " + root.getNodeName())
648               .wwwAuthenticate("SAML error=\"invalid_response\"");
649         var obj = unmarshaller.unmarshall(root);
650         if (!(obj instanceof Response obj2))
651            throw new AuthenticationException("SAML envelope is not a <Response>: " + cns(obj))
652               .wwwAuthenticate("SAML error=\"invalid_response\"");
653         return obj2;
654      } catch (UnmarshallingException | ParserConfigurationException | IOException | org.xml.sax.SAXException e) {
655         throw new AuthenticationException(e, "SAML response could not be parsed")
656            .wwwAuthenticate("SAML error=\"invalid_response\"");
657      }
658   }
659
660   private Assertion extractAndDecryptAssertion(Response response) throws AuthenticationException {
661      var assertions = response.getAssertions();
662      var encrypted = response.getEncryptedAssertions();
663      if (assertions.isEmpty() && encrypted.isEmpty())
664         throw new AuthenticationException("SAML response contains no <Assertion>")
665            .wwwAuthenticate("SAML error=\"invalid_response\"");
666      if (!encrypted.isEmpty()) {
667         if (decryptionCredential == null) {
668            LOG.fine("SAML response contains <EncryptedAssertion> but no decryption credential is configured");
669            throw decryptionFailed();
670         }
671         var resolver = (KeyInfoCredentialResolver) new StaticKeyInfoCredentialResolver(decryptionCredential);
672         EncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(List.of(
673            new InlineEncryptedKeyResolver(),
674            new SimpleRetrievalMethodEncryptedKeyResolver()
675         ));
676         try {
677            var decrypter = new Decrypter(null, resolver, keyResolver, DECRYPTION_ALGORITHMS, null);
678            decrypter.setRootInNewDocument(true);
679            return decrypter.decrypt(encrypted.get(0));
680         } catch (DecryptionException | RuntimeException e) {
681            LOG.log(Level.FINE, e, () -> "SAML <EncryptedAssertion> could not be decrypted");
682            throw decryptionFailed();
683         }
684      }
685      return assertions.get(0);
686   }
687
688   private static AuthenticationException decryptionFailed() {
689      return new AuthenticationException("SAML response could not be decrypted")
690         .wwwAuthenticate("SAML error=\"decryption_failed\"");
691   }
692
693   private void verifySignature(Assertion assertion) throws AuthenticationException {
694      var signature = assertion.getSignature();
695      if (signature == null)
696         throw new AuthenticationException("SAML assertion is unsigned")
697            .wwwAuthenticate("SAML error=\"signature_required\"");
698
699      var alg = signature.getSignatureAlgorithm();
700      if (alg == null || !algorithms.contains(alg)) // HTT: alg==null unreachable; a signature with no SignatureMethod is rejected while parsing the response
701         throw new AuthenticationException("SAML signature algorithm not allowlisted: " + alg)
702            .wwwAuthenticate("SAML error=\"signature_algorithm_rejected\"");
703
704      validateDigestAlgorithms(signature);
705
706      // First, run the SAML signature profile validator to catch wrapping/structural attacks.
707      try {
708         new SAMLSignatureProfileValidator().validate(signature);
709      } catch (SignatureException e) {
710         throw new AuthenticationException(e, "SAML signature profile validation failed")
711            .wwwAuthenticate("SAML error=\"signature_invalid\"");
712      }
713
714      Credential credential = resolveSigningCredential();
715      try {
716         SignatureValidator.validate(signature, credential);
717      } catch (SignatureException e) {
718         throw new AuthenticationException(e, "SAML signature verification failed")
719            .wwwAuthenticate("SAML error=\"signature_invalid\"");
720      }
721   }
722
723   private Credential resolveSigningCredential() throws AuthenticationException {
724      if (signingCredential != null)
725         return signingCredential;
726      var idp = resolveIdpDescriptor();
727      var credential = extractSigningCredential(idp);
728      if (credential == null)
729         throw new AuthenticationException("No signing X.509 certificate in metadata for issuer: " + expectedIssuer)
730            .wwwAuthenticate("SAML error=\"metadata_invalid\"");
731      return credential;
732   }
733
734   private IDPSSODescriptor resolveIdpDescriptor() throws AuthenticationException {
735      try {
736         var criteria = new CriteriaSet(
737            new EntityIdCriterion(expectedIssuer),
738            new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME)
739         );
740         var entityDescriptor = metadataResolver.resolveSingle(criteria);
741         if (entityDescriptor == null)
742            throw new AuthenticationException("No SAML metadata for issuer: " + expectedIssuer)
743               .wwwAuthenticate("SAML error=\"metadata_missing\"");
744         var idp = entityDescriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS);
745         if (idp == null)
746            throw new AuthenticationException("SAML metadata for issuer has no IDPSSODescriptor")
747               .wwwAuthenticate("SAML error=\"metadata_invalid\"");
748         return idp;
749      } catch (ResolverException e) {
750         throw new AuthenticationException(e, "SAML metadata resolution failed")
751            .wwwAuthenticate("SAML error=\"metadata_invalid\"");
752      }
753   }
754
755   private Credential extractSigningCredential(IDPSSODescriptor idp) {
756      for (KeyDescriptor kd : idp.getKeyDescriptors()) {
757         var credential = credentialFromKeyDescriptor(kd);
758         if (credential != null)
759            return credential;
760      }
761      return null;
762   }
763
764   private Credential credentialFromKeyDescriptor(KeyDescriptor kd) {
765      if (!isSigningKey(kd))
766         return null;
767      var keyInfo = kd.getKeyInfo();
768      if (keyInfo == null)
769         return null;
770      for (var x509 : keyInfo.getX509Datas()) {
771         var credential = credentialFromX509Data(x509);
772         if (credential != null)
773            return credential;
774      }
775      return null;
776   }
777
778   private Credential credentialFromX509Data(X509Data x509) {
779      for (var cert : x509.getX509Certificates()) {
780         var base64 = cert.getValue();
781         if (base64 == null)
782            continue;
783         var credential = parseX509Credential(base64);
784         if (credential != null)
785            return credential;
786      }
787      return null;
788   }
789
790   private static boolean isSigningKey(KeyDescriptor kd) {
791      return kd.getUse() == null || kd.getUse() == UsageType.SIGNING || kd.getUse() == UsageType.UNSPECIFIED;
792   }
793
794   private BasicX509Credential parseX509Credential(String base64) {
795      try {
796         var bytes = Base64.getMimeDecoder().decode(base64);
797         var cf = java.security.cert.CertificateFactory.getInstance("X.509");
798         var certificate = (java.security.cert.X509Certificate) cf.generateCertificate(new ByteArrayInputStream(bytes));
799         // The metadata signing cert is the trust anchor; reject one outside its validity window so an
800         // expired (or not-yet-valid) cert can no longer be used to verify assertions.
801         certificate.checkValidity(Date.from(clock.instant()));
802         return new BasicX509Credential(certificate);
803      } catch (java.security.cert.CertificateException | IllegalArgumentException e) {
804         return null;  // Expired/not-yet-valid or malformed cert: caller tries the next certificate.
805      }
806   }
807
808   private Map<String,Object> buildClaims(Response response, Assertion assertion) throws AuthenticationException {
809      validateConditions(assertion);
810      validateIssuer(response, assertion);
811
812      Map<String,Object> claims = m(ISSUER_TYPE_CLAIM, ISSUER_TYPE_SAML, "iss", expectedIssuer, "aud", spEntityId);
813
814      for (var stmt : assertion.getAttributeStatements()) {
815         for (var attr : stmt.getAttributes()) {
816            var name = attr.getName();
817            if (name == null || RESERVED_CLAIMS.contains(name))
818               continue;
819            var values = l();
820            for (var av : attr.getAttributeValues())
821               values.add(extractStringValue(av));
822            if (values.size() == 1)
823               claims.put(name, values.get(0));
824            else if (!values.isEmpty())
825               claims.put(name, values);
826         }
827      }
828      return claims;
829   }
830
831   private void validateConditions(Assertion assertion) throws AuthenticationException {
832      var conditions = assertion.getConditions();
833      if (conditions == null)
834         throw rejectAssertion("missing <Conditions>");
835
836      var now = clock.instant();
837      var nbf = conditions.getNotBefore();
838      var noa = conditions.getNotOnOrAfter();
839      if (nbf != null && nbf.minus(clockSkew).isAfter(now))
840         throw rejectAssertion("assertion not yet valid");
841      if (noa != null && !noa.plus(clockSkew).isAfter(now))
842         throw rejectAssertion("assertion has expired");
843
844      boolean audienceOk = false;
845      for (var ar : conditions.getAudienceRestrictions()) {
846         for (var aud : ar.getAudiences()) {
847            if (eq(spEntityId, aud.getURI())) {
848               audienceOk = true;
849               break;
850            }
851         }
852      }
853      if (!audienceOk)
854         throw rejectAssertion("audience does not include SP entity ID: " + spEntityId);
855   }
856
857   private void validateIssuer(Response response, Assertion assertion) throws AuthenticationException {
858      var assertionIssuer = assertion.getIssuer();
859      if (assertionIssuer == null || neq(expectedIssuer, assertionIssuer.getValue()))
860         throw rejectAssertion("assertion <Issuer> does not match expected issuer");
861      var respIssuer = response.getIssuer();
862      if (respIssuer != null && neq(expectedIssuer, respIssuer.getValue()))
863         throw rejectAssertion("response <Issuer> does not match expected issuer");
864   }
865
866   private void validateDigestAlgorithms(org.opensaml.xmlsec.signature.Signature signature) throws AuthenticationException {
867      var dom = signature.getDOM();
868      if (dom == null) // HTT: null DOM unreachable; a verifiable signature is always marshalled to DOM
869         return; // HTT: null DOM unreachable; a verifiable signature is always marshalled to DOM
870      var digestNodes = dom.getElementsByTagNameNS(XMLSIG_NS, "DigestMethod");
871      for (var i = 0; i < digestNodes.getLength(); i++) {
872         var alg = ((Element) digestNodes.item(i)).getAttribute("Algorithm");
873         if (alg == null || alg.isEmpty() || alg.toLowerCase(Locale.ROOT).contains("sha1") || !digestAlgorithms.contains(alg)) // HTT: the alg==null clause is unreachable because Element.getAttribute never returns null; kept as a fail-closed guard
874            throw new AuthenticationException("SAML signature digest algorithm not allowlisted: " + alg)
875               .wwwAuthenticate("SAML error=\"signature_algorithm_rejected\"");
876      }
877   }
878
879   private void validateSubjectConfirmation(Assertion assertion) throws AuthenticationException {
880      var subject = assertion.getSubject();
881      if (subject == null)
882         throw rejectAssertion("missing <Subject> for bearer confirmation");
883      String failure = null;
884      var sawBearer = false;
885      for (var sc : subject.getSubjectConfirmations()) {
886         if (! SubjectConfirmation.METHOD_BEARER.equals(sc.getMethod()))
887            continue;
888         sawBearer = true;
889         var reason = confirmationFailureReason(sc);
890         if (reason == null)
891            return;  // A valid bearer confirmation was found.
892         failure = reason;
893      }
894      if (! sawBearer)
895         throw rejectAssertion("missing bearer <SubjectConfirmation>");
896      throw rejectAssertion(failure);
897   }
898
899   @SuppressWarnings({
900      "java:S3776" // Branching is inherent to the ordered bearer-confirmation checks.
901   })
902   private String confirmationFailureReason(SubjectConfirmation sc) {
903      var data = sc.getSubjectConfirmationData();
904      if (data == null)
905         return "bearer <SubjectConfirmationData> is missing";
906      if (neq(recipient, data.getRecipient()))
907         return "bearer confirmation <Recipient> does not match the expected ACS URL";
908      var now = clock.instant();
909      var noa = data.getNotOnOrAfter();
910      if (noa == null)
911         return "bearer confirmation is missing NotOnOrAfter";
912      if (! noa.plus(clockSkew).isAfter(now))
913         return "bearer confirmation has expired";
914      var nbf = data.getNotBefore();
915      if (nbf != null && nbf.minus(clockSkew).isAfter(now))
916         return "bearer confirmation is not yet valid";
917      var inResponseTo = data.getInResponseTo();
918      var hasInResponseTo = inResponseTo != null && ! inResponseTo.isEmpty(); // HTT: OpenSAML trims an empty InResponseTo to null; kept as a fail-closed guard
919      if (expectedInResponseTo != null) {
920         if (neq(expectedInResponseTo, inResponseTo))
921            return "bearer confirmation <InResponseTo> does not match the expected request ID";
922      } else if (hasInResponseTo) {
923         if (! consumeAuthnRequest(inResponseTo))
924            return "bearer confirmation <InResponseTo> does not reference an outstanding request";
925      } else if (! allowIdpInitiated) {
926         return "unsolicited (IdP-initiated) responses are not allowed";
927      }
928      if (expectedAddress != null && neq(expectedAddress, data.getAddress()))
929         return "bearer confirmation <Address> does not match the expected client address";
930      return null;
931   }
932
933   private void recordSingleUse(Assertion assertion) throws AuthenticationException {
934      var id = assertion.getID();
935      if (id == null || id.isEmpty()) // HTT: OpenSAML trims an empty ID to null, so the isEmpty() branch cannot run; kept as a fail-closed guard
936         throw rejectAssertion("assertion has no ID for single-use enforcement");
937      var notOnOrAfter = resolveNotOnOrAfter(assertion);
938      if (notOnOrAfter == null)
939         throw rejectAssertion("assertion has no NotOnOrAfter to bound one-time use");
940      var expiresAtMs = notOnOrAfter.plus(clockSkew).toEpochMilli();
941      var firstSeen = replayCache.checkAndRecord(id, expiresAtMs, ReplayCache.FailMode.FAIL_CLOSED,
942         e -> LOG.log(Level.WARNING, e, () -> "SAML assertion single-use check failed; rejecting (fail-closed)."));
943      if (! firstSeen)
944         throw new AuthenticationException("SAML assertion has already been presented")
945            .wwwAuthenticate("SAML error=\"assertion_replayed\"");
946   }
947
948   /**
949    * Resolves the effective {@code NotOnOrAfter} that bounds one-time use of the assertion.
950    *
951    * <p>
952    * The resolved value is the latest of the assertion's {@code Conditions/NotOnOrAfter} and any bearer
953    * {@code SubjectConfirmationData/NotOnOrAfter}.  Returns <jk>null</jk> when the assertion carries neither
954    * &mdash; in that case its validity window is unbounded, so single-use cannot be enforced past a cache
955    * eviction and the caller rejects the assertion rather than inventing a short fallback that later re-opens
956    * replay.  {@code <Conditions>} itself is guaranteed non-<jk>null</jk> here (a null {@code <Conditions>} is
957    * rejected earlier by {@link #validateConditions(Assertion)}).
958    *
959    * @param assertion The assertion.
960    * @return The latest bounding instant, or <jk>null</jk> if the assertion carries no {@code NotOnOrAfter}.
961    */
962   private static Instant resolveNotOnOrAfter(Assertion assertion) {
963      var result = assertion.getConditions().getNotOnOrAfter();
964      var subject = assertion.getSubject();
965      if (subject != null) {
966         for (var sc : subject.getSubjectConfirmations()) {
967            var noa = bearerNotOnOrAfter(sc);
968            if (noa != null && (result == null || noa.isAfter(result)))
969               result = noa;
970         }
971      }
972      return result;
973   }
974
975   /**
976    * Returns the {@code NotOnOrAfter} of {@code sc}'s {@code <SubjectConfirmationData>} if {@code sc} is a
977    * bearer confirmation carrying one, or <jk>null</jk> otherwise.
978    *
979    * @param sc The subject confirmation.
980    * @return The bearer confirmation's {@code NotOnOrAfter}, or <jk>null</jk>.
981    */
982   private static Instant bearerNotOnOrAfter(SubjectConfirmation sc) {
983      if (! SubjectConfirmation.METHOD_BEARER.equals(sc.getMethod()))
984         return null;
985      var data = sc.getSubjectConfirmationData();
986      return data == null ? null : data.getNotOnOrAfter();
987   }
988
989   private static String extractStringValue(org.opensaml.core.xml.XMLObject av) {
990      if (av == null) // HTT: null av unreachable; OpenSAML attribute value lists never contain null entries
991         return null; // HTT: null av unreachable; OpenSAML attribute value lists never contain null entries
992      var dom = av.getDOM();
993      if (dom != null) // HTT: the response is always parsed from XML, so every unmarshalled value carries its DOM
994         return dom.getTextContent();
995      return av.toString(); // HTT: the response is always parsed from XML, so every unmarshalled value carries its DOM
996   }
997
998   private static String nameId(Assertion assertion) throws AuthenticationException {
999      var subject = assertion.getSubject();
1000      var nameID = subject == null ? null : subject.getNameID();
1001      if (nameID == null || nameID.getValue() == null || nameID.getValue().isBlank())
1002         throw rejectAssertion("missing <NameID> subject");
1003      return nameID.getValue();
1004   }
1005
1006   private static AuthenticationException rejectAssertion(String reason) {
1007      return new AuthenticationException("SAML assertion rejected: " + reason)
1008         .wwwAuthenticate("SAML error=\"invalid_assertion\"");
1009   }
1010}