Search in sources :

Example 91 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.

the class SamlCallbackHandler method handle.

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    Message m = PhaseInterceptorChain.getCurrentMessage();
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            if (saml2) {
                callback.setSamlVersion(Version.SAML_20);
            } else {
                callback.setSamlVersion(Version.SAML_11);
            }
            callback.setIssuer(issuer);
            String subject = m != null ? (String) m.getContextualProperty("saml.subject.name") : null;
            if (subject == null) {
                subject = subjectName;
            }
            String subjectQualifier = "www.mock-sts.com";
            SubjectBean subjectBean = new SubjectBean(subject, subjectQualifier, confirmationMethod);
            callback.setSubject(subjectBean);
            ConditionsBean conditions = new ConditionsBean();
            AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
            audienceRestriction.setAudienceURIs(Collections.singletonList(audience));
            conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
            callback.setConditions(conditions);
            AuthDecisionStatementBean authDecBean = new AuthDecisionStatementBean();
            authDecBean.setDecision(Decision.INDETERMINATE);
            authDecBean.setResource("https://sp.example.com/SAML2");
            authDecBean.setSubject(subjectBean);
            ActionBean actionBean = new ActionBean();
            actionBean.setContents("Read");
            authDecBean.setActions(Collections.singletonList(actionBean));
            callback.setAuthDecisionStatementData(Collections.singletonList(authDecBean));
            AuthenticationStatementBean authBean = new AuthenticationStatementBean();
            authBean.setSubject(subjectBean);
            authBean.setAuthenticationInstant(new DateTime());
            authBean.setSessionIndex("123456");
            authBean.setSubject(subjectBean);
            // AuthnContextClassRef is not set
            authBean.setAuthenticationMethod("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
            callback.setAuthenticationStatementData(Collections.singletonList(authBean));
            AttributeStatementBean attrBean = new AttributeStatementBean();
            attrBean.setSubject(subjectBean);
            List<String> roles = m != null ? CastUtils.<String>cast((List<?>) m.getContextualProperty("saml.roles")) : null;
            if (roles == null) {
                roles = Collections.singletonList("user");
            }
            List<AttributeBean> claims = new ArrayList<>();
            AttributeBean roleClaim = new AttributeBean();
            roleClaim.setSimpleName("subject-role");
            roleClaim.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
            roleClaim.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
            roleClaim.setAttributeValues(new ArrayList<>(roles));
            claims.add(roleClaim);
            List<String> authMethods = m != null ? CastUtils.<String>cast((List<?>) m.getContextualProperty("saml.auth")) : null;
            if (authMethods == null) {
                authMethods = Collections.singletonList("password");
            }
            AttributeBean authClaim = new AttributeBean();
            authClaim.setSimpleName("http://claims/authentication");
            authClaim.setQualifiedName("http://claims/authentication");
            authClaim.setNameFormat("http://claims/authentication-format");
            authClaim.setAttributeValues(new ArrayList<>(authMethods));
            claims.add(authClaim);
            attrBean.setSamlAttributes(claims);
            callback.setAttributeStatementData(Collections.singletonList(attrBean));
            if (signAssertion) {
                try {
                    Crypto crypto = CryptoFactory.getInstance(cryptoPropertiesFile);
                    callback.setIssuerCrypto(crypto);
                    callback.setIssuerKeyName(issuerKeyName);
                    callback.setIssuerKeyPassword(issuerKeyPassword);
                    callback.setSignAssertion(true);
                } catch (WSSecurityException e) {
                    throw new IOException(e);
                }
            }
        }
    }
}
Also used : AttributeStatementBean(org.apache.wss4j.common.saml.bean.AttributeStatementBean) AudienceRestrictionBean(org.apache.wss4j.common.saml.bean.AudienceRestrictionBean) Message(org.apache.cxf.message.Message) AuthenticationStatementBean(org.apache.wss4j.common.saml.bean.AuthenticationStatementBean) ConditionsBean(org.apache.wss4j.common.saml.bean.ConditionsBean) ArrayList(java.util.ArrayList) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) ActionBean(org.apache.wss4j.common.saml.bean.ActionBean) DateTime(org.joda.time.DateTime) SubjectBean(org.apache.wss4j.common.saml.bean.SubjectBean) Crypto(org.apache.wss4j.common.crypto.Crypto) AuthDecisionStatementBean(org.apache.wss4j.common.saml.bean.AuthDecisionStatementBean) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) ArrayList(java.util.ArrayList) List(java.util.List) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean)

Example 92 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project ddf by codice.

the class AssertionConsumerService method findCertificate.

private X509Certificate findCertificate(String alias, Crypto crypto) throws WSSecurityException {
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(alias);
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    if (certs == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.SECURITY_ERROR, "Unable to retrieve certificate");
    }
    return certs[0];
}
Also used : WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) CryptoType(org.apache.wss4j.common.crypto.CryptoType) X509Certificate(java.security.cert.X509Certificate)

Example 93 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project ddf by codice.

the class IdpHandler method serializeAndSign.

private String serializeAndSign(boolean isPost, boolean wantSigned, AuthnRequest authnRequest) throws AuthenticationFailureException {
    try {
        if (isPost && wantSigned) {
            simpleSign.signSamlObject(authnRequest);
        }
        Document doc = DOMUtils.createDocument();
        doc.appendChild(doc.createElement("root"));
        Element requestElement = OpenSAMLUtil.toDom(authnRequest, doc);
        String requestMessage = DOM2Writer.nodeToString(requestElement);
        LOGGER.trace(requestMessage);
        return requestMessage;
    } catch (WSSecurityException e) {
        LOGGER.info(UNABLE_TO_ENCODE_SAML_AUTHN_REQUEST, e);
        throw new AuthenticationFailureException(UNABLE_TO_ENCODE_SAML_AUTHN_REQUEST);
    } catch (SignatureException e) {
        LOGGER.info(UNABLE_TO_SIGN_SAML_AUTHN_REQUEST, e);
        throw new AuthenticationFailureException(UNABLE_TO_SIGN_SAML_AUTHN_REQUEST);
    }
}
Also used : Element(org.w3c.dom.Element) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException) SignatureException(ddf.security.samlp.SignatureException) Document(org.w3c.dom.Document)

Example 94 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project ddf by codice.

the class LogoutRequestService method soapLogoutRequest.

@POST
@Consumes({ "text/xml", "application/soap+xml" })
public Response soapLogoutRequest(InputStream body, @Context HttpServletRequest request) {
    XMLObject xmlObject;
    try {
        String bodyString = IOUtils.toString(body, StandardCharsets.UTF_8);
        SOAPPart soapMessage = SamlProtocol.parseSoapMessage(bodyString);
        xmlObject = SamlProtocol.getXmlObjectFromNode(soapMessage.getEnvelope().getBody().getFirstChild());
        if (!(xmlObject instanceof LogoutRequest)) {
            LOGGER.info(UNABLE_TO_PARSE_LOGOUT_REQUEST);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Type of object is {}", xmlObject == null ? "null" : xmlObject.getSchemaType());
            }
            return Response.serverError().build();
        }
    } catch (SOAPException | XMLStreamException | IOException | WSSecurityException e) {
        LOGGER.debug("Error parsing input", e);
        return Response.serverError().build();
    }
    LogoutRequest logoutRequest = (LogoutRequest) xmlObject;
    if (logoutMessage == null) {
        LOGGER.info("Logout message not available yet");
        return Response.serverError().build();
    }
    // Pre-build response with success status
    LogoutWrapper<LogoutResponse> logoutResponse = logoutMessage.buildLogoutResponse(logoutRequest.getIssuer().getValue(), StatusCode.SUCCESS, logoutRequest.getID());
    try {
        if (!validateSignature(logoutRequest)) {
            return getSamlpSoapLogoutResponse(logoutResponse, StatusCode.AUTHN_FAILED, null);
        }
        new SamlValidator.Builder(simpleSign).buildAndValidate(this.request.getRequestURL().toString(), SamlProtocol.Binding.HTTP_POST, logoutRequest);
        httpSessionInvalidator.invalidateSession(logoutRequest.getNameID().getValue(), this::extractSubject);
        securityLogger.audit("Subject logged out by backchannel request: {}", logoutRequest.getNameID().getValue());
        return getSamlpSoapLogoutResponse(logoutResponse);
    } catch (ValidationException e) {
        LOGGER.info(UNABLE_TO_VALIDATE_LOGOUT_REQUEST, e);
        return getSamlpSoapLogoutResponse(logoutResponse, StatusCode.RESPONDER, e.getMessage());
    }
}
Also used : ValidationException(ddf.security.samlp.impl.ValidationException) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) SamlValidator(ddf.security.samlp.impl.SamlValidator) SOAPPart(javax.xml.soap.SOAPPart) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 95 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project ddf by codice.

the class LogoutMessageImpl method extractXmlObject.

@Override
public LogoutWrapper<SignableSAMLObject> extractXmlObject(String samlLogoutResponse) throws LogoutSecurityException, XMLStreamException {
    try {
        Document responseDoc = StaxUtils.read(new ByteArrayInputStream(samlLogoutResponse.getBytes(StandardCharsets.UTF_8)));
        XMLObject xmlObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
        if (xmlObject instanceof SignableSAMLObject) {
            return new LogoutWrapperImpl<>((SignableSAMLObject) xmlObject);
        }
        return null;
    } catch (WSSecurityException e) {
        throw new LogoutSecurityException(e);
    }
}
Also used : SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLObject(org.opensaml.core.xml.XMLObject) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) LogoutSecurityException(ddf.security.samlp.LogoutSecurityException)

Aggregations

WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)241 Element (org.w3c.dom.Element)72 Document (org.w3c.dom.Document)53 IOException (java.io.IOException)51 Crypto (org.apache.wss4j.common.crypto.Crypto)50 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)39 Credential (org.apache.wss4j.dom.validate.Credential)37 RequestData (org.apache.wss4j.dom.handler.RequestData)36 X509Certificate (java.security.cert.X509Certificate)31 Response (org.opensaml.saml.saml2.core.Response)31 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)25 DateTime (org.joda.time.DateTime)22 XMLObject (org.opensaml.core.xml.XMLObject)22 XMLStreamException (javax.xml.stream.XMLStreamException)21 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)21 Fault (org.apache.cxf.interceptor.Fault)20 SOAPException (javax.xml.soap.SOAPException)19 CallbackHandler (javax.security.auth.callback.CallbackHandler)18 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)17 InputStream (java.io.InputStream)16