Search in sources :

Example 26 with WSSecurityException

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

the class SimpleSign method getSignatureCertificates.

private X509Certificate[] getSignatureCertificates() throws SignatureException {
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(crypto.getSignatureAlias());
    X509Certificate[] issuerCerts;
    try {
        issuerCerts = crypto.getSignatureCrypto().getX509Certificates(cryptoType);
    } catch (WSSecurityException e) {
        throw new SignatureException(e);
    }
    if (issuerCerts == null) {
        throw new SignatureException("No certs were found to sign the request using name: " + crypto.getSignatureAlias());
    }
    return issuerCerts;
}
Also used : WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) CryptoType(org.apache.wss4j.common.crypto.CryptoType) X509Certificate(java.security.cert.X509Certificate)

Example 27 with WSSecurityException

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

the class IdpEndpoint method processLogin.

@GET
@Path("/login/sso")
public Response processLogin(@QueryParam(SAML_REQ) String samlRequest, @QueryParam(RELAY_STATE) String relayState, @QueryParam(AUTH_METHOD) String authMethod, @QueryParam(SSOConstants.SIG_ALG) String signatureAlgorithm, @QueryParam(SSOConstants.SIGNATURE) String signature, @QueryParam(ORIGINAL_BINDING) String originalBinding, @Context HttpServletRequest request) {
    LOGGER.debug("Processing login request: [ authMethod {} ], [ sigAlg {} ], [ relayState {} ]", authMethod, signatureAlgorithm, relayState);
    try {
        Binding binding;
        String template;
        if (!request.isSecure()) {
            throw new IllegalArgumentException("Authn Request must use TLS.");
        }
        //the authn request is always encoded as if it came in via redirect when coming from the web app
        Binding redirectBinding = new RedirectBinding(systemCrypto, serviceProviders);
        AuthnRequest authnRequest = redirectBinding.decoder().decodeRequest(samlRequest);
        String assertionConsumerServiceBinding = ResponseCreator.getAssertionConsumerServiceBinding(authnRequest, serviceProviders);
        if (HTTP_POST_BINDING.equals(originalBinding)) {
            binding = new PostBinding(systemCrypto, serviceProviders);
            template = submitForm;
        } else if (HTTP_REDIRECT_BINDING.equals(originalBinding)) {
            binding = redirectBinding;
            template = redirectPage;
        } else {
            throw new IdpException(new UnsupportedOperationException("Must use HTTP POST or Redirect bindings."));
        }
        binding.validator().validateAuthnRequest(authnRequest, samlRequest, relayState, signatureAlgorithm, signature, strictSignature);
        if (HTTP_POST_BINDING.equals(assertionConsumerServiceBinding)) {
            if (!(binding instanceof PostBinding)) {
                binding = new PostBinding(systemCrypto, serviceProviders);
            }
        } else if (HTTP_REDIRECT_BINDING.equals(assertionConsumerServiceBinding)) {
            if (!(binding instanceof RedirectBinding)) {
                binding = new RedirectBinding(systemCrypto, serviceProviders);
            }
        }
        org.opensaml.saml.saml2.core.Response encodedSaml = handleLogin(authnRequest, authMethod, request, null, false, false);
        LOGGER.debug("Returning SAML Response for relayState: {}" + relayState);
        NewCookie newCookie = createCookie(request, encodedSaml);
        Response response = binding.creator().getSamlpResponse(relayState, authnRequest, encodedSaml, newCookie, template);
        if (newCookie != null) {
            cookieCache.addActiveSp(newCookie.getValue(), authnRequest.getIssuer().getValue());
            logAddedSp(authnRequest);
        }
        return response;
    } catch (SecurityServiceException e) {
        LOGGER.info("Unable to retrieve subject for user.", e);
        return Response.status(Response.Status.UNAUTHORIZED).build();
    } catch (WSSecurityException e) {
        LOGGER.info("Unable to encode SAMLP response.", e);
    } catch (SimpleSign.SignatureException e) {
        LOGGER.info("Unable to sign SAML response.", e);
    } catch (IllegalArgumentException e) {
        LOGGER.info(e.getMessage(), e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (ValidationException e) {
        LOGGER.info("AuthnRequest schema validation failed.", e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (IOException e) {
        LOGGER.info("Unable to create SAML Response.", e);
    } catch (IdpException e) {
        LOGGER.info(e.getMessage(), e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
Also used : RedirectBinding(org.codice.ddf.security.idp.binding.redirect.RedirectBinding) SoapBinding(org.codice.ddf.security.idp.binding.soap.SoapBinding) Binding(org.codice.ddf.security.idp.binding.api.Binding) PostBinding(org.codice.ddf.security.idp.binding.post.PostBinding) RedirectBinding(org.codice.ddf.security.idp.binding.redirect.RedirectBinding) SecurityServiceException(ddf.security.service.SecurityServiceException) ValidationException(ddf.security.samlp.ValidationException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) Response(javax.ws.rs.core.Response) SimpleSign(ddf.security.samlp.SimpleSign) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) PostBinding(org.codice.ddf.security.idp.binding.post.PostBinding) NewCookie(javax.ws.rs.core.NewCookie) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 28 with WSSecurityException

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

the class IdpEndpoint method showLoginPage.

private Response showLoginPage(String samlRequest, String relayState, String signatureAlgorithm, String signature, HttpServletRequest request, Binding binding, String template, String originalBinding) throws WSSecurityException {
    String responseStr;
    AuthnRequest authnRequest = null;
    try {
        Map<String, Object> responseMap = new HashMap<>();
        binding.validator().validateRelayState(relayState);
        authnRequest = binding.decoder().decodeRequest(samlRequest);
        authnRequest.getIssueInstant();
        binding.validator().validateAuthnRequest(authnRequest, samlRequest, relayState, signatureAlgorithm, signature, strictSignature);
        if (!request.isSecure()) {
            throw new IllegalArgumentException("Authn Request must use TLS.");
        }
        X509Certificate[] certs = (X509Certificate[]) request.getAttribute(CERTIFICATES_ATTR);
        boolean hasCerts = (certs != null && certs.length > 0);
        boolean hasCookie = hasValidCookie(request, authnRequest.isForceAuthn());
        if ((authnRequest.isPassive() && hasCerts) || hasCookie) {
            LOGGER.debug("Received Passive & PKI AuthnRequest.");
            org.opensaml.saml.saml2.core.Response samlpResponse;
            try {
                samlpResponse = handleLogin(authnRequest, PKI, request, null, authnRequest.isPassive(), hasCookie);
                LOGGER.debug("Passive & PKI AuthnRequest logged in successfully.");
            } catch (SecurityServiceException e) {
                LOGGER.debug(e.getMessage(), e);
                return getErrorResponse(relayState, authnRequest, StatusCode.AUTHN_FAILED, binding);
            } catch (WSSecurityException e) {
                LOGGER.debug(e.getMessage(), e);
                return getErrorResponse(relayState, authnRequest, StatusCode.REQUEST_DENIED, binding);
            } catch (SimpleSign.SignatureException | ConstraintViolationException e) {
                LOGGER.debug(e.getMessage(), e);
                return getErrorResponse(relayState, authnRequest, StatusCode.REQUEST_UNSUPPORTED, binding);
            }
            LOGGER.debug("Returning Passive & PKI SAML Response.");
            NewCookie cookie = null;
            if (hasCookie) {
                cookieCache.addActiveSp(getCookie(request).getValue(), authnRequest.getIssuer().getValue());
            } else {
                cookie = createCookie(request, samlpResponse);
                if (cookie != null) {
                    cookieCache.addActiveSp(cookie.getValue(), authnRequest.getIssuer().getValue());
                }
            }
            logAddedSp(authnRequest);
            return binding.creator().getSamlpResponse(relayState, authnRequest, samlpResponse, cookie, template);
        } else {
            LOGGER.debug("Building the JSON map to embed in the index.html page for login.");
            Document doc = DOMUtils.createDocument();
            doc.appendChild(doc.createElement("root"));
            String authn = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(authnRequest, doc, false));
            String encodedAuthn = RestSecurity.deflateAndBase64Encode(authn);
            responseMap.put(PKI, hasCerts);
            responseMap.put(GUEST, guestAccess);
            responseMap.put(SAML_REQ, encodedAuthn);
            responseMap.put(RELAY_STATE, relayState);
            String assertionConsumerServiceURL = ((ResponseCreatorImpl) binding.creator()).getAssertionConsumerServiceURL(authnRequest);
            responseMap.put(ACS_URL, assertionConsumerServiceURL);
            responseMap.put(SSOConstants.SIG_ALG, signatureAlgorithm);
            responseMap.put(SSOConstants.SIGNATURE, signature);
            responseMap.put(ORIGINAL_BINDING, originalBinding);
        }
        String json = Boon.toJson(responseMap);
        LOGGER.debug("Returning index.html page.");
        responseStr = indexHtml.replace(IDP_STATE_OBJ, json);
        return Response.ok(responseStr).build();
    } catch (IllegalArgumentException e) {
        LOGGER.debug(e.getMessage(), e);
        if (authnRequest != null) {
            try {
                return getErrorResponse(relayState, authnRequest, StatusCode.REQUEST_UNSUPPORTED, binding);
            } catch (IOException | SimpleSign.SignatureException e1) {
                LOGGER.debug(e1.getMessage(), e1);
            }
        }
    } catch (UnsupportedOperationException e) {
        LOGGER.debug(e.getMessage(), e);
        if (authnRequest != null) {
            try {
                return getErrorResponse(relayState, authnRequest, StatusCode.UNSUPPORTED_BINDING, binding);
            } catch (IOException | SimpleSign.SignatureException e1) {
                LOGGER.debug(e1.getMessage(), e1);
            }
        }
    } catch (SimpleSign.SignatureException e) {
        LOGGER.debug("Unable to validate AuthRequest Signature", e);
    } catch (IOException e) {
        LOGGER.debug("Unable to decode AuthRequest", e);
    } catch (ValidationException e) {
        LOGGER.debug("AuthnRequest schema validation failed.", e);
    }
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) ValidationException(ddf.security.samlp.ValidationException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Document(org.w3c.dom.Document) SimpleSign(ddf.security.samlp.SimpleSign) ConstraintViolationException(net.shibboleth.utilities.java.support.logic.ConstraintViolationException) NewCookie(javax.ws.rs.core.NewCookie) ResponseCreatorImpl(org.codice.ddf.security.idp.binding.api.impl.ResponseCreatorImpl) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject)

Example 29 with WSSecurityException

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

the class X509PathTokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     *
     * @param tokenParameters
     * @return TokenValidatorResponse
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.trace("Validating X.509 Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    requestData.setWssConfig(WSSConfig.getNewInstance());
    requestData.setCallbackHandler(callbackHandler);
    requestData.setMsgContext(tokenParameters.getMessageContext());
    requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    BinarySecurity binarySecurity = null;
    BinarySecurityTokenType binarySecurityType = null;
    if (validateTarget.isBinarySecurityToken()) {
        binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
        // Test the encoding type
        String encodingType = binarySecurityType.getEncodingType();
        if (!BASE64_ENCODING.equals(encodingType)) {
            LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
            return response;
        }
        //
        // Turn the received JAXB object into a DOM element
        //
        Document doc = DOMUtils.createDocument();
        binarySecurity = new X509Security(doc);
        binarySecurity.setEncodingType(encodingType);
        binarySecurity.setValueType(binarySecurityType.getValueType());
        String data = binarySecurityType.getValue();
        Node textNode = doc.createTextNode(data);
        binarySecurity.getElement().appendChild(textNode);
    } else if (validateTarget.isDOMElement()) {
        try {
            Document doc = DOMUtils.createDocument();
            binarySecurity = new X509Security(doc);
            binarySecurity.setEncodingType(BASE64_ENCODING);
            X509Data x509Data = new X509Data((Element) validateTarget.getToken(), "");
            if (x509Data.containsCertificate()) {
                XMLX509Certificate xmlx509Certificate = x509Data.itemCertificate(0);
                if (xmlx509Certificate == null) {
                    throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN);
                }
                X509Certificate cert = xmlx509Certificate.getX509Certificate();
                ((X509Security) binarySecurity).setX509Certificate(cert);
            }
        } catch (WSSecurityException ex) {
            LOGGER.debug("Unable to set certificate", ex);
            return response;
        } catch (XMLSecurityException ex) {
            LOGGER.debug("Unable to get certificates", ex);
            return response;
        }
    } else {
        return response;
    }
    //
    try {
        Credential credential = new Credential();
        credential.setBinarySecurityToken(binarySecurity);
        if (merlin != null) {
            byte[] token = binarySecurity.getToken();
            if (token != null) {
                if (binarySecurityType != null) {
                    if (binarySecurityType.getValueType().equals(X509_PKI_PATH)) {
                        X509Certificate[] certificates = merlin.getCertificatesFromBytes(token);
                        if (certificates != null) {
                            credential.setCertificates(certificates);
                        }
                    } else {
                        X509Certificate singleCert = merlin.loadCertificate(new ByteArrayInputStream(token));
                        credential.setCertificates(new X509Certificate[] { singleCert });
                    }
                }
            } else {
                LOGGER.debug("Binary Security Token bytes were null.");
            }
        }
        Credential returnedCredential = validator.validate(credential, requestData);
        X500Principal subjectX500Principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
        response.setPrincipal(subjectX500Principal);
        if (response.getAdditionalProperties() == null) {
            response.setAdditionalProperties(new HashMap<>());
        }
        try {
            String emailAddress = SubjectUtils.getEmailAddress(subjectX500Principal);
            if (emailAddress != null) {
                response.getAdditionalProperties().put(SubjectUtils.EMAIL_ADDRESS_CLAIM_URI, emailAddress);
            }
            String country = SubjectUtils.getCountry(subjectX500Principal);
            if (country != null) {
                response.getAdditionalProperties().put(SubjectUtils.COUNTRY_CLAIM_URI, country);
            }
        } catch (Exception e) {
            LOGGER.debug("Unable to set email address or country from certificate.", e);
        }
        validateTarget.setState(STATE.VALID);
        validateTarget.setPrincipal(subjectX500Principal);
    } catch (WSSecurityException ex) {
        LOGGER.debug("Unable to validate credentials.", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) RequestData(org.apache.wss4j.dom.handler.RequestData) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) X509Security(org.apache.wss4j.common.token.X509Security) Credential(org.apache.wss4j.dom.validate.Credential) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) X509Certificate(java.security.cert.X509Certificate) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) ByteArrayInputStream(java.io.ByteArrayInputStream) X500Principal(javax.security.auth.x500.X500Principal) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse)

Example 30 with WSSecurityException

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

the class UPBSTValidator method getUsernameTokenFromTarget.

private UPAuthenticationToken getUsernameTokenFromTarget(ReceivedToken validateTarget) {
    Object token = validateTarget.getToken();
    if ((token instanceof BinarySecurityTokenType) && UPAuthenticationToken.UP_TOKEN_VALUE_TYPE.equals(((BinarySecurityTokenType) token).getValueType())) {
        String encodedCredential = ((BinarySecurityTokenType) token).getValue();
        LOGGER.debug("Encoded username/password credential: {}", encodedCredential);
        BaseAuthenticationToken base = null;
        try {
            base = UPAuthenticationToken.parse(encodedCredential, true);
            return new UPAuthenticationToken(base.getPrincipal().toString(), base.getCredentials().toString(), base.getRealm());
        } catch (WSSecurityException e) {
            LOGGER.info("Unable to parse {} from encodedToken.", UPAuthenticationToken.class.getSimpleName(), e);
            return null;
        }
    }
    return null;
}
Also used : BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) AttributedString(org.apache.cxf.ws.security.sts.provider.model.secext.AttributedString) PasswordString(org.apache.cxf.ws.security.sts.provider.model.secext.PasswordString)

Aggregations

WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)44 IOException (java.io.IOException)16 X509Certificate (java.security.cert.X509Certificate)13 RequestData (org.apache.wss4j.dom.handler.RequestData)13 Credential (org.apache.wss4j.dom.validate.Credential)12 Document (org.w3c.dom.Document)12 BinarySecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType)11 Crypto (org.apache.wss4j.common.crypto.Crypto)11 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)10 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)10 TokenValidatorResponse (org.apache.cxf.sts.token.validator.TokenValidatorResponse)10 XMLObject (org.opensaml.core.xml.XMLObject)7 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)7 Element (org.w3c.dom.Element)7 X500Principal (javax.security.auth.x500.X500Principal)6 XMLStreamException (javax.xml.stream.XMLStreamException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 CallbackHandler (javax.security.auth.callback.CallbackHandler)5 TokenValidatorParameters (org.apache.cxf.sts.token.validator.TokenValidatorParameters)5 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)5