Search in sources :

Example 76 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class TokenRequestCollectionOperation method requestCollection.

public RequestSecurityTokenResponseCollectionType requestCollection(RequestSecurityTokenCollectionType requestCollection, Principal principal, Map<String, Object> messageContext) {
    RequestSecurityTokenResponseCollectionType responseCollection = QNameConstants.WS_TRUST_FACTORY.createRequestSecurityTokenResponseCollectionType();
    String requestType = null;
    for (RequestSecurityTokenType request : requestCollection.getRequestSecurityToken()) {
        List<?> objectList = request.getAny();
        for (Object o : objectList) {
            if (o instanceof JAXBElement) {
                QName qname = ((JAXBElement<?>) o).getName();
                if (qname.equals(new QName(STSConstants.WST_NS_05_12, "RequestType"))) {
                    String val = ((JAXBElement<?>) o).getValue().toString();
                    // All batch requests must have the same RequestType
                    if (val == null || (requestType != null && !requestType.equals(val))) {
                        LOG.log(Level.WARNING, "All RequestSecurityTokenCollection elements do not share the same " + "RequestType");
                        throw new STSException("Error in requesting a token", STSException.REQUEST_FAILED);
                    }
                    requestType = val;
                }
            }
        }
        RequestSecurityTokenResponseType response = handleRequest(request, principal, messageContext, requestType);
        responseCollection.getRequestSecurityTokenResponse().add(response);
    }
    return responseCollection;
}
Also used : QName(javax.xml.namespace.QName) RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) STSException(org.apache.cxf.ws.security.sts.provider.STSException) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) JAXBElement(javax.xml.bind.JAXBElement) RequestSecurityTokenResponseCollectionType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseCollectionType)

Example 77 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class RequestParser method parseKeyInfoElement.

/**
 * Parse the KeyInfo Element to return a ReceivedCredential object containing the found certificate or
 * public key.
 */
private static ReceivedCredential parseKeyInfoElement(Element keyInfoElement) throws STSException {
    KeyInfoFactory keyInfoFactory;
    try {
        keyInfoFactory = KeyInfoFactory.getInstance("DOM", "ApacheXMLDSig");
    } catch (NoSuchProviderException ex) {
        keyInfoFactory = KeyInfoFactory.getInstance("DOM");
    }
    try {
        KeyInfo keyInfo = keyInfoFactory.unmarshalKeyInfo(new DOMStructure(keyInfoElement));
        List<?> list = keyInfo.getContent();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) instanceof KeyValue) {
                KeyValue keyValue = (KeyValue) list.get(i);
                ReceivedCredential receivedKey = new ReceivedCredential();
                receivedKey.setPublicKey(keyValue.getPublicKey());
                return receivedKey;
            } else if (list.get(i) instanceof X509Certificate) {
                ReceivedCredential receivedKey = new ReceivedCredential();
                receivedKey.setX509Cert((X509Certificate) list.get(i));
                return receivedKey;
            } else if (list.get(i) instanceof X509Data) {
                X509Data x509Data = (X509Data) list.get(i);
                for (int j = 0; j < x509Data.getContent().size(); j++) {
                    if (x509Data.getContent().get(j) instanceof X509Certificate) {
                        ReceivedCredential receivedKey = new ReceivedCredential();
                        receivedKey.setX509Cert((X509Certificate) x509Data.getContent().get(j));
                        return receivedKey;
                    }
                }
            }
        }
    } catch (MarshalException | KeyException e) {
        LOG.log(Level.WARNING, "", e);
        throw new STSException(e.getMessage(), e, STSException.INVALID_REQUEST);
    }
    return null;
}
Also used : MarshalException(javax.xml.crypto.MarshalException) KeyValue(javax.xml.crypto.dsig.keyinfo.KeyValue) STSException(org.apache.cxf.ws.security.sts.provider.STSException) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) X509Certificate(java.security.cert.X509Certificate) KeyException(java.security.KeyException) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMStructure(javax.xml.crypto.dom.DOMStructure) NoSuchProviderException(java.security.NoSuchProviderException)

Example 78 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class RequestParser method fetchTokenElementFromReference.

/**
 * Method to fetch token from the SecurityTokenReference
 */
private static Element fetchTokenElementFromReference(Object targetToken, Map<String, Object> messageContext) {
    // Get the reference URI
    String referenceURI = null;
    if (targetToken instanceof Element) {
        Element tokenElement = (Element) targetToken;
        NodeList refList = tokenElement.getElementsByTagNameNS(STSConstants.WSSE_EXT_04_01, "Reference");
        if (refList.getLength() == 0) {
            throw new STSException("Cannot find Reference element in the SecurityTokenReference.", STSException.REQUEST_FAILED);
        }
        referenceURI = refList.item(0).getNodeValue();
    } else if (targetToken instanceof SecurityTokenReferenceType) {
        Iterator<?> iterator = ((SecurityTokenReferenceType) targetToken).getAny().iterator();
        while (iterator.hasNext()) {
            JAXBElement<?> jaxbElement = (JAXBElement<?>) iterator.next();
            if (jaxbElement.getValue() instanceof ReferenceType) {
                referenceURI = ((ReferenceType) jaxbElement.getValue()).getURI();
            }
        }
    }
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Reference URI found " + referenceURI);
    }
    if (referenceURI == null) {
        LOG.log(Level.WARNING, "No Reference URI was received");
        throw new STSException("An unknown element was received", STSException.BAD_REQUEST);
    }
    // Find processed token corresponding to the URI
    referenceURI = XMLUtils.getIDFromReference(referenceURI);
    final List<WSHandlerResult> handlerResults = CastUtils.cast((List<?>) messageContext.get(WSHandlerConstants.RECV_RESULTS));
    if (handlerResults != null && !handlerResults.isEmpty()) {
        WSHandlerResult handlerResult = handlerResults.get(0);
        List<WSSecurityEngineResult> engineResults = handlerResult.getResults();
        for (WSSecurityEngineResult engineResult : engineResults) {
            Integer actInt = (Integer) engineResult.get(WSSecurityEngineResult.TAG_ACTION);
            String id = (String) engineResult.get(WSSecurityEngineResult.TAG_ID);
            if (referenceURI.equals(id)) {
                Element tokenElement = (Element) engineResult.get(WSSecurityEngineResult.TAG_TOKEN_ELEMENT);
                if (tokenElement == null) {
                    throw new STSException("Cannot retrieve token from reference", STSException.INVALID_REQUEST);
                }
                return tokenElement;
            } else if (actInt == WSConstants.SCT) {
                // Need to check special case of SecurityContextToken Identifier separately
                SecurityContextToken sct = (SecurityContextToken) engineResult.get(WSSecurityEngineResult.TAG_SECURITY_CONTEXT_TOKEN);
                if (referenceURI.equals(sct.getIdentifier())) {
                    return sct.getElement();
                }
            }
        }
    }
    throw new STSException("Cannot retreive token from reference", STSException.REQUEST_FAILED);
}
Also used : JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) STSException(org.apache.cxf.ws.security.sts.provider.STSException) JAXBElement(javax.xml.bind.JAXBElement) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) SecurityTokenReferenceType(org.apache.cxf.ws.security.sts.provider.model.secext.SecurityTokenReferenceType) ReferenceType(org.apache.cxf.ws.security.sts.provider.model.secext.ReferenceType) SecurityContextToken(org.apache.wss4j.dom.message.token.SecurityContextToken) Iterator(java.util.Iterator) SecurityTokenReferenceType(org.apache.cxf.ws.security.sts.provider.model.secext.SecurityTokenReferenceType)

Example 79 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class RequestParser method parseUseKey.

/**
 * Parse the UseKey structure to get a ReceivedKey containing a cert/public-key/secret-key.
 * @param useKey The UseKey object
 * @param messageContext The message context object
 * @return the ReceivedKey that has been parsed
 * @throws STSException
 */
private static ReceivedCredential parseUseKey(UseKeyType useKey, Map<String, Object> messageContext) throws STSException {
    byte[] x509 = null;
    if (useKey.getAny() instanceof JAXBElement<?>) {
        JAXBElement<?> useKeyJaxb = (JAXBElement<?>) useKey.getAny();
        Object obj = useKeyJaxb.getValue();
        if (KeyInfoType.class == useKeyJaxb.getDeclaredType() || obj instanceof KeyInfoType) {
            KeyInfoType keyInfoType = KeyInfoType.class.cast(useKeyJaxb.getValue());
            LOG.fine("Found KeyInfo UseKey type");
            for (Object keyInfoContent : keyInfoType.getContent()) {
                X509DataType x509DataType = extractType(keyInfoContent, X509DataType.class);
                if (null != x509DataType) {
                    LOG.fine("Found X509Data KeyInfo type");
                    for (Object x509Object : x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
                        x509 = extractType(x509Object, byte[].class);
                        if (null != x509) {
                            LOG.fine("Found X509Certificate UseKey type");
                            break;
                        }
                    }
                }
            }
        } else if (SecurityTokenReferenceType.class == useKeyJaxb.getDeclaredType() || obj instanceof SecurityTokenReferenceType) {
            SecurityTokenReferenceType strType = SecurityTokenReferenceType.class.cast(useKeyJaxb.getValue());
            Element token = fetchTokenElementFromReference(strType, messageContext);
            try {
                x509 = Base64Utility.decode(token.getTextContent().trim());
                LOG.fine("Found X509Certificate UseKey type via reference");
            } catch (Exception e) {
                LOG.log(Level.WARNING, "", e);
                throw new STSException(e.getMessage(), e, STSException.INVALID_REQUEST);
            }
        }
    } else if (useKey.getAny() instanceof Element) {
        if (isTokenReferenced(useKey.getAny())) {
            Element token = fetchTokenElementFromReference(useKey.getAny(), messageContext);
            try {
                x509 = Base64Utility.decode(token.getTextContent().trim());
                LOG.fine("Found X509Certificate UseKey type via reference");
            } catch (Exception e) {
                LOG.log(Level.WARNING, "", e);
                throw new STSException(e.getMessage(), e, STSException.INVALID_REQUEST);
            }
        } else {
            Element element = (Element) useKey.getAny();
            if ("KeyInfo".equals(element.getLocalName())) {
                return parseKeyInfoElement((Element) useKey.getAny());
            }
            NodeList x509CertData = element.getElementsByTagNameNS(Constants.SignatureSpecNS, Constants._TAG_X509CERTIFICATE);
            if (x509CertData != null && x509CertData.getLength() > 0) {
                try {
                    x509 = Base64Utility.decode(x509CertData.item(0).getTextContent().trim());
                    LOG.fine("Found X509Certificate UseKey type");
                } catch (Exception e) {
                    LOG.log(Level.WARNING, "", e);
                    throw new STSException(e.getMessage(), e, STSException.INVALID_REQUEST);
                }
            }
        }
    } else {
        LOG.log(Level.WARNING, "An unknown element was received");
        throw new STSException("An unknown element was received", STSException.BAD_REQUEST);
    }
    if (x509 != null) {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(x509));
            LOG.fine("Successfully parsed X509 Certificate from UseKey");
            ReceivedCredential receivedCredential = new ReceivedCredential();
            receivedCredential.setX509Cert(cert);
            return receivedCredential;
        } catch (CertificateException ex) {
            LOG.log(Level.WARNING, "", ex);
            throw new STSException("Error in parsing certificate: ", ex, STSException.INVALID_REQUEST);
        }
    }
    return null;
}
Also used : X509DataType(org.apache.cxf.ws.security.sts.provider.model.xmldsig.X509DataType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) STSException(org.apache.cxf.ws.security.sts.provider.STSException) CertificateException(java.security.cert.CertificateException) JAXBElement(javax.xml.bind.JAXBElement) CertificateFactory(java.security.cert.CertificateFactory) KeyException(java.security.KeyException) URISyntaxException(java.net.URISyntaxException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) MarshalException(javax.xml.crypto.MarshalException) CertificateException(java.security.cert.CertificateException) STSException(org.apache.cxf.ws.security.sts.provider.STSException) NoSuchProviderException(java.security.NoSuchProviderException) X509Certificate(java.security.cert.X509Certificate) KeyInfoType(org.apache.cxf.ws.security.sts.provider.model.xmldsig.KeyInfoType) ByteArrayInputStream(java.io.ByteArrayInputStream) SecurityTokenReferenceType(org.apache.cxf.ws.security.sts.provider.model.secext.SecurityTokenReferenceType)

Example 80 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class DefaultJWTClaimsProvider method getSubjectName.

protected String getSubjectName(JWTClaimsProviderParameters jwtClaimsProviderParameters) {
    Principal principal = getPrincipal(jwtClaimsProviderParameters);
    if (principal == null) {
        LOG.fine("Error in getting principal");
        throw new STSException("Error in getting principal", STSException.REQUEST_FAILED);
    }
    String subjectName = principal.getName();
    if (principal instanceof X500Principal) {
        // Just use the "cn" instead of the entire DN
        try {
            String principalName = principal.getName();
            int index = principalName.indexOf('=');
            principalName = principalName.substring(index + 1, principalName.indexOf(',', index));
            subjectName = principalName;
        } catch (Throwable ex) {
            subjectName = principal.getName();
        // Ignore, not X500 compliant thus use the whole string as the value
        }
    }
    return subjectName;
}
Also used : STSException(org.apache.cxf.ws.security.sts.provider.STSException) X500Principal(javax.security.auth.x500.X500Principal) X500Principal(javax.security.auth.x500.X500Principal) Principal(java.security.Principal)

Aggregations

STSException (org.apache.cxf.ws.security.sts.provider.STSException)87 Element (org.w3c.dom.Element)33 Crypto (org.apache.wss4j.common.crypto.Crypto)31 JAXBElement (javax.xml.bind.JAXBElement)30 StaticSTSProperties (org.apache.cxf.sts.StaticSTSProperties)26 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)26 RequestSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType)26 WrappedMessageContext (org.apache.cxf.jaxws.context.WrappedMessageContext)25 MessageImpl (org.apache.cxf.message.MessageImpl)25 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)24 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)24 ServiceMBean (org.apache.cxf.sts.service.ServiceMBean)21 StaticService (org.apache.cxf.sts.service.StaticService)20 RequestSecurityTokenResponseCollectionType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseCollectionType)18 Document (org.w3c.dom.Document)18 Principal (java.security.Principal)14 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)14 EncryptionProperties (org.apache.cxf.sts.service.EncryptionProperties)14 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)13 SAMLTokenProvider (org.apache.cxf.sts.token.provider.SAMLTokenProvider)13