Java Code Examples for org.apache.cxf.ws.security.tokenstore.SecurityToken#getToken()

The following examples show how to use org.apache.cxf.ws.security.tokenstore.SecurityToken#getToken() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultSTSTokenCacher.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static boolean isOneTimeUse(SecurityToken issuedToken) {
    Element token = issuedToken.getToken();
    if (token != null && "Assertion".equals(token.getLocalName())
        && WSS4JConstants.SAML2_NS.equals(token.getNamespaceURI())) {
        try {
            SamlAssertionWrapper assertion = new SamlAssertionWrapper(token);

            if (assertion.getSaml2().getConditions() != null
                && assertion.getSaml2().getConditions().getOneTimeUse() != null) {
                return true;
            }
        } catch (WSSecurityException ex) {
            throw new Fault(ex);
        }
    }

    return false;
}
 
Example 2
Source File: BinarySecurityTokenInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void addToken(SoapMessage message) {
    SecurityToken securityToken = getSecurityToken(message);
    if (securityToken == null || securityToken.getToken() == null) {
        // No SecurityToken so just return
        return;
    }

    assertTokens(message);
    Header h = findSecurityHeader(message, true);
    Element el = (Element)h.getObject();
    el.appendChild(el.getOwnerDocument().importNode(securityToken.getToken(), true));
}
 
Example 3
Source File: STSClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void inlineAttachments(SecurityToken token, Collection<Attachment> attachments) throws WSSecurityException {
    Message msg = PhaseInterceptorChain.getCurrentMessage();
    if (AttachmentUtil.isMtomEnabled(msg) && attachments != null) {
        Element requestedSecurityTokenElement = token.getToken();
        if (requestedSecurityTokenElement != null) {
            // Look for xop:Include Nodes + inline the contents
            List<Element> includeElements =
                XMLUtils.findElements(requestedSecurityTokenElement.getFirstChild(), "Include", WSConstants.XOP_NS);
            WSSecurityUtil.inlineAttachments(includeElements, new AttachmentCallbackHandler(attachments), true);
        }
    }
}
 
Example 4
Source File: TransportBindingHandler.java    From steady with Apache License 2.0 5 votes vote down vote up
public void handleBinding() {
    WSSecTimestamp timestamp = createTimestamp();
    handleLayout(timestamp);
    
    try {
        if (this.isRequestor()) {
            TransportToken transportTokenWrapper = tbinding.getTransportToken();
            if (transportTokenWrapper != null) {
                Token transportToken = transportTokenWrapper.getToken();
                if (transportToken instanceof IssuedToken) {
                    SecurityToken secToken = getSecurityToken();
                    if (secToken == null) {
                        policyNotAsserted(transportToken, "No transport token id");
                        return;
                    } else {
                        policyAsserted(transportToken);
                    }
                    if (includeToken(transportToken.getInclusion())) {
                        Element el = secToken.getToken();
                        addEncryptedKeyElement(cloneElement(el));
                    } 
                }
                
                handleNonEndorsingSupportingTokens();
                handleEndorsingSupportingTokens();
            }
        } else {
            addSignatureConfirmation(null);
        }
    } catch (Exception e) {
        LOG.log(Level.FINE, e.getMessage(), e);
        throw new Fault(e);
    }
}
 
Example 5
Source File: TransportBindingHandler.java    From steady with Apache License 2.0 5 votes vote down vote up
public void handleBinding() {
    WSSecTimestamp timestamp = createTimestamp();
    handleLayout(timestamp);
    
    try {
        if (this.isRequestor()) {
            TransportToken transportTokenWrapper = tbinding.getTransportToken();
            if (transportTokenWrapper != null) {
                Token transportToken = transportTokenWrapper.getToken();
                if (transportToken instanceof IssuedToken) {
                    SecurityToken secToken = getSecurityToken();
                    if (secToken == null) {
                        policyNotAsserted(transportToken, "No transport token id");
                        return;
                    } else {
                        policyAsserted(transportToken);
                    }
                    if (includeToken(transportToken.getInclusion())) {
                        Element el = secToken.getToken();
                        addEncryptedKeyElement(cloneElement(el));
                    } 
                }
                
                handleNonEndorsingSupportingTokens();
                handleEndorsingSupportingTokens();
            }
        } else {
            addSignatureConfirmation(null);
        }
    } catch (Exception e) {
        LOG.log(Level.FINE, e.getMessage(), e);
        throw new Fault(e);
    }
}
 
Example 6
Source File: STSAuthenticationProvider.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected List<GrantedAuthority> createAuthorities(SecurityToken token) throws WSSecurityException {
    List<GrantedAuthority> authorities = new ArrayList<>();
    // authorities.add(new SimpleGrantedAuthority("ROLE_AUTHENTICATED"));
    // Not needed because AuthenticatedVoter has been added for SecurityFlowExecutionListener
    if (roleURI != null) {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(token.getToken());

        List<Claim> claims = parseClaimsInAssertion(assertion.getSaml2());
        for (Claim c : claims) {
            if (c.getClaimType() != null && roleURI.equals(c.getClaimType().toString())) {
                Object oValue = c.getValue();
                if ((oValue instanceof List<?>) && !((List<?>)oValue).isEmpty()) {
                    List<?> values = (List<?>)oValue;
                    for (Object role : values) {
                        if (role instanceof String) {
                            authorities.add(new SimpleGrantedAuthority((String)role));
                        }
                    }
                } else {
                    LOG.error("Unsupported value type of Claim value");
                    throw new IllegalStateException("Unsupported value type of Claim value");
                }
                claims.remove(c);
                break;
            }
        }
    }

    // Add IDP_LOGIN role to be able to access resource Idp, TrustedIdp, etc.
    authorities.add(new SimpleGrantedAuthority("ROLE_IDP_LOGIN"));

    return authorities;
}
 
Example 7
Source File: AsymmetricBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private void doSignBeforeEncrypt() {
    try {
        TokenWrapper initiatorWrapper = abinding.getInitiatorSignatureToken();
        if (initiatorWrapper == null) {
            initiatorWrapper = abinding.getInitiatorToken();
        }
        boolean attached = false;
        if (initiatorWrapper != null) {
            Token initiatorToken = initiatorWrapper.getToken();
            if (initiatorToken instanceof IssuedToken) {
                SecurityToken secToken = getSecurityToken();
                if (secToken == null) {
                    policyNotAsserted(initiatorToken, "Security token is not found or expired");
                    return;
                } else {
                    policyAsserted(initiatorToken);
                    
                    if (includeToken(initiatorToken.getInclusion())) {
                        Element el = secToken.getToken();
                        this.addEncryptedKeyElement(cloneElement(el));
                        attached = true;
                    } 
                }
            } else if (initiatorToken instanceof SamlToken) {
                AssertionWrapper assertionWrapper = addSamlToken((SamlToken)initiatorToken);
                if (assertionWrapper != null) {
                    if (includeToken(initiatorToken.getInclusion())) {
                        addSupportingElement(assertionWrapper.toDOM(saaj.getSOAPPart()));
                        storeAssertionAsSecurityToken(assertionWrapper);
                    }
                    policyAsserted(initiatorToken);
                }
            }
        }
        
        // Add timestamp
        List<WSEncryptionPart> sigs = new ArrayList<WSEncryptionPart>();
        if (timestampEl != null) {
            WSEncryptionPart timestampPart = 
                convertToEncryptionPart(timestampEl.getElement());
            sigs.add(timestampPart);
        }
        addSupportingTokens(sigs);
        
        if (isRequestor() && initiatorWrapper != null) {
            doSignature(initiatorWrapper, sigs, attached);
            doEndorse();
        } else if (!isRequestor()) {
            //confirm sig
            addSignatureConfirmation(sigs);
            
            TokenWrapper recipientSignatureToken = abinding.getRecipientSignatureToken();
            if (recipientSignatureToken == null) {
                recipientSignatureToken = abinding.getRecipientToken();
            }
            if (recipientSignatureToken != null) {
                doSignature(recipientSignatureToken, sigs, attached);
            }
        }

        List<WSEncryptionPart> enc = getEncryptedParts();
        
        //Check for signature protection
        if (abinding.isSignatureProtection()) {
            if (mainSigId != null) {
                WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId, "Element");
                sigPart.setElement(bottomUpElement);
                enc.add(sigPart);
            }
            if (sigConfList != null && !sigConfList.isEmpty()) {
                enc.addAll(sigConfList);
            }
        }
        
        //Do encryption
        TokenWrapper encToken;
        if (isRequestor()) {
            enc.addAll(encryptedTokensList);
            encToken = abinding.getRecipientEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getRecipientToken();
            }
        } else {
            encToken = abinding.getInitiatorEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getInitiatorToken();
            }
        }            
        doEncryption(encToken, enc, false);
        
    } catch (Exception e) {
        String reason = e.getMessage();
        LOG.log(Level.WARNING, "Sign before encryption failed due to : " + reason);
        throw new Fault(e);
    }
}
 
Example 8
Source File: AbstractStaxBindingHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected SecurePart addKerberosToken(
    KerberosToken token, boolean signed, boolean endorsing, boolean encrypting
) throws WSSecurityException, TokenStoreException {
    assertToken(token);
    IncludeTokenType includeToken = token.getIncludeTokenType();
    if (!isTokenRequired(includeToken)) {
        return null;
    }

    final SecurityToken secToken = getSecurityToken();
    if (secToken == null) {
        unassertPolicy(token, "Could not find KerberosToken");
    }

    // Get the kerberos token from the element
    byte[] data = null;
    if (secToken.getToken() != null) {
        String text = XMLUtils.getElementText(secToken.getToken());
        if (text != null) {
            data = org.apache.xml.security.utils.XMLUtils.decode(text);
        }
    }

    // Convert to WSS4J token
    final KerberosClientSecurityToken wss4jToken =
        new KerberosClientSecurityToken(data, secToken.getKey(), secToken.getId()) {

            @Override
            public Key getSecretKey(String algorithmURI) throws XMLSecurityException {
                if (secToken.getSecret() != null && algorithmURI != null && !"".equals(algorithmURI)) {
                    return KeyUtils.prepareSecretKey(algorithmURI, secToken.getSecret());
                }
                return secToken.getKey();
            }
        };
    wss4jToken.setSha1Identifier(secToken.getSHA1());

    final SecurityTokenProvider<OutboundSecurityToken> kerberosSecurityTokenProvider =
        new SecurityTokenProvider<OutboundSecurityToken>() {

            @Override
            public OutboundSecurityToken getSecurityToken() throws WSSecurityException {
                return wss4jToken;
            }

            @Override
            public String getId() {
                return wss4jToken.getId();
            }
        };
    outboundSecurityContext.registerSecurityTokenProvider(
            kerberosSecurityTokenProvider.getId(), kerberosSecurityTokenProvider);
    outboundSecurityContext.put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_KERBEROS,
            kerberosSecurityTokenProvider.getId());

    if (encrypting) {
        outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION,
                kerberosSecurityTokenProvider.getId());
    }
    if (endorsing) {
        outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE,
                kerberosSecurityTokenProvider.getId());
    }

    // Action
    properties.addAction(WSSConstants.KERBEROS_TOKEN);

    /*
    if (endorsing) {
        String action = (String)config.get(ConfigurationConstants.ACTION);
        config.put(ConfigurationConstants.ACTION,
            ConfigurationConstants.SIGNATURE_WITH_KERBEROS_TOKEN  + " " + action);
        // config.put(ConfigurationConstants.SIG_KEY_ID, "DirectReference");
    }
    */

    SecurePart securePart = new SecurePart(WSSConstants.TAG_WSSE_BINARY_SECURITY_TOKEN, Modifier.Element);
    securePart.setIdToSecure(wss4jToken.getId());

    return securePart;
}
 
Example 9
Source File: AsymmetricBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private void doSignBeforeEncrypt() {
    try {
        TokenWrapper initiatorWrapper = abinding.getInitiatorSignatureToken();
        if (initiatorWrapper == null) {
            initiatorWrapper = abinding.getInitiatorToken();
        }
        boolean attached = false;
        if (initiatorWrapper != null) {
            Token initiatorToken = initiatorWrapper.getToken();
            if (initiatorToken instanceof IssuedToken) {
                SecurityToken secToken = getSecurityToken();
                if (secToken == null) {
                    policyNotAsserted(initiatorToken, "Security token is not found or expired");
                    return;
                } else {
                    policyAsserted(initiatorToken);
                    
                    if (includeToken(initiatorToken.getInclusion())) {
                        Element el = secToken.getToken();
                        this.addEncryptedKeyElement(cloneElement(el));
                        attached = true;
                    } 
                }
            } else if (initiatorToken instanceof SamlToken) {
                AssertionWrapper assertionWrapper = addSamlToken((SamlToken)initiatorToken);
                if (assertionWrapper != null) {
                    if (includeToken(initiatorToken.getInclusion())) {
                        addSupportingElement(assertionWrapper.toDOM(saaj.getSOAPPart()));
                        storeAssertionAsSecurityToken(assertionWrapper);
                    }
                    policyAsserted(initiatorToken);
                }
            }
        }
        
        // Add timestamp
        List<WSEncryptionPart> sigs = new ArrayList<WSEncryptionPart>();
        if (timestampEl != null) {
            WSEncryptionPart timestampPart = 
                convertToEncryptionPart(timestampEl.getElement());
            sigs.add(timestampPart);
        }
        addSupportingTokens(sigs);
        
        if (isRequestor() && initiatorWrapper != null) {
            doSignature(initiatorWrapper, sigs, attached);
            doEndorse();
        } else if (!isRequestor()) {
            //confirm sig
            addSignatureConfirmation(sigs);
            
            TokenWrapper recipientSignatureToken = abinding.getRecipientSignatureToken();
            if (recipientSignatureToken == null) {
                recipientSignatureToken = abinding.getRecipientToken();
            }
            if (recipientSignatureToken != null) {
                doSignature(recipientSignatureToken, sigs, attached);
            }
        }

        List<WSEncryptionPart> enc = getEncryptedParts();
        
        //Check for signature protection
        if (abinding.isSignatureProtection()) {
            if (mainSigId != null) {
                WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId, "Element");
                sigPart.setElement(bottomUpElement);
                enc.add(sigPart);
            }
            if (sigConfList != null && !sigConfList.isEmpty()) {
                enc.addAll(sigConfList);
            }
        }
        
        //Do encryption
        TokenWrapper encToken;
        if (isRequestor()) {
            enc.addAll(encryptedTokensList);
            encToken = abinding.getRecipientEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getRecipientToken();
            }
        } else {
            encToken = abinding.getInitiatorEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getInitiatorToken();
            }
        }            
        doEncryption(encToken, enc, false);
        
    } catch (Exception e) {
        String reason = e.getMessage();
        LOG.log(Level.WARNING, "Sign before encryption failed due to : " + reason);
        throw new Fault(e);
    }
}
 
Example 10
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Cancel" invocation and return the response as a STSResponse Object
 */
protected STSResponse cancel(SecurityToken token) throws Exception {
    createClient();

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, token);
    
    BindingOperationInfo boi = findOperation("/RST/Cancel");
    boolean attachTokenDirectly = true;
    if (boi == null) {
        attachTokenDirectly = false;
        boi = findOperation("/RST/Issue");
        
        Policy cancelPolicy = new Policy();
        ExactlyOne one = new ExactlyOne();
        cancelPolicy.addPolicyComponent(one);
        All all = new All();
        one.addPolicyComponent(all);
        all.addAssertion(getAddressingAssertion());
        
        PolicyBuilder pbuilder = bus.getExtension(PolicyBuilder.class);
        SymmetricBinding binding = new SymmetricBinding(pbuilder);
        all.addAssertion(binding);
        all.addAssertion(getAddressingAssertion());
        ProtectionToken ptoken = new ProtectionToken(pbuilder);
        binding.setProtectionToken(ptoken);
        binding.setIncludeTimestamp(true);
        binding.setEntireHeadersAndBodySignatures(true);
        binding.setTokenProtection(false);
        AlgorithmSuite suite = new AlgorithmSuite();
        binding.setAlgorithmSuite(suite);
        SecureConversationToken sct = new SecureConversationToken();
        sct.setOptional(true);
        ptoken.setToken(sct);
        
        SignedEncryptedParts parts = new SignedEncryptedParts(true);
        parts.setOptional(true);
        parts.setBody(true);
        parts.addHeader(new Header("To", addressingNamespace));
        parts.addHeader(new Header("From", addressingNamespace));
        parts.addHeader(new Header("FaultTo", addressingNamespace));
        parts.addHeader(new Header("ReplyTo", addressingNamespace));
        parts.addHeader(new Header("Action", addressingNamespace));
        parts.addHeader(new Header("MessageID", addressingNamespace));
        parts.addHeader(new Header("RelatesTo", addressingNamespace));
        all.addPolicyComponent(parts);
        
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, cancelPolicy);
    }
    
    if (isSecureConv) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION,
                                       namespace + "/RST/SCT/Cancel");
    } else {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                       namespace + "/RST/Cancel");            
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Cancel");
    writer.writeEndElement();

    writer.writeStartElement("wst", "CancelTarget", namespace);
    Element el = null;
    if (attachTokenDirectly) {
        el = token.getToken();
    } else {
        el = token.getUnattachedReference();
        if (el == null) {
            el = token.getAttachedReference();
        }
    }
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object[] obj = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    return new STSResponse((DOMSource)obj[0], null);
}
 
Example 11
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Validate" invocation and return the response as a STSResponse Object
 */
protected STSResponse validate(SecurityToken tok, String tokentype) 
    throws Exception {
    createClient();
    
    if (tokentype == null) {
        tokentype = tokenType;
    }
    if (tokentype == null) {
        tokentype = namespace + "/RSTR/Status";
    }

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    Policy validatePolicy = new Policy();
    ExactlyOne one = new ExactlyOne();
    validatePolicy.addPolicyComponent(one);
    All all = new All();
    one.addPolicyComponent(all);
    all.addAssertion(getAddressingAssertion());

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    BindingOperationInfo boi = findOperation("/RST/Validate");
    if (boi == null) {
        boi = findOperation("/RST/Issue");
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, validatePolicy);
    }
    
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                   namespace + "/RST/Validate");

    
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Validate");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", namespace);
    writer.writeCharacters(tokentype);
    writer.writeEndElement();

    writer.writeStartElement("wst", "ValidateTarget", namespace);

    Element el = tok.getToken();
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object o[] = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    
    return new STSResponse((DOMSource)o[0], null);
}
 
Example 12
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Validate" invocation and return the response as a STSResponse Object
 */
protected STSResponse validate(SecurityToken tok, String tokentype) 
    throws Exception {
    createClient();
    
    if (tokentype == null) {
        tokentype = tokenType;
    }
    if (tokentype == null) {
        tokentype = namespace + "/RSTR/Status";
    }

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    Policy validatePolicy = new Policy();
    ExactlyOne one = new ExactlyOne();
    validatePolicy.addPolicyComponent(one);
    All all = new All();
    one.addPolicyComponent(all);
    all.addAssertion(getAddressingAssertion());

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    BindingOperationInfo boi = findOperation("/RST/Validate");
    if (boi == null) {
        boi = findOperation("/RST/Issue");
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, validatePolicy);
    }
    
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                   namespace + "/RST/Validate");

    
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Validate");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", namespace);
    writer.writeCharacters(tokentype);
    writer.writeEndElement();

    writer.writeStartElement("wst", "ValidateTarget", namespace);

    Element el = tok.getToken();
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object o[] = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    
    return new STSResponse((DOMSource)o[0], null);
}
 
Example 13
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Cancel" invocation and return the response as a STSResponse Object
 */
protected STSResponse cancel(SecurityToken token) throws Exception {
    createClient();

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, token);
    
    BindingOperationInfo boi = findOperation("/RST/Cancel");
    boolean attachTokenDirectly = true;
    if (boi == null) {
        attachTokenDirectly = false;
        boi = findOperation("/RST/Issue");
        
        Policy cancelPolicy = new Policy();
        ExactlyOne one = new ExactlyOne();
        cancelPolicy.addPolicyComponent(one);
        All all = new All();
        one.addPolicyComponent(all);
        all.addAssertion(getAddressingAssertion());
        
        PolicyBuilder pbuilder = bus.getExtension(PolicyBuilder.class);
        SymmetricBinding binding = new SymmetricBinding(pbuilder);
        all.addAssertion(binding);
        all.addAssertion(getAddressingAssertion());
        ProtectionToken ptoken = new ProtectionToken(pbuilder);
        binding.setProtectionToken(ptoken);
        binding.setIncludeTimestamp(true);
        binding.setEntireHeadersAndBodySignatures(true);
        binding.setTokenProtection(false);
        AlgorithmSuite suite = new AlgorithmSuite();
        binding.setAlgorithmSuite(suite);
        SecureConversationToken sct = new SecureConversationToken();
        sct.setOptional(true);
        ptoken.setToken(sct);
        
        SignedEncryptedParts parts = new SignedEncryptedParts(true);
        parts.setOptional(true);
        parts.setBody(true);
        parts.addHeader(new Header("To", addressingNamespace));
        parts.addHeader(new Header("From", addressingNamespace));
        parts.addHeader(new Header("FaultTo", addressingNamespace));
        parts.addHeader(new Header("ReplyTo", addressingNamespace));
        parts.addHeader(new Header("Action", addressingNamespace));
        parts.addHeader(new Header("MessageID", addressingNamespace));
        parts.addHeader(new Header("RelatesTo", addressingNamespace));
        all.addPolicyComponent(parts);
        
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, cancelPolicy);
    }
    
    if (isSecureConv) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION,
                                       namespace + "/RST/SCT/Cancel");
    } else {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                       namespace + "/RST/Cancel");            
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Cancel");
    writer.writeEndElement();

    writer.writeStartElement("wst", "CancelTarget", namespace);
    Element el = null;
    if (attachTokenDirectly) {
        el = token.getToken();
    } else {
        el = token.getUnattachedReference();
        if (el == null) {
            el = token.getAttachedReference();
        }
    }
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object[] obj = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    return new STSResponse((DOMSource)obj[0], null);
}
 
Example 14
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Validate" invocation and return the response as a STSResponse Object
 */
protected STSResponse validate(SecurityToken tok, String tokentype) 
    throws Exception {
    createClient();
    
    if (tokentype == null) {
        tokentype = tokenType;
    }
    if (tokentype == null) {
        tokentype = namespace + "/RSTR/Status";
    }

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    Policy validatePolicy = new Policy();
    ExactlyOne one = new ExactlyOne();
    validatePolicy.addPolicyComponent(one);
    All all = new All();
    one.addPolicyComponent(all);
    all.addAssertion(getAddressingAssertion());

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    BindingOperationInfo boi = findOperation("/RST/Validate");
    if (boi == null) {
        boi = findOperation("/RST/Issue");
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, validatePolicy);
    }
    
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                   namespace + "/RST/Validate");

    
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Validate");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", namespace);
    writer.writeCharacters(tokentype);
    writer.writeEndElement();

    writer.writeStartElement("wst", "ValidateTarget", namespace);

    Element el = tok.getToken();
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object o[] = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    
    return new STSResponse((DOMSource)o[0], null);
}
 
Example 15
Source File: STSKrbAuthenticationProvider.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Authentication handleKerberos(
    KerberosServiceRequestToken kerberosRequestToken,
    IdpSTSClient sts
) {
    Principal kerberosPrincipal = null;
    //
    // If delegation is required then validate the received token + store the
    // Delegated Credential so that we can retrieve a new kerberos token for the
    // STS with it. If delegation is not required, then we just get the received
    // token + pass it to the STS
    //
    if (requireDelegation) {
        kerberosPrincipal = validateKerberosToken(kerberosRequestToken, sts);
        if (kerberosPrincipal == null) {
            return null;
        }
    } else {
        PassThroughKerberosClient kerberosClient = new PassThroughKerberosClient();
        kerberosClient.setToken(kerberosRequestToken.getToken());
        sts.getProperties().put(SecurityConstants.KERBEROS_CLIENT, kerberosClient);
    }

    try {
        // Line below may be uncommented for debugging
        // setTimeout(sts.getClient(), 3600000L);

        SecurityToken token = sts.requestSecurityToken(this.appliesTo);

        if (kerberosPrincipal == null && token.getToken() != null
            && "Assertion".equals(token.getToken().getLocalName())) {
            // For the pass-through Kerberos case, we don't know the Principal name...
            kerberosPrincipal =
                new SAMLTokenPrincipalImpl(new SamlAssertionWrapper(token.getToken()));
        }

        if (kerberosPrincipal == null) {
            LOG.info("Failed to authenticate user '" + kerberosRequestToken.getName());
            return null;
        }

        List<GrantedAuthority> authorities = createAuthorities(token);

        KerberosServiceRequestToken ksrt =
            new KerberosServiceRequestToken(kerberosPrincipal, authorities, kerberosRequestToken.getToken());

        STSUserDetails details = new STSUserDetails(kerberosPrincipal.getName(),
                                                    "",
                                                    authorities,
                                                    token);
        ksrt.setDetails(details);

        LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), kerberosPrincipal.getName());
        return ksrt;
    } catch (Exception ex) {
        LOG.info("Failed to authenticate user '" + kerberosRequestToken.getName() + "'", ex);
        return null;
    }
}
 
Example 16
Source File: AsymmetricBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private void doSignBeforeEncrypt() {
    try {
        TokenWrapper initiatorWrapper = abinding.getInitiatorSignatureToken();
        if (initiatorWrapper == null) {
            initiatorWrapper = abinding.getInitiatorToken();
        }
        boolean attached = false;
        if (initiatorWrapper != null) {
            Token initiatorToken = initiatorWrapper.getToken();
            if (initiatorToken instanceof IssuedToken) {
                SecurityToken secToken = getSecurityToken();
                if (secToken == null) {
                    policyNotAsserted(initiatorToken, "Security token is not found or expired");
                    return;
                } else {
                    policyAsserted(initiatorToken);
                    
                    if (includeToken(initiatorToken.getInclusion())) {
                        Element el = secToken.getToken();
                        this.addEncryptedKeyElement(cloneElement(el));
                        attached = true;
                    } 
                }
            } else if (initiatorToken instanceof SamlToken) {
                AssertionWrapper assertionWrapper = addSamlToken((SamlToken)initiatorToken);
                if (assertionWrapper != null) {
                    if (includeToken(initiatorToken.getInclusion())) {
                        addSupportingElement(assertionWrapper.toDOM(saaj.getSOAPPart()));
                        storeAssertionAsSecurityToken(assertionWrapper);
                    }
                    policyAsserted(initiatorToken);
                }
            }
        }
        
        // Add timestamp
        List<WSEncryptionPart> sigs = new ArrayList<WSEncryptionPart>();
        if (timestampEl != null) {
            WSEncryptionPart timestampPart = 
                convertToEncryptionPart(timestampEl.getElement());
            sigs.add(timestampPart);
        }
        addSupportingTokens(sigs);
        
        if (isRequestor() && initiatorWrapper != null) {
            doSignature(initiatorWrapper, sigs, attached);
            doEndorse();
        } else if (!isRequestor()) {
            //confirm sig
            addSignatureConfirmation(sigs);
            
            TokenWrapper recipientSignatureToken = abinding.getRecipientSignatureToken();
            if (recipientSignatureToken == null) {
                recipientSignatureToken = abinding.getRecipientToken();
            }
            if (recipientSignatureToken != null) {
                doSignature(recipientSignatureToken, sigs, attached);
            }
        }

        List<WSEncryptionPart> enc = getEncryptedParts();
        
        //Check for signature protection
        if (abinding.isSignatureProtection()) {
            if (mainSigId != null) {
                WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId, "Element");
                sigPart.setElement(bottomUpElement);
                enc.add(sigPart);
            }
            if (sigConfList != null && !sigConfList.isEmpty()) {
                enc.addAll(sigConfList);
            }
        }
        
        //Do encryption
        TokenWrapper encToken;
        if (isRequestor()) {
            enc.addAll(encryptedTokensList);
            encToken = abinding.getRecipientEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getRecipientToken();
            }
        } else {
            encToken = abinding.getInitiatorEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getInitiatorToken();
            }
        }            
        doEncryption(encToken, enc, false);
        
    } catch (Exception e) {
        String reason = e.getMessage();
        LOG.log(Level.WARNING, "Sign before encryption failed due to : " + reason);
        throw new Fault(e);
    }
}
 
Example 17
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Cancel" invocation and return the response as a STSResponse Object
 */
protected STSResponse cancel(SecurityToken token) throws Exception {
    createClient();

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, token);
    
    BindingOperationInfo boi = findOperation("/RST/Cancel");
    boolean attachTokenDirectly = true;
    if (boi == null) {
        attachTokenDirectly = false;
        boi = findOperation("/RST/Issue");
        
        Policy cancelPolicy = new Policy();
        ExactlyOne one = new ExactlyOne();
        cancelPolicy.addPolicyComponent(one);
        All all = new All();
        one.addPolicyComponent(all);
        all.addAssertion(getAddressingAssertion());
        
        PolicyBuilder pbuilder = bus.getExtension(PolicyBuilder.class);
        SymmetricBinding binding = new SymmetricBinding(pbuilder);
        all.addAssertion(binding);
        all.addAssertion(getAddressingAssertion());
        ProtectionToken ptoken = new ProtectionToken(pbuilder);
        binding.setProtectionToken(ptoken);
        binding.setIncludeTimestamp(true);
        binding.setEntireHeadersAndBodySignatures(true);
        binding.setTokenProtection(false);
        AlgorithmSuite suite = new AlgorithmSuite();
        binding.setAlgorithmSuite(suite);
        SecureConversationToken sct = new SecureConversationToken();
        sct.setOptional(true);
        ptoken.setToken(sct);
        
        SignedEncryptedParts parts = new SignedEncryptedParts(true);
        parts.setOptional(true);
        parts.setBody(true);
        parts.addHeader(new Header("To", addressingNamespace));
        parts.addHeader(new Header("From", addressingNamespace));
        parts.addHeader(new Header("FaultTo", addressingNamespace));
        parts.addHeader(new Header("ReplyTo", addressingNamespace));
        parts.addHeader(new Header("Action", addressingNamespace));
        parts.addHeader(new Header("MessageID", addressingNamespace));
        parts.addHeader(new Header("RelatesTo", addressingNamespace));
        all.addPolicyComponent(parts);
        
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, cancelPolicy);
    }
    
    if (isSecureConv) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION,
                                       namespace + "/RST/SCT/Cancel");
    } else {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                       namespace + "/RST/Cancel");            
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Cancel");
    writer.writeEndElement();

    writer.writeStartElement("wst", "CancelTarget", namespace);
    Element el = null;
    if (attachTokenDirectly) {
        el = token.getToken();
    } else {
        el = token.getUnattachedReference();
        if (el == null) {
            el = token.getAttachedReference();
        }
    }
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object[] obj = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    return new STSResponse((DOMSource)obj[0], null);
}
 
Example 18
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Validate" invocation and return the response as a STSResponse Object
 */
protected STSResponse validate(SecurityToken tok, String tokentype) 
    throws Exception {
    createClient();
    
    if (tokentype == null) {
        tokentype = tokenType;
    }
    if (tokentype == null) {
        tokentype = namespace + "/RSTR/Status";
    }

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    Policy validatePolicy = new Policy();
    ExactlyOne one = new ExactlyOne();
    validatePolicy.addPolicyComponent(one);
    All all = new All();
    one.addPolicyComponent(all);
    all.addAssertion(getAddressingAssertion());

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    BindingOperationInfo boi = findOperation("/RST/Validate");
    if (boi == null) {
        boi = findOperation("/RST/Issue");
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, validatePolicy);
    }
    
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                   namespace + "/RST/Validate");

    
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Validate");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", namespace);
    writer.writeCharacters(tokentype);
    writer.writeEndElement();

    writer.writeStartElement("wst", "ValidateTarget", namespace);

    Element el = tok.getToken();
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object o[] = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    
    return new STSResponse((DOMSource)o[0], null);
}
 
Example 19
Source File: AsymmetricBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private void doSignBeforeEncrypt() {
    try {
        TokenWrapper initiatorWrapper = abinding.getInitiatorSignatureToken();
        if (initiatorWrapper == null) {
            initiatorWrapper = abinding.getInitiatorToken();
        }
        boolean attached = false;
        if (initiatorWrapper != null) {
            Token initiatorToken = initiatorWrapper.getToken();
            if (initiatorToken instanceof IssuedToken) {
                SecurityToken secToken = getSecurityToken();
                if (secToken == null) {
                    policyNotAsserted(initiatorToken, "Security token is not found or expired");
                    return;
                } else {
                    policyAsserted(initiatorToken);
                    
                    if (includeToken(initiatorToken.getInclusion())) {
                        Element el = secToken.getToken();
                        this.addEncryptedKeyElement(cloneElement(el));
                        attached = true;
                    } 
                }
            } else if (initiatorToken instanceof SamlToken) {
                AssertionWrapper assertionWrapper = addSamlToken((SamlToken)initiatorToken);
                if (assertionWrapper != null) {
                    if (includeToken(initiatorToken.getInclusion())) {
                        addSupportingElement(assertionWrapper.toDOM(saaj.getSOAPPart()));
                        storeAssertionAsSecurityToken(assertionWrapper);
                    }
                    policyAsserted(initiatorToken);
                }
            }
        }
        
        // Add timestamp
        List<WSEncryptionPart> sigs = new ArrayList<WSEncryptionPart>();
        if (timestampEl != null) {
            WSEncryptionPart timestampPart = 
                convertToEncryptionPart(timestampEl.getElement());
            sigs.add(timestampPart);
        }
        addSupportingTokens(sigs);
        
        if (isRequestor() && initiatorWrapper != null) {
            doSignature(initiatorWrapper, sigs, attached);
            doEndorse();
        } else if (!isRequestor()) {
            //confirm sig
            addSignatureConfirmation(sigs);
            
            TokenWrapper recipientSignatureToken = abinding.getRecipientSignatureToken();
            if (recipientSignatureToken == null) {
                recipientSignatureToken = abinding.getRecipientToken();
            }
            if (recipientSignatureToken != null) {
                doSignature(recipientSignatureToken, sigs, attached);
            }
        }

        List<WSEncryptionPart> enc = getEncryptedParts();
        
        //Check for signature protection
        if (abinding.isSignatureProtection()) {
            if (mainSigId != null) {
                WSEncryptionPart sigPart = new WSEncryptionPart(mainSigId, "Element");
                sigPart.setElement(bottomUpElement);
                enc.add(sigPart);
            }
            if (sigConfList != null && !sigConfList.isEmpty()) {
                enc.addAll(sigConfList);
            }
        }
        
        //Do encryption
        TokenWrapper encToken;
        if (isRequestor()) {
            enc.addAll(encryptedTokensList);
            encToken = abinding.getRecipientEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getRecipientToken();
            }
        } else {
            encToken = abinding.getInitiatorEncryptionToken();
            if (encToken == null) {
                encToken = abinding.getInitiatorToken();
            }
        }            
        doEncryption(encToken, enc, false);
        
    } catch (Exception e) {
        String reason = e.getMessage();
        LOG.log(Level.WARNING, "Sign before encryption failed due to : " + reason);
        throw new Fault(e);
    }
}
 
Example 20
Source File: TransportBindingHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handleBinding() {
    WSSecTimestamp timestamp = createTimestamp();
    handleLayout(timestamp);

    try {
        if (this.isRequestor()) {
            TransportToken transportTokenWrapper = tbinding.getTransportToken();
            if (transportTokenWrapper != null) {
                AbstractToken transportToken = transportTokenWrapper.getToken();
                if (transportToken instanceof IssuedToken) {
                    SecurityToken secToken = getSecurityToken();
                    if (secToken == null) {
                        unassertPolicy(transportToken, "No transport token id");
                        return;
                    }
                    assertPolicy(transportToken);
                    if (isTokenRequired(transportToken.getIncludeTokenType())) {
                        Element el = secToken.getToken();
                        addEncryptedKeyElement(cloneElement(el));
                    }
                }
                assertToken(transportToken);
                assertTokenWrapper(transportTokenWrapper);
            }

            handleNonEndorsingSupportingTokens();
            if (transportTokenWrapper != null) {
                handleEndorsingSupportingTokens();
            }
        } else {
            handleNonEndorsingSupportingTokens();
            if (tbinding != null && tbinding.getTransportToken() != null) {
                assertTokenWrapper(tbinding.getTransportToken());
                assertToken(tbinding.getTransportToken().getToken());
                handleEndorsingSupportingTokens();
            }
            addSignatureConfirmation(null);
        }
    } catch (Exception e) {
        LOG.log(Level.FINE, e.getMessage(), e);
        throw new Fault(e);
    }

    if (tbinding != null) {
        assertPolicy(tbinding.getName());
        assertAlgorithmSuite(tbinding.getAlgorithmSuite());
        assertWSSProperties(tbinding.getName().getNamespaceURI());
        assertTrustProperties(tbinding.getName().getNamespaceURI());
    }
    assertPolicy(SP12Constants.SIGNED_PARTS);
    assertPolicy(SP11Constants.SIGNED_PARTS);
    assertPolicy(SP12Constants.ENCRYPTED_PARTS);
    assertPolicy(SP11Constants.ENCRYPTED_PARTS);
}