Search in sources :

Example 61 with Request

use of org.opensaml.saml.saml2.ecp.Request in project ddf by codice.

the class AuthnResponseValidator method validate.

public void validate(XMLObject xmlObject) throws ValidationException {
    if (!(xmlObject instanceof Response)) {
        throw new ValidationException("Invalid AuthN response XML.");
    }
    Response authnResponse = (Response) xmlObject;
    String status = authnResponse.getStatus().getStatusCode().getValue();
    if (!StatusCode.SUCCESS.equals(status)) {
        throw new ValidationException("AuthN request was unsuccessful.  Received status: " + status);
    }
    if (authnResponse.getAssertions().size() < 1) {
        throw new ValidationException("Assertion missing in AuthN response.");
    }
    if (authnResponse.getAssertions().size() > 1) {
        LOGGER.info("Received multiple assertions in AuthN response.  Only using the first assertion.");
    }
    if (authnResponse.getSignature() != null) {
        try {
            simpleSign.validateSignature(authnResponse.getSignature(), authnResponse.getDOM().getOwnerDocument());
        } catch (SimpleSign.SignatureException e) {
            throw new ValidationException("Invalid or untrusted signature.");
        }
    }
}
Also used : Response(org.opensaml.saml.saml2.core.Response) SimpleSign(ddf.security.samlp.SimpleSign) ValidationException(ddf.security.samlp.ValidationException)

Example 62 with Request

use of org.opensaml.saml.saml2.ecp.Request in project ddf by codice.

the class IdpHandler method createEcpRelayState.

private String createEcpRelayState(HttpServletRequest request) throws WSSecurityException {
    RelayStateBuilder relayStateBuilder = new RelayStateBuilder();
    RelayState relayState = relayStateBuilder.buildObject();
    relayState.setSOAP11Actor(HTTP_SCHEMAS_XMLSOAP_ORG_SOAP_ACTOR_NEXT);
    relayState.setSOAP11MustUnderstand(true);
    relayState.setValue(createRelayState(request));
    return convertXmlObjectToString(relayState);
}
Also used : RelayState(org.opensaml.saml.saml2.ecp.RelayState) RelayStateBuilder(org.opensaml.saml.saml2.ecp.impl.RelayStateBuilder)

Example 63 with Request

use of org.opensaml.saml.saml2.ecp.Request in project ddf by codice.

the class LoginFilter method handleAuthenticationToken.

private Subject handleAuthenticationToken(HttpServletRequest httpRequest, SAMLAuthenticationToken token) throws ServletException {
    Subject subject;
    try {
        LOGGER.debug("Validating received SAML assertion.");
        boolean wasReference = false;
        boolean firstLogin = true;
        if (token.isReference()) {
            wasReference = true;
            LOGGER.trace("Converting SAML reference to assertion");
            Object sessionToken = httpRequest.getSession(false).getAttribute(SecurityConstants.SAML_ASSERTION);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Http Session assertion - class: {}  loader: {}", sessionToken.getClass().getName(), sessionToken.getClass().getClassLoader());
                LOGGER.trace("SecurityToken class: {}  loader: {}", SecurityToken.class.getName(), SecurityToken.class.getClassLoader());
            }
            SecurityToken savedToken = null;
            try {
                savedToken = ((SecurityTokenHolder) sessionToken).getSecurityToken(token.getRealm());
            } catch (ClassCastException e) {
                httpRequest.getSession(false).invalidate();
            }
            if (savedToken != null) {
                firstLogin = false;
                token.replaceReferenece(savedToken);
            }
            if (token.isReference()) {
                String msg = "Missing or invalid SAML assertion for provided reference.";
                LOGGER.debug(msg);
                throw new InvalidSAMLReceivedException(msg);
            }
        }
        SAMLAuthenticationToken newToken = renewSecurityToken(httpRequest.getSession(false), token);
        SecurityToken securityToken;
        if (newToken != null) {
            firstLogin = false;
            securityToken = (SecurityToken) newToken.getCredentials();
        } else {
            securityToken = (SecurityToken) token.getCredentials();
        }
        if (!wasReference) {
            // wrap the token
            SamlAssertionWrapper assertion = new SamlAssertionWrapper(securityToken.getToken());
            // get the crypto junk
            Crypto crypto = getSignatureCrypto();
            Response samlResponse = createSamlResponse(httpRequest.getRequestURI(), assertion.getIssuerString(), createStatus(SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null));
            BUILDER.get().reset();
            Document doc = BUILDER.get().newDocument();
            Element policyElement = OpenSAMLUtil.toDom(samlResponse, doc);
            doc.appendChild(policyElement);
            Credential credential = new Credential();
            credential.setSamlAssertion(assertion);
            RequestData requestData = new RequestData();
            requestData.setSigVerCrypto(crypto);
            WSSConfig wssConfig = WSSConfig.getNewInstance();
            requestData.setWssConfig(wssConfig);
            X509Certificate[] x509Certs = (X509Certificate[]) httpRequest.getAttribute("javax.servlet.request.X509Certificate");
            requestData.setTlsCerts(x509Certs);
            validateHolderOfKeyConfirmation(assertion, x509Certs);
            if (assertion.isSigned()) {
                // Verify the signature
                WSSSAMLKeyInfoProcessor wsssamlKeyInfoProcessor = new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument()));
                assertion.verifySignature(wsssamlKeyInfoProcessor, crypto);
                assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument())), requestData.getSigVerCrypto(), requestData.getCallbackHandler());
            }
            // Validate the Assertion & verify trust in the signature
            assertionValidator.validate(credential, requestData);
        }
        // if it is all good, then we'll create our subject
        subject = securityManager.getSubject(securityToken);
        if (firstLogin) {
            boolean hasSecurityAuditRole = Arrays.stream(System.getProperty("security.audit.roles").split(",")).filter(subject::hasRole).findFirst().isPresent();
            if (hasSecurityAuditRole) {
                SecurityLogger.audit("Subject has logged in with admin privileges", subject);
            }
        }
        if (!wasReference && firstLogin) {
            addSamlToSession(httpRequest, token.getRealm(), securityToken);
        }
    } catch (SecurityServiceException e) {
        LOGGER.debug("Unable to get subject from SAML request.", e);
        throw new ServletException(e);
    } catch (WSSecurityException e) {
        LOGGER.debug("Unable to read/validate security token from request.", e);
        throw new ServletException(e);
    }
    return subject;
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) SecurityServiceException(ddf.security.service.SecurityServiceException) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException) Document(org.w3c.dom.Document) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject) X509Certificate(java.security.cert.X509Certificate) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Response(org.opensaml.saml.saml2.core.Response) ServletResponse(javax.servlet.ServletResponse) ServletException(javax.servlet.ServletException) Crypto(org.apache.wss4j.common.crypto.Crypto) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Example 64 with Request

use of org.opensaml.saml.saml2.ecp.Request in project ddf by codice.

the class AttributeQueryClient method retrieveResponse.

/**
     * Retrieves the response and returns its SAML Assertion.
     *
     * @param requestDocument of the request.
     * @return Assertion of the response or null if the response is empty.
     * @throws AttributeQueryException
     */
private Assertion retrieveResponse(Document requestDocument) throws AttributeQueryException {
    Assertion assertion = null;
    try {
        Document responseDocument = sendRequest(requestDocument);
        if (responseDocument == null) {
            return null;
        }
        // Print Response
        if (LOGGER.isTraceEnabled()) {
            printXML("SAML Response:\n {}", responseDocument);
        }
        // Extract Response from Soap message.
        NodeList elementsByTagNameNS = responseDocument.getElementsByTagNameNS(SAML2_PROTOCOL, "Response");
        if (elementsByTagNameNS == null) {
            throw new AttributeQueryException("Unable to find SAML Response.");
        }
        Node responseNode = elementsByTagNameNS.item(0);
        Element responseElement = (Element) responseNode;
        Unmarshaller unmarshaller = XMLObjectProviderRegistrySupport.getUnmarshallerFactory().getUnmarshaller(responseElement);
        Response response = (Response) unmarshaller.unmarshall(responseElement);
        LOGGER.debug("Successfully marshalled Element to SAML Response.");
        if (response.getStatus().getStatusCode().getValue().equals(SAML2_SUCCESS)) {
            LOGGER.debug("Successful response, retrieved attributes.");
            // Should only have one assertion.
            assertion = response.getAssertions().get(0);
        } else {
            reportError(response.getStatus());
        }
        return assertion;
    } catch (UnmarshallingException e) {
        throw new AttributeQueryException("Unable to marshall Element to SAML Response.", e);
    }
}
Also used : Response(org.opensaml.saml.saml2.core.Response) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Assertion(org.opensaml.saml.saml2.core.Assertion) Document(org.w3c.dom.Document) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException)

Example 65 with Request

use of org.opensaml.saml.saml2.ecp.Request in project cas by apereo.

the class SamlIdPUtils method getAssertionConsumerServiceFor.

/**
 * Gets assertion consumer service for.
 *
 * @param authnRequest    the authn request
 * @param servicesManager the services manager
 * @param resolver        the resolver
 * @return the assertion consumer service for
 */
public static AssertionConsumerService getAssertionConsumerServiceFor(final AuthnRequest authnRequest, final ServicesManager servicesManager, final SamlRegisteredServiceCachingMetadataResolver resolver) {
    try {
        final AssertionConsumerService acs = new AssertionConsumerServiceBuilder().buildObject();
        if (authnRequest.getAssertionConsumerServiceIndex() != null) {
            final String issuer = getIssuerFromSamlRequest(authnRequest);
            final MetadataResolver samlResolver = getMetadataResolverForAllSamlServices(servicesManager, issuer, resolver);
            final CriteriaSet criteriaSet = new CriteriaSet();
            criteriaSet.add(new EntityIdCriterion(issuer));
            criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
            criteriaSet.add(new BindingCriterion(CollectionUtils.wrap(SAMLConstants.SAML2_POST_BINDING_URI)));
            final Iterable<EntityDescriptor> it = samlResolver.resolve(criteriaSet);
            it.forEach(entityDescriptor -> {
                final SPSSODescriptor spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS);
                final List<AssertionConsumerService> acsEndpoints = spssoDescriptor.getAssertionConsumerServices();
                if (acsEndpoints.isEmpty()) {
                    throw new IllegalArgumentException("Metadata resolved for entity id " + issuer + " has no defined ACS endpoints");
                }
                final int acsIndex = authnRequest.getAssertionConsumerServiceIndex();
                if (acsIndex + 1 > acsEndpoints.size()) {
                    throw new IllegalArgumentException("AssertionConsumerService index specified in the request " + acsIndex + " is invalid " + "since the total endpoints available to " + issuer + " is " + acsEndpoints.size());
                }
                final AssertionConsumerService foundAcs = acsEndpoints.get(acsIndex);
                acs.setBinding(foundAcs.getBinding());
                acs.setLocation(foundAcs.getLocation());
                acs.setResponseLocation(foundAcs.getResponseLocation());
                acs.setIndex(acsIndex);
            });
        } else {
            acs.setBinding(authnRequest.getProtocolBinding());
            acs.setLocation(authnRequest.getAssertionConsumerServiceURL());
            acs.setResponseLocation(authnRequest.getAssertionConsumerServiceURL());
            acs.setIndex(0);
            acs.setIsDefault(Boolean.TRUE);
        }
        LOGGER.debug("Resolved AssertionConsumerService from the request is [{}]", acs);
        if (StringUtils.isBlank(acs.getBinding())) {
            throw new SamlException("AssertionConsumerService has no protocol binding defined");
        }
        if (StringUtils.isBlank(acs.getLocation()) && StringUtils.isBlank(acs.getResponseLocation())) {
            throw new SamlException("AssertionConsumerService has no location or response location defined");
        }
        return acs;
    } catch (final Exception e) {
        throw new IllegalArgumentException(new SamlException(e.getMessage(), e));
    }
}
Also used : AssertionConsumerServiceBuilder(org.opensaml.saml.saml2.metadata.impl.AssertionConsumerServiceBuilder) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) BindingCriterion(org.opensaml.saml.criterion.BindingCriterion) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) Endpoint(org.opensaml.saml.saml2.metadata.Endpoint) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService)

Aggregations

AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)24 IOException (java.io.IOException)13 LogoutResponse (org.opensaml.saml.saml2.core.LogoutResponse)13 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)12 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)11 Test (org.junit.Test)10 ValidationException (ddf.security.samlp.ValidationException)9 Response (javax.ws.rs.core.Response)9 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)9 Assertion (org.jasig.cas.client.validation.Assertion)9 MessageContext (org.opensaml.messaging.context.MessageContext)9 Assertion (org.opensaml.saml.saml2.core.Assertion)9 Document (org.w3c.dom.Document)9 XMLStreamException (javax.xml.stream.XMLStreamException)8 LogoutRequest (org.opensaml.saml.saml2.core.LogoutRequest)8 NameID (org.opensaml.saml.saml2.core.NameID)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 SimpleSign (ddf.security.samlp.SimpleSign)5 ZonedDateTime (java.time.ZonedDateTime)5 Path (javax.ws.rs.Path)5