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

The following examples show how to use org.apache.cxf.ws.security.tokenstore.SecurityToken#getAttachedReference() . 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: TransportBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private byte[] doDerivedKeySignature(
    boolean tokenIncluded,
    SecurityToken secTok,
    Token token,
    List<WSEncryptionPart> sigParts
) throws Exception {
    //Do Signature with derived keys
    WSSecDKSign dkSign = new WSSecDKSign(wssConfig);
    AlgorithmSuite algorithmSuite = tbinding.getAlgorithmSuite();

    //Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (tokenIncluded) {
        ref = secTok.getAttachedReference();
    } else {
        ref = secTok.getUnattachedReference();
    }

    if (ref != null) {
        dkSign.setExternalKey(secTok.getSecret(), cloneElement(ref));
    } else {
        dkSign.setExternalKey(secTok.getSecret(), secTok.getId());
    }
    
    if (token instanceof UsernameToken) {
        dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    } 

    // Set the algo info
    dkSign.setSignatureAlgorithm(algorithmSuite.getSymmetricSignature());
    dkSign.setDerivedKeyLength(algorithmSuite.getSignatureDerivedKeyLength() / 8);
    if (token.getSPConstants() == SP12Constants.INSTANCE) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
    }
    Document doc = saaj.getSOAPPart();
    dkSign.prepare(doc, secHeader);

    addDerivedKeyElement(dkSign.getdktElement());

    dkSign.setParts(sigParts);
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts, secHeader);

    //Do signature
    dkSign.computeSignature(referenceList, false, null);

    return dkSign.getSignatureValue();
}
 
Example 2
Source File: AbstractBindingBuilder.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void doSymmSignatureDerived(AbstractToken policyToken, SecurityToken tok,
                             List<WSEncryptionPart> sigParts, boolean isTokenProtection,
                             boolean isSigProtect)
    throws WSSecurityException {

    Document doc = saaj.getSOAPPart();
    WSSecDKSign dkSign = new WSSecDKSign(secHeader);
    dkSign.setIdAllocator(wssConfig.getIdAllocator());
    dkSign.setCallbackLookup(callbackLookup);
    dkSign.setStoreBytesInAttachment(storeBytesInAttachment);
    dkSign.setExpandXopInclude(isExpandXopInclude());

    //Check whether it is security policy 1.2 and use the secure conversation accordingly
    if (policyToken.getVersion() == SPConstants.SPVersion.SP11) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_02);
    }

    //Check for whether the token is attached in the message or not
    boolean attached = false;
    if (isTokenRequired(policyToken.getIncludeTokenType())) {
        attached = true;
    }

    // Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (attached) {
        ref = tok.getAttachedReference();
    } else {
        ref = tok.getUnattachedReference();
    }

    if (ref != null) {
        ref = cloneElement(ref);
        dkSign.setStrElem(ref);
    } else if (!isRequestor() && policyToken.getDerivedKeys() == DerivedKeys.RequireDerivedKeys) {
        // If the Encrypted key used to create the derived key is not
        // attached use key identifier as defined in WSS1.1 section
        // 7.7 Encrypted Key reference
        SecurityTokenReference tokenRef
            = new SecurityTokenReference(doc);
        if (tok.getSHA1() != null) {
            tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1());
            tokenRef.addTokenType(WSS4JConstants.WSS_ENC_KEY_VALUE_TYPE);
        }
        dkSign.setStrElem(tokenRef.getElement());

    } else {
        dkSign.setTokenIdentifier(tok.getId());
    }

    //Set the algo info
    dkSign.setSignatureAlgorithm(binding.getAlgorithmSuite().getAlgorithmSuiteType().getSymmetricSignature());
    dkSign.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue());
    AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType();
    dkSign.setDerivedKeyLength(algType.getSignatureDerivedKeyLength() / 8);
    if (tok.getSHA1() != null) {
        //Set the value type of the reference
        dkSign.setCustomValueType(WSS4JConstants.SOAPMESSAGE_NS11 + "#"
            + WSS4JConstants.ENC_KEY_VALUE_TYPE);
    } else if (policyToken instanceof UsernameToken) {
        dkSign.setCustomValueType(WSS4JConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    }

    dkSign.prepare(tok.getSecret());

    if (isTokenProtection) {
        String sigTokId = XMLUtils.getIDFromReference(tok.getId());
        sigParts.add(new WSEncryptionPart(sigTokId));
    }

    dkSign.getParts().addAll(sigParts);

    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts);

    //Add elements to header
    addSupportingElement(dkSign.getdktElement());

    //Do signature
    dkSign.computeSignature(referenceList, false, null);

    if (isSigProtect) {
        WSEncryptionPart part = new WSEncryptionPart(dkSign.getSignatureId(), "Element");
        encryptedTokensList.add(part);
    }

    addSig(dkSign.getSignatureValue());
    dkSign.clean();
}
 
Example 3
Source File: TransportBindingHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
private byte[] doDerivedKeySignature(
    boolean tokenIncluded,
    SecurityToken secTok,
    AbstractToken token,
    List<WSEncryptionPart> sigParts
) throws Exception {
    //Do Signature with derived keys
    WSSecDKSign dkSign = new WSSecDKSign(secHeader);
    dkSign.setIdAllocator(wssConfig.getIdAllocator());
    dkSign.setCallbackLookup(callbackLookup);
    dkSign.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message));
    dkSign.setStoreBytesInAttachment(storeBytesInAttachment);
    dkSign.setExpandXopInclude(isExpandXopInclude());
    dkSign.setWsDocInfo(wsDocInfo);

    AlgorithmSuite algorithmSuite = tbinding.getAlgorithmSuite();

    //Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (tokenIncluded) {
        ref = secTok.getAttachedReference();
    } else {
        ref = secTok.getUnattachedReference();
    }

    if (ref != null) {
        dkSign.setStrElem(cloneElement(ref));
    } else {
        dkSign.setTokenIdentifier(secTok.getId());
    }

    if (token instanceof UsernameToken) {
        dkSign.setCustomValueType(WSS4JConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    }

    // Set the algo info
    dkSign.setSignatureAlgorithm(algorithmSuite.getAlgorithmSuiteType().getSymmetricSignature());
    AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType();
    dkSign.setDerivedKeyLength(algType.getSignatureDerivedKeyLength() / 8);
    if (token.getVersion() == SPConstants.SPVersion.SP11) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_02);
    }
    dkSign.prepare(secTok.getSecret());

    addDerivedKeyElement(dkSign.getdktElement());

    dkSign.getParts().addAll(sigParts);
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts);

    //Do signature
    dkSign.computeSignature(referenceList, false, null);

    dkSign.clean();
    return dkSign.getSignatureValue();
}
 
Example 4
Source File: AbstractStaxBindingHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void storeSecurityToken(AbstractToken policyToken, SecurityToken tok) {
    SecurityTokenConstants.TokenType tokenType = WSSecurityTokenConstants.EncryptedKeyToken;
    if (tok.getTokenType() != null) {
        if (tok.getTokenType().startsWith(WSSConstants.NS_KERBEROS11_TOKEN_PROFILE)) {
            tokenType = WSSecurityTokenConstants.KERBEROS_TOKEN;
        } else if (tok.getTokenType().startsWith(WSSConstants.NS_SAML10_TOKEN_PROFILE)
            || tok.getTokenType().startsWith(WSSConstants.NS_SAML11_TOKEN_PROFILE)) {
            tokenType = WSSecurityTokenConstants.SAML_11_TOKEN;
        } else if (tok.getTokenType().startsWith(WSSConstants.NS_WSC_05_02)
            || tok.getTokenType().startsWith(WSSConstants.NS_WSC_05_12)) {
            tokenType = WSSecurityTokenConstants.SECURE_CONVERSATION_TOKEN;
        }
    }

    final Key key = tok.getKey();
    final byte[] secret = tok.getSecret();
    final X509Certificate[] certs = new X509Certificate[1];
    if (tok.getX509Certificate() != null) {
        certs[0] = tok.getX509Certificate();
    }

    final GenericOutboundSecurityToken encryptedKeySecurityToken =
        new GenericOutboundSecurityToken(tok.getId(), tokenType, key, certs) {

            @Override
            public Key getSecretKey(String algorithmURI) throws XMLSecurityException {
                if (secret != null && algorithmURI != null && !"".equals(algorithmURI)) {
                    return KeyUtils.prepareSecretKey(algorithmURI, secret);
                }
                if (key != null) {
                    return key;
                }
                if (secret != null) {
                    String jceAlg = JCEMapper.getJCEKeyAlgorithmFromURI(algorithmURI);
                    if (jceAlg == null || "".equals(jceAlg)) {
                        jceAlg = "HmacSHA1";
                    }
                    return new SecretKeySpec(secret, jceAlg);
                }

                return super.getSecretKey(algorithmURI);
            }
        };

    // Store a DOM Element reference if it exists
    Element ref;
    if (isTokenRequired(policyToken.getIncludeTokenType())) {
        ref = tok.getAttachedReference();
    } else {
        ref = tok.getUnattachedReference();
    }

    if (ref != null && policyToken instanceof IssuedToken) {
        encryptedKeySecurityToken.setCustomTokenReference(ref);
    }
    final SecurityTokenProvider<OutboundSecurityToken> encryptedKeySecurityTokenProvider =
        new SecurityTokenProvider<OutboundSecurityToken>() {

            @Override
            public OutboundSecurityToken getSecurityToken() throws XMLSecurityException {
                return encryptedKeySecurityToken;
            }

            @Override
            public String getId() {
                return encryptedKeySecurityToken.getId();
            }

        };
    encryptedKeySecurityToken.setSha1Identifier(tok.getSHA1());

    outboundSecurityContext.registerSecurityTokenProvider(
            encryptedKeySecurityTokenProvider.getId(), encryptedKeySecurityTokenProvider);
    outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION,
            encryptedKeySecurityTokenProvider.getId());
    outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE,
            encryptedKeySecurityTokenProvider.getId());
    outboundSecurityContext.put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_CUSTOM_TOKEN,
            encryptedKeySecurityTokenProvider.getId());
}
 
Example 5
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 4 votes vote down vote up
private void doSymmSignatureDerived(Token policyToken, SecurityToken tok,
                             List<WSEncryptionPart> sigParts, boolean isTokenProtection)
    throws WSSecurityException, ConversationException {
    
    Document doc = saaj.getSOAPPart();
    WSSecDKSign dkSign = new WSSecDKSign(wssConfig);  
    
    //Check whether it is security policy 1.2 and use the secure conversation accordingly
    if (SP12Constants.INSTANCE == policyToken.getSPConstants()) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
    }
                  
    //Check for whether the token is attached in the message or not
    boolean attached = false;
    if (includeToken(policyToken.getInclusion())) {
        attached = true;
    }
    
    // Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (attached) {
        ref = tok.getAttachedReference();
    } else {
        ref = tok.getUnattachedReference();
    }
    
    if (ref != null) {
        ref = cloneElement(ref);
        dkSign.setExternalKey(tok.getSecret(), ref);
    } else if (!isRequestor() && policyToken.isDerivedKeys()) { 
        // If the Encrypted key used to create the derived key is not
        // attached use key identifier as defined in WSS1.1 section
        // 7.7 Encrypted Key reference
        SecurityTokenReference tokenRef 
            = new SecurityTokenReference(doc);
        if (tok.getSHA1() != null) {
            tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1());
            tokenRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
        }
        dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
    
    } else {
        dkSign.setExternalKey(tok.getSecret(), tok.getId());
    }

    //Set the algo info
    dkSign.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
    dkSign.setDerivedKeyLength(binding.getAlgorithmSuite().getSignatureDerivedKeyLength() / 8);
    if (tok.getSHA1() != null) {
        //Set the value type of the reference
        dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
            + WSConstants.ENC_KEY_VALUE_TYPE);
    } else if (policyToken instanceof UsernameToken) {
        dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    } 
    
    dkSign.prepare(doc, secHeader);
    
    if (isTokenProtection) {
        //Hack to handle reference id issues
        //TODO Need a better fix
        String sigTokId = tok.getId();
        if (sigTokId.startsWith("#")) {
            sigTokId = sigTokId.substring(1);
        }
        sigParts.add(new WSEncryptionPart(sigTokId));
    }
    
    dkSign.setParts(sigParts);
    
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts, secHeader);
    
    //Add elements to header
    addSupportingElement(dkSign.getdktElement());
    
    //Do signature
    dkSign.computeSignature(referenceList, false, null);
    
    signatures.add(dkSign.getSignatureValue());
}
 
Example 6
Source File: TransportBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private byte[] doSignature(
    boolean tokenIncluded,
    SecurityToken secTok,
    Token token,
    TokenWrapper wrapper,
    List<WSEncryptionPart> sigParts
) throws Exception {
    WSSecSignature sig = new WSSecSignature(wssConfig);
    
    //Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (tokenIncluded) {
        ref = secTok.getAttachedReference();
    } else {
        ref = secTok.getUnattachedReference();
    }
    
    if (ref != null) {
        SecurityTokenReference secRef = 
            new SecurityTokenReference(cloneElement(ref), false);
        sig.setSecurityTokenReference(secRef);
        sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
    } else if (token instanceof UsernameToken) {
        sig.setCustomTokenId(secTok.getId());
        sig.setCustomTokenValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        int type = tokenIncluded ? WSConstants.CUSTOM_SYMM_SIGNING 
                : WSConstants.CUSTOM_SYMM_SIGNING_DIRECT;
        sig.setKeyIdentifierType(type);
    } else if (secTok.getTokenType() == null) {
        sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
        sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
    } else {
        String id = secTok.getWsuId();
        if (id == null) {
            sig.setCustomTokenId(secTok.getId());
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING_DIRECT);
        } else {
            sig.setCustomTokenId(secTok.getWsuId());
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        }
        String tokenType = secTok.getTokenType();
        if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML2_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        } else {
            sig.setCustomTokenValueType(tokenType);
        }
    }
    Crypto crypto = null;
    if (secTok.getSecret() == null) {
        sig.setX509Certificate(secTok.getX509Certificate());

        crypto = secTok.getCrypto();
        if (crypto == null) {
            crypto = getSignatureCrypto(wrapper);
        }
        String uname = crypto.getX509Identifier(secTok.getX509Certificate());
        if (uname == null) {
            String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
            uname = (String)message.getContextualProperty(userNameKey);
        }
        String password = getPassword(uname, token, WSPasswordCallback.SIGNATURE);
        if (password == null) {
            password = "";
        }
        sig.setUserInfo(uname, password);
        sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature());
    } else {
        crypto = getSignatureCrypto(wrapper);
        sig.setSecretKey(secTok.getSecret());
        sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
    }
    sig.setSigCanonicalization(binding.getAlgorithmSuite().getInclusiveC14n());

    Document doc = saaj.getSOAPPart();
    sig.prepare(doc, crypto, secHeader);

    sig.setParts(sigParts);
    List<Reference> referenceList = sig.addReferencesToSign(sigParts, secHeader);

    //Do signature
    if (bottomUpElement == null) {
        sig.computeSignature(referenceList, false, null);
    } else {
        sig.computeSignature(referenceList, true, bottomUpElement);
    }
    bottomUpElement = sig.getSignatureElement();
    mainSigId = sig.getId();

    return sig.getSignatureValue();
}
 
Example 7
Source File: TransportBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private byte[] doDerivedKeySignature(
    boolean tokenIncluded,
    SecurityToken secTok,
    Token token,
    List<WSEncryptionPart> sigParts
) throws Exception {
    //Do Signature with derived keys
    WSSecDKSign dkSign = new WSSecDKSign(wssConfig);
    AlgorithmSuite algorithmSuite = tbinding.getAlgorithmSuite();

    //Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (tokenIncluded) {
        ref = secTok.getAttachedReference();
    } else {
        ref = secTok.getUnattachedReference();
    }

    if (ref != null) {
        dkSign.setExternalKey(secTok.getSecret(), cloneElement(ref));
    } else {
        dkSign.setExternalKey(secTok.getSecret(), secTok.getId());
    }
    
    if (token instanceof UsernameToken) {
        dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    } 

    // Set the algo info
    dkSign.setSignatureAlgorithm(algorithmSuite.getSymmetricSignature());
    dkSign.setDerivedKeyLength(algorithmSuite.getSignatureDerivedKeyLength() / 8);
    if (token.getSPConstants() == SP12Constants.INSTANCE) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
    }
    Document doc = saaj.getSOAPPart();
    dkSign.prepare(doc, secHeader);

    addDerivedKeyElement(dkSign.getdktElement());

    dkSign.setParts(sigParts);
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts, secHeader);

    //Do signature
    dkSign.computeSignature(referenceList, false, null);

    return dkSign.getSignatureValue();
}
 
Example 8
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 9
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 4 votes vote down vote up
private void doSymmSignatureDerived(Token policyToken, SecurityToken tok,
                             List<WSEncryptionPart> sigParts, boolean isTokenProtection)
    throws WSSecurityException, ConversationException {
    
    Document doc = saaj.getSOAPPart();
    WSSecDKSign dkSign = new WSSecDKSign(wssConfig);  
    
    //Check whether it is security policy 1.2 and use the secure conversation accordingly
    if (SP12Constants.INSTANCE == policyToken.getSPConstants()) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
    }
                  
    //Check for whether the token is attached in the message or not
    boolean attached = false;
    if (includeToken(policyToken.getInclusion())) {
        attached = true;
    }
    
    // Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (attached) {
        ref = tok.getAttachedReference();
    } else {
        ref = tok.getUnattachedReference();
    }
    
    if (ref != null) {
        ref = cloneElement(ref);
        dkSign.setExternalKey(tok.getSecret(), ref);
    } else if (!isRequestor() && policyToken.isDerivedKeys()) { 
        // If the Encrypted key used to create the derived key is not
        // attached use key identifier as defined in WSS1.1 section
        // 7.7 Encrypted Key reference
        SecurityTokenReference tokenRef 
            = new SecurityTokenReference(doc);
        if (tok.getSHA1() != null) {
            tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1());
            tokenRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
        }
        dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
    
    } else {
        dkSign.setExternalKey(tok.getSecret(), tok.getId());
    }

    //Set the algo info
    dkSign.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
    dkSign.setDerivedKeyLength(binding.getAlgorithmSuite().getSignatureDerivedKeyLength() / 8);
    if (tok.getSHA1() != null) {
        //Set the value type of the reference
        dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
            + WSConstants.ENC_KEY_VALUE_TYPE);
    } else if (policyToken instanceof UsernameToken) {
        dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    } 
    
    dkSign.prepare(doc, secHeader);
    
    if (isTokenProtection) {
        //Hack to handle reference id issues
        //TODO Need a better fix
        String sigTokId = tok.getId();
        if (sigTokId.startsWith("#")) {
            sigTokId = sigTokId.substring(1);
        }
        sigParts.add(new WSEncryptionPart(sigTokId));
    }
    
    dkSign.setParts(sigParts);
    
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts, secHeader);
    
    //Add elements to header
    addSupportingElement(dkSign.getdktElement());
    
    //Do signature
    dkSign.computeSignature(referenceList, false, null);
    
    signatures.add(dkSign.getSignatureValue());
}
 
Example 10
Source File: TransportBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private byte[] doSignature(
    boolean tokenIncluded,
    SecurityToken secTok,
    Token token,
    TokenWrapper wrapper,
    List<WSEncryptionPart> sigParts
) throws Exception {
    WSSecSignature sig = new WSSecSignature(wssConfig);
    
    //Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (tokenIncluded) {
        ref = secTok.getAttachedReference();
    } else {
        ref = secTok.getUnattachedReference();
    }
    
    if (ref != null) {
        SecurityTokenReference secRef = 
            new SecurityTokenReference(cloneElement(ref), false);
        sig.setSecurityTokenReference(secRef);
        sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
    } else if (token instanceof UsernameToken) {
        sig.setCustomTokenId(secTok.getId());
        sig.setCustomTokenValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        int type = tokenIncluded ? WSConstants.CUSTOM_SYMM_SIGNING 
                : WSConstants.CUSTOM_SYMM_SIGNING_DIRECT;
        sig.setKeyIdentifierType(type);
    } else if (secTok.getTokenType() == null) {
        sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
        sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
    } else {
        String id = secTok.getWsuId();
        if (id == null) {
            sig.setCustomTokenId(secTok.getId());
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING_DIRECT);
        } else {
            sig.setCustomTokenId(secTok.getWsuId());
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        }
        String tokenType = secTok.getTokenType();
        if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML2_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        } else {
            sig.setCustomTokenValueType(tokenType);
        }
    }
    Crypto crypto = null;
    if (secTok.getSecret() == null) {
        sig.setX509Certificate(secTok.getX509Certificate());

        crypto = secTok.getCrypto();
        if (crypto == null) {
            crypto = getSignatureCrypto(wrapper);
        }
        String uname = crypto.getX509Identifier(secTok.getX509Certificate());
        if (uname == null) {
            String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
            uname = (String)message.getContextualProperty(userNameKey);
        }
        String password = getPassword(uname, token, WSPasswordCallback.SIGNATURE);
        if (password == null) {
            password = "";
        }
        sig.setUserInfo(uname, password);
        sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature());
    } else {
        crypto = getSignatureCrypto(wrapper);
        sig.setSecretKey(secTok.getSecret());
        sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
    }
    sig.setSigCanonicalization(binding.getAlgorithmSuite().getInclusiveC14n());

    Document doc = saaj.getSOAPPart();
    sig.prepare(doc, crypto, secHeader);

    sig.setParts(sigParts);
    List<Reference> referenceList = sig.addReferencesToSign(sigParts, secHeader);

    //Do signature
    if (bottomUpElement == null) {
        sig.computeSignature(referenceList, false, null);
    } else {
        sig.computeSignature(referenceList, true, bottomUpElement);
    }
    bottomUpElement = sig.getSignatureElement();
    mainSigId = sig.getId();

    return sig.getSignatureValue();
}
 
Example 11
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 12
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 13
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 4 votes vote down vote up
private void doSymmSignatureDerived(Token policyToken, SecurityToken tok,
                             List<WSEncryptionPart> sigParts, boolean isTokenProtection)
    throws WSSecurityException, ConversationException {
    
    Document doc = saaj.getSOAPPart();
    WSSecDKSign dkSign = new WSSecDKSign(wssConfig);  
    
    //Check whether it is security policy 1.2 and use the secure conversation accordingly
    if (SP12Constants.INSTANCE == policyToken.getSPConstants()) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
    }
                  
    //Check for whether the token is attached in the message or not
    boolean attached = false;
    if (includeToken(policyToken.getInclusion())) {
        attached = true;
    }
    
    // Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (attached) {
        ref = tok.getAttachedReference();
    } else {
        ref = tok.getUnattachedReference();
    }
    
    if (ref != null) {
        ref = cloneElement(ref);
        dkSign.setExternalKey(tok.getSecret(), ref);
    } else if (!isRequestor() && policyToken.isDerivedKeys()) { 
        // If the Encrypted key used to create the derived key is not
        // attached use key identifier as defined in WSS1.1 section
        // 7.7 Encrypted Key reference
        SecurityTokenReference tokenRef 
            = new SecurityTokenReference(doc);
        if (tok.getSHA1() != null) {
            tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1());
            tokenRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
        }
        dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
    
    } else {
        dkSign.setExternalKey(tok.getSecret(), tok.getId());
    }

    //Set the algo info
    dkSign.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
    dkSign.setDerivedKeyLength(binding.getAlgorithmSuite().getSignatureDerivedKeyLength() / 8);
    if (tok.getSHA1() != null) {
        //Set the value type of the reference
        dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
            + WSConstants.ENC_KEY_VALUE_TYPE);
    } else if (policyToken instanceof UsernameToken) {
        dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    } 
    
    dkSign.prepare(doc, secHeader);
    
    if (isTokenProtection) {
        //Hack to handle reference id issues
        //TODO Need a better fix
        String sigTokId = tok.getId();
        if (sigTokId.startsWith("#")) {
            sigTokId = sigTokId.substring(1);
        }
        sigParts.add(new WSEncryptionPart(sigTokId));
    }
    
    dkSign.setParts(sigParts);
    
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts, secHeader);
    
    //Add elements to header
    addSupportingElement(dkSign.getdktElement());
    
    //Do signature
    dkSign.computeSignature(referenceList, false, null);
    
    signatures.add(dkSign.getSignatureValue());
}
 
Example 14
Source File: TransportBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private byte[] doSignature(
    boolean tokenIncluded,
    SecurityToken secTok,
    Token token,
    TokenWrapper wrapper,
    List<WSEncryptionPart> sigParts
) throws Exception {
    WSSecSignature sig = new WSSecSignature(wssConfig);
    
    //Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (tokenIncluded) {
        ref = secTok.getAttachedReference();
    } else {
        ref = secTok.getUnattachedReference();
    }
    
    if (ref != null) {
        SecurityTokenReference secRef = 
            new SecurityTokenReference(cloneElement(ref), false);
        sig.setSecurityTokenReference(secRef);
        sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
    } else if (token instanceof UsernameToken) {
        sig.setCustomTokenId(secTok.getId());
        sig.setCustomTokenValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        int type = tokenIncluded ? WSConstants.CUSTOM_SYMM_SIGNING 
                : WSConstants.CUSTOM_SYMM_SIGNING_DIRECT;
        sig.setKeyIdentifierType(type);
    } else if (secTok.getTokenType() == null) {
        sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
        sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
    } else {
        String id = secTok.getWsuId();
        if (id == null) {
            sig.setCustomTokenId(secTok.getId());
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING_DIRECT);
        } else {
            sig.setCustomTokenId(secTok.getWsuId());
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        }
        String tokenType = secTok.getTokenType();
        if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML2_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        } else {
            sig.setCustomTokenValueType(tokenType);
        }
    }
    Crypto crypto = null;
    if (secTok.getSecret() == null) {
        sig.setX509Certificate(secTok.getX509Certificate());

        crypto = secTok.getCrypto();
        if (crypto == null) {
            crypto = getSignatureCrypto(wrapper);
        }
        String uname = crypto.getX509Identifier(secTok.getX509Certificate());
        if (uname == null) {
            String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
            uname = (String)message.getContextualProperty(userNameKey);
        }
        String password = getPassword(uname, token, WSPasswordCallback.SIGNATURE);
        if (password == null) {
            password = "";
        }
        sig.setUserInfo(uname, password);
        sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature());
    } else {
        crypto = getSignatureCrypto(wrapper);
        sig.setSecretKey(secTok.getSecret());
        sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
    }
    sig.setSigCanonicalization(binding.getAlgorithmSuite().getInclusiveC14n());

    Document doc = saaj.getSOAPPart();
    sig.prepare(doc, crypto, secHeader);

    sig.setParts(sigParts);
    List<Reference> referenceList = sig.addReferencesToSign(sigParts, secHeader);

    //Do signature
    if (bottomUpElement == null) {
        sig.computeSignature(referenceList, false, null);
    } else {
        sig.computeSignature(referenceList, true, bottomUpElement);
    }
    bottomUpElement = sig.getSignatureElement();
    mainSigId = sig.getId();

    return sig.getSignatureValue();
}
 
Example 15
Source File: TransportBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private byte[] doDerivedKeySignature(
    boolean tokenIncluded,
    SecurityToken secTok,
    Token token,
    List<WSEncryptionPart> sigParts
) throws Exception {
    //Do Signature with derived keys
    WSSecDKSign dkSign = new WSSecDKSign(wssConfig);
    AlgorithmSuite algorithmSuite = tbinding.getAlgorithmSuite();

    //Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (tokenIncluded) {
        ref = secTok.getAttachedReference();
    } else {
        ref = secTok.getUnattachedReference();
    }

    if (ref != null) {
        dkSign.setExternalKey(secTok.getSecret(), cloneElement(ref));
    } else {
        dkSign.setExternalKey(secTok.getSecret(), secTok.getId());
    }
    
    if (token instanceof UsernameToken) {
        dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    } 

    // Set the algo info
    dkSign.setSignatureAlgorithm(algorithmSuite.getSymmetricSignature());
    dkSign.setDerivedKeyLength(algorithmSuite.getSignatureDerivedKeyLength() / 8);
    if (token.getSPConstants() == SP12Constants.INSTANCE) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
    }
    Document doc = saaj.getSOAPPart();
    dkSign.prepare(doc, secHeader);

    addDerivedKeyElement(dkSign.getdktElement());

    dkSign.setParts(sigParts);
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts, secHeader);

    //Do signature
    dkSign.computeSignature(referenceList, false, null);

    return dkSign.getSignatureValue();
}
 
Example 16
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 17
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 4 votes vote down vote up
private void doSymmSignatureDerived(Token policyToken, SecurityToken tok,
                             List<WSEncryptionPart> sigParts, boolean isTokenProtection)
    throws WSSecurityException, ConversationException {
    
    Document doc = saaj.getSOAPPart();
    WSSecDKSign dkSign = new WSSecDKSign(wssConfig);  
    
    //Check whether it is security policy 1.2 and use the secure conversation accordingly
    if (SP12Constants.INSTANCE == policyToken.getSPConstants()) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
    }
                  
    //Check for whether the token is attached in the message or not
    boolean attached = false;
    if (includeToken(policyToken.getInclusion())) {
        attached = true;
    }
    
    // Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (attached) {
        ref = tok.getAttachedReference();
    } else {
        ref = tok.getUnattachedReference();
    }
    
    if (ref != null) {
        ref = cloneElement(ref);
        dkSign.setExternalKey(tok.getSecret(), ref);
    } else if (!isRequestor() && policyToken.isDerivedKeys()) { 
        // If the Encrypted key used to create the derived key is not
        // attached use key identifier as defined in WSS1.1 section
        // 7.7 Encrypted Key reference
        SecurityTokenReference tokenRef 
            = new SecurityTokenReference(doc);
        if (tok.getSHA1() != null) {
            tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1());
            tokenRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
        }
        dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
    
    } else {
        dkSign.setExternalKey(tok.getSecret(), tok.getId());
    }

    //Set the algo info
    dkSign.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
    dkSign.setDerivedKeyLength(binding.getAlgorithmSuite().getSignatureDerivedKeyLength() / 8);
    if (tok.getSHA1() != null) {
        //Set the value type of the reference
        dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
            + WSConstants.ENC_KEY_VALUE_TYPE);
    } else if (policyToken instanceof UsernameToken) {
        dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    } 
    
    dkSign.prepare(doc, secHeader);
    
    if (isTokenProtection) {
        //Hack to handle reference id issues
        //TODO Need a better fix
        String sigTokId = tok.getId();
        if (sigTokId.startsWith("#")) {
            sigTokId = sigTokId.substring(1);
        }
        sigParts.add(new WSEncryptionPart(sigTokId));
    }
    
    dkSign.setParts(sigParts);
    
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts, secHeader);
    
    //Add elements to header
    addSupportingElement(dkSign.getdktElement());
    
    //Do signature
    dkSign.computeSignature(referenceList, false, null);
    
    signatures.add(dkSign.getSignatureValue());
}
 
Example 18
Source File: TransportBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private byte[] doSignature(
    boolean tokenIncluded,
    SecurityToken secTok,
    Token token,
    TokenWrapper wrapper,
    List<WSEncryptionPart> sigParts
) throws Exception {
    WSSecSignature sig = new WSSecSignature(wssConfig);
    
    //Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (tokenIncluded) {
        ref = secTok.getAttachedReference();
    } else {
        ref = secTok.getUnattachedReference();
    }
    
    if (ref != null) {
        SecurityTokenReference secRef = 
            new SecurityTokenReference(cloneElement(ref), false);
        sig.setSecurityTokenReference(secRef);
        sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
    } else if (token instanceof UsernameToken) {
        sig.setCustomTokenId(secTok.getId());
        sig.setCustomTokenValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        int type = tokenIncluded ? WSConstants.CUSTOM_SYMM_SIGNING 
                : WSConstants.CUSTOM_SYMM_SIGNING_DIRECT;
        sig.setKeyIdentifierType(type);
    } else if (secTok.getTokenType() == null) {
        sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
        sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
    } else {
        String id = secTok.getWsuId();
        if (id == null) {
            sig.setCustomTokenId(secTok.getId());
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING_DIRECT);
        } else {
            sig.setCustomTokenId(secTok.getWsuId());
            sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        }
        String tokenType = secTok.getTokenType();
        if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
            || WSConstants.SAML2_NS.equals(tokenType)) {
            sig.setCustomTokenValueType(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
            sig.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        } else {
            sig.setCustomTokenValueType(tokenType);
        }
    }
    Crypto crypto = null;
    if (secTok.getSecret() == null) {
        sig.setX509Certificate(secTok.getX509Certificate());

        crypto = secTok.getCrypto();
        if (crypto == null) {
            crypto = getSignatureCrypto(wrapper);
        }
        String uname = crypto.getX509Identifier(secTok.getX509Certificate());
        if (uname == null) {
            String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
            uname = (String)message.getContextualProperty(userNameKey);
        }
        String password = getPassword(uname, token, WSPasswordCallback.SIGNATURE);
        if (password == null) {
            password = "";
        }
        sig.setUserInfo(uname, password);
        sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getAsymmetricSignature());
    } else {
        crypto = getSignatureCrypto(wrapper);
        sig.setSecretKey(secTok.getSecret());
        sig.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
    }
    sig.setSigCanonicalization(binding.getAlgorithmSuite().getInclusiveC14n());

    Document doc = saaj.getSOAPPart();
    sig.prepare(doc, crypto, secHeader);

    sig.setParts(sigParts);
    List<Reference> referenceList = sig.addReferencesToSign(sigParts, secHeader);

    //Do signature
    if (bottomUpElement == null) {
        sig.computeSignature(referenceList, false, null);
    } else {
        sig.computeSignature(referenceList, true, bottomUpElement);
    }
    bottomUpElement = sig.getSignatureElement();
    mainSigId = sig.getId();

    return sig.getSignatureValue();
}
 
Example 19
Source File: TransportBindingHandler.java    From steady with Apache License 2.0 4 votes vote down vote up
private byte[] doDerivedKeySignature(
    boolean tokenIncluded,
    SecurityToken secTok,
    Token token,
    List<WSEncryptionPart> sigParts
) throws Exception {
    //Do Signature with derived keys
    WSSecDKSign dkSign = new WSSecDKSign(wssConfig);
    AlgorithmSuite algorithmSuite = tbinding.getAlgorithmSuite();

    //Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (tokenIncluded) {
        ref = secTok.getAttachedReference();
    } else {
        ref = secTok.getUnattachedReference();
    }

    if (ref != null) {
        dkSign.setExternalKey(secTok.getSecret(), cloneElement(ref));
    } else {
        dkSign.setExternalKey(secTok.getSecret(), secTok.getId());
    }
    
    if (token instanceof UsernameToken) {
        dkSign.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    } 

    // Set the algo info
    dkSign.setSignatureAlgorithm(algorithmSuite.getSymmetricSignature());
    dkSign.setDerivedKeyLength(algorithmSuite.getSignatureDerivedKeyLength() / 8);
    if (token.getSPConstants() == SP12Constants.INSTANCE) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
    }
    Document doc = saaj.getSOAPPart();
    dkSign.prepare(doc, secHeader);

    addDerivedKeyElement(dkSign.getdktElement());

    dkSign.setParts(sigParts);
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts, secHeader);

    //Do signature
    dkSign.computeSignature(referenceList, false, null);

    return dkSign.getSignatureValue();
}