Search in sources :

Example 1 with SAMLException

use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.

the class SAML2DefaultResponseValidator method validate.

/**
 * Validates the SAML protocol response and the SAML SSO response.
 * The method decrypt encrypted assertions if any.
 *
 * @param context the context
 */
@Override
public Credentials validate(final SAML2MessageContext context) {
    final SAMLObject message = context.getMessage();
    if (!(message instanceof Response)) {
        throw new SAMLException("Response instance is an unsupported type");
    }
    final Response response = (Response) message;
    final SignatureTrustEngine engine = this.signatureTrustEngineProvider.build();
    validateSamlProtocolResponse(response, context, engine);
    if (decrypter != null) {
        decryptEncryptedAssertions(response, decrypter);
    }
    validateSamlSSOResponse(response, context, engine, decrypter);
    return buildSAML2Credentials(context);
}
Also used : Response(org.opensaml.saml.saml2.core.Response) SAMLObject(org.opensaml.saml.common.SAMLObject) SignatureTrustEngine(org.opensaml.xmlsec.signature.support.SignatureTrustEngine) SAMLException(org.pac4j.saml.exceptions.SAMLException)

Example 2 with SAMLException

use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.

the class SAML2LogoutResponseValidator method validateSamlProtocolResponse.

/**
 * Validates the SAML protocol response:
 *  - IssueInstant
 *  - Issuer
 *  - StatusCode
 *  - Signature
 *
 * @param response the response
 * @param context the context
 * @param engine the engine
 */
protected final void validateSamlProtocolResponse(final Response response, final SAML2MessageContext context, final SignatureTrustEngine engine) {
    if (!StatusCode.SUCCESS.equals(response.getStatus().getStatusCode().getValue())) {
        String status = response.getStatus().getStatusCode().getValue();
        if (response.getStatus().getStatusMessage() != null) {
            status += " / " + response.getStatus().getStatusMessage().getMessage();
        }
        throw new SAMLException("Logout response is not success ; actual " + status);
    }
    if (response.getSignature() != null) {
        final String entityId = context.getSAMLPeerEntityContext().getEntityId();
        validateSignature(response.getSignature(), entityId, engine);
        context.getSAMLPeerEntityContext().setAuthenticated(true);
    }
    if (!isIssueInstantValid(response.getIssueInstant())) {
        throw new SAMLIssueInstantException("Response issue instant is too old or in the future");
    }
    final SAMLMessageStorage messageStorage = context.getSAMLMessageStorage();
    if (messageStorage != null && response.getInResponseTo() != null) {
        final XMLObject xmlObject = messageStorage.retrieveMessage(response.getInResponseTo());
        if (xmlObject == null) {
            throw new SAMLInResponseToMismatchException("InResponseToField of the Response doesn't correspond to sent message " + response.getInResponseTo());
        } else if (!(xmlObject instanceof LogoutRequest)) {
            throw new SAMLInResponseToMismatchException("Sent request was of different type than the expected LogoutRequest " + response.getInResponseTo());
        }
    }
    verifyEndpoint(context.getSAMLEndpointContext().getEndpoint(), response.getDestination());
    if (response.getIssuer() != null) {
        validateIssuer(response.getIssuer(), context);
    }
}
Also used : SAMLInResponseToMismatchException(org.pac4j.saml.exceptions.SAMLInResponseToMismatchException) XMLObject(org.opensaml.core.xml.XMLObject) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) SAMLIssueInstantException(org.pac4j.saml.exceptions.SAMLIssueInstantException) SAMLMessageStorage(org.pac4j.saml.storage.SAMLMessageStorage) SAMLException(org.pac4j.saml.exceptions.SAMLException)

Example 3 with SAMLException

use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.

the class SAML2WebSSOMessageSender method sendMessage.

@Override
public void sendMessage(final SAML2MessageContext context, final AuthnRequest authnRequest, final Object relayState) {
    final SPSSODescriptor spDescriptor = context.getSPSSODescriptor();
    final IDPSSODescriptor idpssoDescriptor = context.getIDPSSODescriptor();
    final SingleSignOnService ssoService = context.getIDPSingleSignOnService(destinationBindingType);
    final AssertionConsumerService acsService = context.getSPAssertionConsumerService();
    final MessageEncoder encoder = getMessageEncoder(context);
    final SAML2MessageContext outboundContext = new SAML2MessageContext(context);
    outboundContext.getProfileRequestContext().setProfileId(context.getProfileRequestContext().getProfileId());
    outboundContext.getProfileRequestContext().setInboundMessageContext(context.getProfileRequestContext().getInboundMessageContext());
    outboundContext.getProfileRequestContext().setOutboundMessageContext(context.getProfileRequestContext().getOutboundMessageContext());
    outboundContext.setMessage(authnRequest);
    outboundContext.getSAMLEndpointContext().setEndpoint(acsService);
    outboundContext.getSAMLPeerEndpointContext().setEndpoint(ssoService);
    outboundContext.getSAMLPeerEntityContext().setRole(context.getSAMLPeerEntityContext().getRole());
    outboundContext.getSAMLPeerEntityContext().setEntityId(context.getSAMLPeerEntityContext().getEntityId());
    outboundContext.getSAMLProtocolContext().setProtocol(context.getSAMLProtocolContext().getProtocol());
    outboundContext.getSecurityParametersContext().setSignatureSigningParameters(this.signatureSigningParametersProvider.build(spDescriptor));
    if (relayState != null) {
        outboundContext.getSAMLBindingContext().setRelayState(relayState.toString());
    }
    try {
        invokeOutboundMessageHandlers(spDescriptor, idpssoDescriptor, outboundContext);
        encoder.setMessageContext(outboundContext);
        encoder.initialize();
        encoder.prepareContext();
        encoder.encode();
        final SAMLMessageStorage messageStorage = context.getSAMLMessageStorage();
        if (messageStorage != null) {
            messageStorage.storeMessage(authnRequest.getID(), authnRequest);
        }
    } catch (final MessageEncodingException e) {
        throw new SAMLException("Error encoding saml message", e);
    } catch (final ComponentInitializationException e) {
        throw new SAMLException("Error initializing saml encoder", e);
    }
}
Also used : SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) SAML2MessageContext(org.pac4j.saml.context.SAML2MessageContext) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) ComponentInitializationException(net.shibboleth.utilities.java.support.component.ComponentInitializationException) SingleSignOnService(org.opensaml.saml.saml2.metadata.SingleSignOnService) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) MessageEncoder(org.opensaml.messaging.encoder.MessageEncoder) SAMLMessageStorage(org.pac4j.saml.storage.SAMLMessageStorage) MessageEncodingException(org.opensaml.messaging.encoder.MessageEncodingException) SAMLException(org.pac4j.saml.exceptions.SAMLException)

Example 4 with SAMLException

use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.

the class SAML2WebSSOMessageSender method invokeOutboundMessageHandlers.

protected final void invokeOutboundMessageHandlers(final SPSSODescriptor spDescriptor, final IDPSSODescriptor idpssoDescriptor, final SAML2MessageContext outboundContext) {
    try {
        final EndpointURLSchemeSecurityHandler handlerEnd = new EndpointURLSchemeSecurityHandler();
        handlerEnd.initialize();
        handlerEnd.invoke(outboundContext);
        final SAMLOutboundDestinationHandler handlerDest = new SAMLOutboundDestinationHandler();
        handlerDest.initialize();
        handlerDest.invoke(outboundContext);
        boolean signOutboundContext = false;
        if (this.isAuthnRequestSigned) {
            logger.debug("Authn requests are expected to be always signed before submission");
            signOutboundContext = true;
        } else if (spDescriptor.isAuthnRequestsSigned()) {
            logger.debug("The service provider metadata indicates that authn requests are signed");
            signOutboundContext = true;
        } else if (idpssoDescriptor.getWantAuthnRequestsSigned()) {
            logger.debug("The identity provider metadata indicates that authn requests may be signed");
            signOutboundContext = true;
        }
        if (signOutboundContext) {
            logger.debug("Signing SAML2 outbound context...");
            final SAMLOutboundProtocolMessageSigningHandler handler = new SAMLOutboundProtocolMessageSigningHandler();
            handler.invoke(outboundContext);
        }
    } catch (final Exception e) {
        throw new SAMLException(e);
    }
}
Also used : EndpointURLSchemeSecurityHandler(org.opensaml.saml.common.binding.security.impl.EndpointURLSchemeSecurityHandler) SAMLOutboundProtocolMessageSigningHandler(org.opensaml.saml.common.binding.security.impl.SAMLOutboundProtocolMessageSigningHandler) SAMLOutboundDestinationHandler(org.opensaml.saml.common.binding.impl.SAMLOutboundDestinationHandler) SAMLException(org.pac4j.saml.exceptions.SAMLException) ComponentInitializationException(net.shibboleth.utilities.java.support.component.ComponentInitializationException) SAMLException(org.pac4j.saml.exceptions.SAMLException) MessageEncodingException(org.opensaml.messaging.encoder.MessageEncodingException)

Example 5 with SAMLException

use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.

the class SAML2ClientConfiguration method createKeystore.

private void createKeystore() {
    try {
        if (CommonHelper.isBlank(this.keyStoreAlias)) {
            this.keyStoreAlias = getClass().getSimpleName();
            LOGGER.warn("Using keystore alias {}", this.keyStoreAlias);
        }
        if (CommonHelper.isBlank(this.keyStoreType)) {
            this.keyStoreType = KeyStore.getDefaultType();
            LOGGER.warn("Using keystore type {}", this.keyStoreType);
        }
        final KeyStore ks = KeyStore.getInstance(this.keyStoreType);
        final char[] password = this.keystorePassword.toCharArray();
        ks.load(null, password);
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        final KeyPair kp = kpg.genKeyPair();
        final String sigAlgName = "SHA1WithRSA";
        final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
        final String dn = InetAddress.getLocalHost().getHostName();
        final PrivateKey signingKey = kp.getPrivate();
        final X509Certificate certificate = createSelfSignedCert(new X500Name("CN=" + dn), sigAlgName, sigAlgID, kp);
        final char[] keyPassword = this.privateKeyPassword.toCharArray();
        ks.setKeyEntry(this.keyStoreAlias, signingKey, keyPassword, new Certificate[] { certificate });
        try (final FileOutputStream fos = new FileOutputStream(this.keystoreResource.getFile().getCanonicalPath())) {
            ks.store(fos, password);
            fos.flush();
        }
        LOGGER.info("Created keystore {} with key alias {} ", keystoreResource.getFile().getCanonicalPath(), ks.aliases().nextElement());
    } catch (final Exception e) {
        throw new SAMLException("Could not create keystore", e);
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) FileOutputStream(java.io.FileOutputStream) KeyPairGenerator(java.security.KeyPairGenerator) DERBitString(org.bouncycastle.asn1.DERBitString) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) SAMLException(org.pac4j.saml.exceptions.SAMLException) X509Certificate(java.security.cert.X509Certificate) TechnicalException(org.pac4j.core.exception.TechnicalException) MalformedURLException(java.net.MalformedURLException) SAMLException(org.pac4j.saml.exceptions.SAMLException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

SAMLException (org.pac4j.saml.exceptions.SAMLException)19 ComponentInitializationException (net.shibboleth.utilities.java.support.component.ComponentInitializationException)7 MessageEncodingException (org.opensaml.messaging.encoder.MessageEncodingException)4 AssertionConsumerService (org.opensaml.saml.saml2.metadata.AssertionConsumerService)4 SAMLMessageStorage (org.pac4j.saml.storage.SAMLMessageStorage)4 CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)3 ResolverException (net.shibboleth.utilities.java.support.resolver.ResolverException)3 EntityDescriptor (org.opensaml.saml.saml2.metadata.EntityDescriptor)3 SAML2MessageContext (org.pac4j.saml.context.SAML2MessageContext)3 IOException (java.io.IOException)2 KeyStore (java.security.KeyStore)2 EntityIdCriterion (org.opensaml.core.criterion.EntityIdCriterion)2 XMLObject (org.opensaml.core.xml.XMLObject)2 MessageEncoder (org.opensaml.messaging.encoder.MessageEncoder)2 SAMLObject (org.opensaml.saml.common.SAMLObject)2 SAMLOutboundDestinationHandler (org.opensaml.saml.common.binding.impl.SAMLOutboundDestinationHandler)2 EndpointURLSchemeSecurityHandler (org.opensaml.saml.common.binding.security.impl.EndpointURLSchemeSecurityHandler)2 SAMLOutboundProtocolMessageSigningHandler (org.opensaml.saml.common.binding.security.impl.SAMLOutboundProtocolMessageSigningHandler)2 Response (org.opensaml.saml.saml2.core.Response)2 SPSSODescriptor (org.opensaml.saml.saml2.metadata.SPSSODescriptor)2