Search in sources :

Example 1 with X509Security

use of org.apache.wss4j.common.token.X509Security in project ddf by codice.

the class PKITokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     *
     * @param tokenParameters
     * @return TokenValidatorResponse
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.trace("Validating PKI 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);
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    PKIAuthenticationToken pkiToken = getPKITokenFromTarget(validateTarget);
    if (pkiToken == null) {
        return response;
    }
    BinarySecurityTokenType binarySecurityType = pkiToken.createBinarySecurityTokenType(pkiToken.getCredentials());
    // Test the encoding type
    String encodingType = binarySecurityType.getEncodingType();
    if (!PKIAuthenticationToken.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 binarySecurity = new X509Security(doc);
    binarySecurity.setEncodingType(encodingType);
    binarySecurity.setValueType(binarySecurityType.getValueType());
    String data = binarySecurityType.getValue();
    Node textNode = doc.createTextNode(data);
    binarySecurity.getElement().appendChild(textNode);
    //
    try {
        Credential credential = new Credential();
        credential.setBinarySecurityToken(binarySecurity);
        if (merlin != null) {
            byte[] token = binarySecurity.getToken();
            if (token != null) {
                X509Certificate[] certificates = merlin.getCertificatesFromBytes(token);
                if (certificates != null) {
                    if (doPathValidation) {
                        credential.setCertificates(certificates);
                    } else {
                        credential.setCertificates(new X509Certificate[] { certificates[0] });
                    }
                }
            } 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.setPrincipal(subjectX500Principal);
        validateTarget.setState(STATE.VALID);
    } catch (WSSecurityException ex) {
        LOGGER.info("Unable to validate credentials.", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Credential(org.apache.wss4j.dom.validate.Credential) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) Node(org.w3c.dom.Node) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) PKIAuthenticationToken(org.codice.ddf.security.handler.api.PKIAuthenticationToken) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) RequestData(org.apache.wss4j.dom.handler.RequestData) X500Principal(javax.security.auth.x500.X500Principal) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) X509Security(org.apache.wss4j.common.token.X509Security)

Example 2 with X509Security

use of org.apache.wss4j.common.token.X509Security in project ddf by codice.

the class StsIssueTest method testBearerPkiTokenSaml2.

/**
     * Test the User PKI Token
     */
public void testBearerPkiTokenSaml2(StsPortTypes portType) throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = StsIssueTest.class.getResource("/cxf-client.xml");
    Bus bus = bf.createBus(busFile.toString());
    SpringBusFactory.setDefaultBus(bus);
    SpringBusFactory.setThreadDefaultBus(bus);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    // Build the Claims object
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement(WST, CLAIMS, STSUtils.WST_NS_05_12);
    writer.writeNamespace(WST, STSUtils.WST_NS_05_12);
    writer.writeNamespace(IC, IDENTITY_URI);
    writer.writeAttribute(DIALECT, IDENTITY_URI);
    // Add the Role claim
    writer.writeStartElement(IC, CLAIM_TYPE, IDENTITY_URI);
    writer.writeAttribute("URI", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");
    writer.writeEndElement();
    Element claims = writer.getDocument().getDocumentElement();
    // Alerternatively we can use a certificate to request a SAML
    X509Security oboToken = new X509Security(doc);
    Crypto crypto = CryptoFactory.getInstance("clientKeystore.properties");
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("client");
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    if (null != certs) {
        oboToken.setX509Certificate(certs[0]);
        // Get a token
        SecurityToken token = requestSecurityToken(SAML2_TOKEN_TYPE, BEARER_KEYTYPE, oboToken.getElement(), bus, StsAddresses.valueOf(portType.toString()).toString(), WsdlLocations.valueOf(portType.toString()).toString(), EndPoints.valueOf(portType.toString()).toString(), claims);
        if (token != null) {
            validateSecurityToken(token);
        }
    }
    bus.shutdown(true);
}
Also used : Bus(org.apache.cxf.Bus) W3CDOMStreamWriter(org.apache.cxf.staxutils.W3CDOMStreamWriter) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) CryptoType(org.apache.wss4j.common.crypto.CryptoType) Document(org.w3c.dom.Document) URL(java.net.URL) X509Certificate(java.security.cert.X509Certificate) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Crypto(org.apache.wss4j.common.crypto.Crypto) SpringBusFactory(org.apache.cxf.bus.spring.SpringBusFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) X509Security(org.apache.wss4j.common.token.X509Security)

Example 3 with X509Security

use of org.apache.wss4j.common.token.X509Security in project ddf by codice.

the class WssPKIHandler method extractAuthenticationInfo.

@Override
protected BaseAuthenticationToken extractAuthenticationInfo(String realm, X509Certificate[] certs) {
    PKIAuthenticationToken pkiToken = tokenFactory.getTokenFromCerts(certs, realm);
    BinarySecurityTokenType binarySecurityType = pkiToken.createBinarySecurityTokenType(pkiToken.getCredentials());
    //
    // Turn the received JAXB object into a DOM element
    //
    Document doc = DOMUtils.createDocument();
    BinarySecurity binarySecurity = new X509Security(doc);
    binarySecurity.setEncodingType(binarySecurityType.getEncodingType());
    binarySecurity.setValueType(X509Security.X509_V3_TYPE);
    String data = binarySecurityType.getValue();
    Node textNode = doc.createTextNode(data);
    binarySecurity.getElement().appendChild(textNode);
    BaseAuthenticationToken baseAuthenticationToken = new BaseAuthenticationToken(null, "", binarySecurity.toString());
    baseAuthenticationToken.setUseWssSts(true);
    return baseAuthenticationToken;
}
Also used : PKIAuthenticationToken(org.codice.ddf.security.handler.api.PKIAuthenticationToken) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) Node(org.w3c.dom.Node) BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) Document(org.w3c.dom.Document) X509Security(org.apache.wss4j.common.token.X509Security)

Example 4 with X509Security

use of org.apache.wss4j.common.token.X509Security 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)

Aggregations

X509Security (org.apache.wss4j.common.token.X509Security)4 Document (org.w3c.dom.Document)4 X509Certificate (java.security.cert.X509Certificate)3 BinarySecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType)3 Crypto (org.apache.wss4j.common.crypto.Crypto)3 BinarySecurity (org.apache.wss4j.common.token.BinarySecurity)3 Node (org.w3c.dom.Node)3 IOException (java.io.IOException)2 CallbackHandler (javax.security.auth.callback.CallbackHandler)2 X500Principal (javax.security.auth.x500.X500Principal)2 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)2 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)2 TokenValidatorResponse (org.apache.cxf.sts.token.validator.TokenValidatorResponse)2 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)2 RequestData (org.apache.wss4j.dom.handler.RequestData)2 Credential (org.apache.wss4j.dom.validate.Credential)2 PKIAuthenticationToken (org.codice.ddf.security.handler.api.PKIAuthenticationToken)2 Element (org.w3c.dom.Element)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 URL (java.net.URL)1