Package com.sun.xml.wss.impl

Examples of com.sun.xml.wss.impl.SecurableSoapMessage


            FilterProcessingContext contextthrows XWSSecurityException {
       
        Key returnKey;
        //HashMap tokenCache = context.getTokenCache();
        try {
            SecurableSoapMessage secureMsg = context.getSecurableSoapMessage();
            if (keyInfo.containsSecurityTokenReference()) {
                return processSecurityTokenReference(keyInfo,sig, context);
            }else if (keyInfo.containsKeyName()) {
                EncryptionPolicy policy = (EncryptionPolicy)context.getInferredPolicy();
               
View Full Code Here


    @SuppressWarnings("unchecked")
    public static Key processSecurityTokenReference(KeyInfoHeaderBlock keyInfo,
            boolean sig, FilterProcessingContext context)throws XWSSecurityException{
        Key returnKey = null;
        HashMap tokenCache = context.getTokenCache();
        SecurableSoapMessage secureMsg = context.getSecurableSoapMessage();
        SecurityTokenReference str = keyInfo.getSecurityTokenReference(0);
        ReferenceElement refElement = str.getReference();
        EncryptionPolicy policy = (EncryptionPolicy)context.getInferredPolicy();
        EncryptionPolicy inferredEncryptionPolicy = null;
        boolean isWSITRecipient = (context.getMode()== FilterProcessingContext.WSDL_POLICY);
        try{
            if(isWSITRecipient){
                int i = context.getInferredSecurityPolicy().size() - 1;
                inferredEncryptionPolicy = (EncryptionPolicy)context.getInferredSecurityPolicy().get(i);
            }
        } catch(Exception e){
            log.log(Level.SEVERE, LogStringsMessages.WSS_0239_FAILED_PROCESS_SECURITY_TOKEN_REFERENCE(), e);
            throw new XWSSecurityException(e);
        }
        // Do a case analysis based on the type of refElement.
        // X509 Token Profile supports 3 kinds of reference mechanisms.
        // Embedded Reference not considered.
        if (refElement instanceof KeyIdentifier) {
            KeyIdentifier keyId = (KeyIdentifier)refElement;
           
            if (MessageConstants.X509SubjectKeyIdentifier_NS.equals(keyId.getValueType()) ||
                    MessageConstants.X509v3SubjectKeyIdentifier_NS.equals(keyId.getValueType())) {
                if(policy != null){
                    AuthenticationTokenPolicy.X509CertificateBinding keyBinding = null;
                    keyBinding = (AuthenticationTokenPolicy.X509CertificateBinding) policy.newX509CertificateKeyBinding();
                    keyBinding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                }
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    x509Binding.setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
                    x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                    if(inferredKB == null){
                        inferredEncryptionPolicy.setKeyBinding(x509Binding);
                    } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                        ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding)inferredKB;
                        if(dktBind.getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                        else if(PolicyTypeUtil.symmetricKeyBinding(dktBind.getOriginalKeyBinding())){
                            dktBind.getOriginalKeyBinding().setKeyBinding(x509Binding);
                        }
                    }
                   
                }
                if (sig) {
                    returnKey =
                            context.getSecurityEnvironment().getPublicKey(context.getExtraneousProperties(),
                            getDecodedBase64EncodedData(keyId.getReferenceValue()));
                } else {
                    returnKey =
                            context.getSecurityEnvironment().getPrivateKey(context.getExtraneousProperties(),
                            getDecodedBase64EncodedData(keyId.getReferenceValue()));
                }
               
            } else if (MessageConstants.ThumbPrintIdentifier_NS.equals(keyId.getValueType())) {
                if(policy != null){
                    AuthenticationTokenPolicy.X509CertificateBinding keyBinding = null;
                    keyBinding = (AuthenticationTokenPolicy.X509CertificateBinding) policy.newX509CertificateKeyBinding();
                    keyBinding.setReferenceType(MessageConstants.THUMB_PRINT_TYPE);
                }
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    x509Binding.setValueType(MessageConstants.ThumbPrintIdentifier_NS);
                    x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                    if(inferredKB == null){
                        inferredEncryptionPolicy.setKeyBinding(x509Binding);
                    } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                        ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding)inferredKB;
                        if(dktBind.getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                        else if(PolicyTypeUtil.symmetricKeyBinding(dktBind.getOriginalKeyBinding())){
                            dktBind.getOriginalKeyBinding().setKeyBinding(x509Binding);
                        }
                    }
                   
                }
                if (sig) {
                    returnKey =
                            context.getSecurityEnvironment().getPublicKey(
                            context.getExtraneousProperties(),
                            getDecodedBase64EncodedData(keyId.getReferenceValue()),
                            MessageConstants.THUMB_PRINT_TYPE
                            );
                } else {
                    returnKey =
                            context.getSecurityEnvironment().getPrivateKey(
                            context.getExtraneousProperties(),
                            getDecodedBase64EncodedData(keyId.getReferenceValue()),
                            MessageConstants.THUMB_PRINT_TYPE
                            );
                }
               
            } else if(MessageConstants.EncryptedKeyIdentifier_NS.equals(keyId.getValueType())){
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                    SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                    skBinding.setKeyBinding(x509Binding);
                    //TODO: ReferenceType and ValueType not set on X509Binding
                    if(inferredKB == null){
                        inferredEncryptionPolicy.setKeyBinding(skBinding);
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(skBinding);
                    }
                }
                String ekSha1RefValue = (String)context.getExtraneousProperty("EncryptedKeySHA1");
                Key secretKey = (Key)context.getExtraneousProperty("SecretKey");
                String keyRefValue = keyId.getReferenceValue();
                if(ekSha1RefValue != null && secretKey != null){
                    if(ekSha1RefValue.equals(keyRefValue))
                        returnKey = secretKey;
                } else{
                    String message = "EncryptedKeySHA1 reference not correct";
                    log.log(Level.SEVERE, LogStringsMessages.WSS_0240_INVALID_ENCRYPTED_KEY_SHA_1_REFERENCE());
                    throw new XWSSecurityException(message);
                }
               
            } else if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE.equals(keyId.getValueType())
            || MessageConstants.WSSE_SAML_v2_0_KEY_IDENTIFIER_VALUE_TYPE.equals(keyId.getValueType())) {
                // Its a SAML Assertion, retrieve the assertion
                if(policy != null){
                    AuthenticationTokenPolicy.SAMLAssertionBinding keyBinding = null;
                    keyBinding = (AuthenticationTokenPolicy.SAMLAssertionBinding) policy.newSAMLAssertionKeyBinding();
                    keyBinding.setReferenceType(keyId.getValueType());
                }
                String assertionID = keyId.getDecodedReferenceValue();
                Element samlAssertion = resolveSAMLToken(str, assertionID,context);
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                    IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
                    if(inferredKB == null){
                        if (context.hasIssuedToken()){
                            inferredEncryptionPolicy.setKeyBinding(itkBinding);
                        }else{
                            inferredEncryptionPolicy.setKeyBinding(new AuthenticationTokenPolicy.SAMLAssertionBinding());
                        }
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(itkBinding);
                    }
                }
                returnKey = resolveSamlAssertion(secureMsg,samlAssertion, sig,context, assertionID);
                if (context.hasIssuedToken() && returnKey != null){
                    SecurityUtil.initInferredIssuedTokenContext(context,str, returnKey);
                }
               
            } else {
                if(policy != null){
                    AuthenticationTokenPolicy.SAMLAssertionBinding keyBinding = null;
                    keyBinding = (AuthenticationTokenPolicy.SAMLAssertionBinding) policy.newSAMLAssertionKeyBinding();
                }
                Element samlAssertion = null;
                String assertionID = keyId.getDecodedReferenceValue();
                try{
                    samlAssertion = resolveSAMLToken(str, assertionID,context);
                }catch(Exception ex){
                    //ignore
                }
                if (samlAssertion != null) {
                    if(isWSITRecipient){
                        MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                        IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
                        if(inferredKB == null){
                            inferredEncryptionPolicy.setKeyBinding(itkBinding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(itkBinding);
                        }
                    }
                    returnKey = resolveSamlAssertion(secureMsg,samlAssertion, sig,context, assertionID);
                    if (context.hasIssuedToken() && returnKey != null){
                        SecurityUtil.initInferredIssuedTokenContext(context,str, returnKey);
                    }
                } else {
                    // now assume its an X509Token
                    // Note: the code below assumes base64 EncodingType for X509 SKI
                    if(isWSITRecipient){
                        MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
                        x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                        if(inferredKB == null){
                            inferredEncryptionPolicy.setKeyBinding(x509Binding);
                        } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                            ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding)inferredKB;
                            if(dktBind.getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                            else if(PolicyTypeUtil.symmetricKeyBinding(dktBind.getOriginalKeyBinding())){
                                dktBind.getOriginalKeyBinding().setKeyBinding(x509Binding);
                            }
                        }
                       
                    }
                    if (sig) {
                        returnKey =
                                context.getSecurityEnvironment().getPublicKey(context.getExtraneousProperties(),
                                getDecodedBase64EncodedData(keyId.getReferenceValue()));
                    } else {
                        returnKey =
                                context.getSecurityEnvironment().getPrivateKey(context.getExtraneousProperties(),
                                getDecodedBase64EncodedData(keyId.getReferenceValue()));
                    }
                }
            }
        } else if (refElement instanceof DirectReference) {
            String uri = ((DirectReference) refElement).getURI();
           
            // will be only during verify.
            AuthenticationTokenPolicy.X509CertificateBinding keyBinding = null;
            String valueType = ((DirectReference) refElement).getValueType();
            if (MessageConstants.DKT_VALUETYPE.equals(valueType) ||
                    MessageConstants.DKT_13_VALUETYPE.equals(valueType)){
                //TODO: this will work for now but need to handle this case here later
                valueType = null;
            }
           
            if(policy != null){
                keyBinding = (AuthenticationTokenPolicy.X509CertificateBinding) policy.newX509CertificateKeyBinding();
                keyBinding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                keyBinding.setValueType(valueType);
            }
           
            if (MessageConstants.X509v3_NS.equals(valueType)||MessageConstants.X509v1_NS.equals(valueType)) {
                // its an X509 Token
                HashMap insertedX509Cache = context.getInsertedX509Cache();
                String wsuId = secureMsg.getIdFromFragmentRef(uri);
                X509SecurityToken token = (X509SecurityToken)insertedX509Cache.get(wsuId);
                if(token == null)
                    token =(X509SecurityToken)resolveToken(wsuId,context,secureMsg);
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    x509Binding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                    x509Binding.setValueType(valueType);
                    if(inferredKB == null){
                        inferredEncryptionPolicy.setKeyBinding(x509Binding);
                    } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                        ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                    } else  if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding)inferredKB;
                        if(dktBind.getOriginalKeyBinding() == null)
                            dktBind.setOriginalKeyBinding(x509Binding);
                        else if(PolicyTypeUtil.symmetricKeyBinding(dktBind.getOriginalKeyBinding()))
                            dktBind.getOriginalKeyBinding().setKeyBinding(x509Binding);
                    }
                   
                }
                returnKey = resolveX509Token(secureMsg, token, sig,context);
               
            } else if(MessageConstants.EncryptedKey_NS.equals(valueType)){
                // Do default processing
                String wsuId = secureMsg.getIdFromFragmentRef(uri);
                SecurityToken token =resolveToken(wsuId,context,secureMsg);
                //TODO: STR is referring to EncryptedKey
                KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken)token).getKeyInfo();
                SecurityTokenReference sectr = kiHB.getSecurityTokenReference(0);
               
                //String dataEncAlgo = MessageConstants.AES_BLOCK_ENCRYPTION_128;
                // now that context will have AlgoSuite under WSIT, this should not be an issue
                // so restoring old value since it breaks Backward Compat otherwise
                String dataEncAlgo = MessageConstants.DEFAULT_DATA_ENC_ALGO;
                if (context.getAlgorithmSuite() != null) {
                    dataEncAlgo = context.getAlgorithmSuite().getEncryptionAlgorithm();
                }else{
                    if (context.getDataEncryptionAlgorithm() != null){
                        dataEncAlgo = context.getDataEncryptionAlgorithm();
                    }
                }
                try{
                    Element cipherData = (Element)((EncryptedKeyToken)token).getAsSoapElement().getChildElements(new QName(MessageConstants.XENC_NS, "CipherData", MessageConstants.XENC_PREFIX)).next();
                    String cipherValue = cipherData.getElementsByTagNameNS(MessageConstants.XENC_NS, "CipherValue").item(0).getTextContent();
                    byte[] decodedCipher = Base64.decode(cipherValue);
                    byte[] ekSha1 = MessageDigest.getInstance("SHA-1").digest(decodedCipher);
                    String encEkSha1 = Base64.encode(ekSha1);
                    context.setExtraneousProperty(MessageConstants.EK_SHA1_VALUE, encEkSha1);
                   
                } catch(Exception e){
                    log.log(Level.SEVERE, LogStringsMessages.WSS_0241_UNABLETO_SET_EKSHA_1_ON_CONTEXT(), e);
                    throw new XWSSecurityException(e);
                }
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                    SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    skBinding.setKeyBinding(x509Binding);
                    //TODO: ReferenceType and ValueType not set on X509Binding
                    if(inferredKB == null){
                        inferredEncryptionPolicy.setKeyBinding(skBinding);
                    } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                        ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding)inferredKB;
                        if(dktBind.getOriginalKeyBinding() == null)
                            dktBind.setOriginalKeyBinding(x509Binding);
                        else if(PolicyTypeUtil.symmetricKeyBinding(dktBind.getOriginalKeyBinding()))
                            dktBind.getOriginalKeyBinding().setKeyBinding(x509Binding);
                    }
                   
                }
                returnKey = ((EncryptedKeyToken)token).getSecretKey(getKey(kiHB, sig, context), dataEncAlgo);
                context.setExtraneousProperty(MessageConstants.SECRET_KEY_VALUE, returnKey);
               
            } else if (MessageConstants.SCT_VALUETYPE.equals(valueType) || MessageConstants.SCT_13_VALUETYPE.equals(valueType)) {
                // could be wsuId or SCT Session Id
                String sctId = secureMsg.getIdFromFragmentRef(uri);
                SecurityToken token = (SecurityToken)tokenCache.get(sctId);
               
                if(token == null){
                    token = SecurityUtil.locateBySCTId(context, uri);
                    if (token == null) {
                        token = resolveToken(sctId, context, secureMsg);
                    }
                    if(token == null){
                        log.log(Level.SEVERE, LogStringsMessages.WSS_0242_UNABLETO_LOCATE_SCT());
                        throw new XWSSecurityException("SCT Token with Id "+sctId+ "not found");
                    }else{
                        tokenCache.put(sctId, token);
                    }
                }
               
                if (token instanceof SecurityContextToken) {
                    //handling for SecurityContext Token
                    byte[] proofKey = resolveSCT(context, (SecurityContextTokenImpl)token, sig);
                    String encAlgo = "AES"; //hardcoding for now
                    if (context.getAlgorithmSuite() != null) {
                        encAlgo = SecurityUtil.getSecretKeyAlgorithm(context.getAlgorithmSuite().getEncryptionAlgorithm());
                    }
                    if(isWSITRecipient){
                        MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                        SecureConversationTokenKeyBinding sctBinding = new SecureConversationTokenKeyBinding();
                        if(inferredKB == null){
                            inferredEncryptionPolicy.setKeyBinding(sctBinding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(sctBinding);
                        }
                    }
                    returnKey = new SecretKeySpec(proofKey, encAlgo);
                   
                } else {
                    log.log(Level.SEVERE, LogStringsMessages.WSS_0243_INVALID_VALUE_TYPE_NON_SCT_TOKEN());
                    throw new XWSSecurityException("Incorrect ValueType: " + MessageConstants.SCT_VALUETYPE + ", specified for a Non SCT Token");
                }
               
            } else if (null == valueType) {
                // Do default processing
                String wsuId = secureMsg.getIdFromFragmentRef(uri);
                SecurityToken token = SecurityUtil.locateBySCTId(context, wsuId);
                if (token == null) {
                    token =resolveToken(wsuId,context,secureMsg);
                }
                if (token instanceof X509SecurityToken) {
View Full Code Here

        String dataEncAlgo = MessageConstants.AES_BLOCK_ENCRYPTION_128;
        if (context.getAlgorithmSuite() != null) {
            dataEncAlgo = context.getAlgorithmSuite().getEncryptionAlgorithm();
        }
        //HashMap tokenCache = context.getTokenCache();
        SecurableSoapMessage secureMsg = context.getSecurableSoapMessage();
       
        EncryptionPolicy inferredEncryptionPolicy = null;
        boolean isWSITRecipient = (context.getMode()== FilterProcessingContext.WSDL_POLICY);
        try{
            if(isWSITRecipient){
                int i = context.getInferredSecurityPolicy().size() - 1;
                inferredEncryptionPolicy = (EncryptionPolicy)context.getInferredSecurityPolicy().get(i);
            }
        } catch(Exception e){
            log.log(Level.SEVERE, LogStringsMessages.WSS_0247_FAILED_RESOLVE_DERIVED_KEY_TOKEN());
            throw new XWSSecurityException(e);
        }
       
       
        SecurityTokenReference sectr = token.getDerivedKeyElement();
        if (sectr == null) {
            log.log(Level.SEVERE, LogStringsMessages.WSS_0248_NULL_STR());
            throw new XWSSecurityException("Invalid DerivedKey Token encountered, no STR found");
        }
        ReferenceElement refElement = sectr.getReference();
        Key encKey = null;
        byte[] secret = null;
        if (refElement instanceof DirectReference) {
            String uri = ((DirectReference) refElement).getURI();
            String valueType = ((DirectReference) refElement).getValueType();
            String wsuId = secureMsg.getIdFromFragmentRef(uri);
            SecurityToken secToken = SecurityUtil.locateBySCTId(context, wsuId);
            if (secToken == null) {
                secToken =resolveToken(wsuId,context,secureMsg);
                //workaround for case where Reference does not have ValueType
                if ((valueType == null) && (secToken instanceof EncryptedKeyToken)){
View Full Code Here

    @SuppressWarnings("unchecked")
    public static Key processSTR(KeyInfoHeaderBlock keyInfo,
            boolean sig, FilterProcessingContext context)throws XWSSecurityException{
        Key returnKey = null;
        HashMap tokenCache = context.getTokenCache();
        SecurableSoapMessage secureMsg = context.getSecurableSoapMessage();
        SecurityTokenReference str = keyInfo.getSecurityTokenReference(0);
        ReferenceElement refElement = str.getReference();
        SignaturePolicy policy = (SignaturePolicy)context.getInferredPolicy();
        SignaturePolicy inferredSignaturePolicy = null;
        boolean isWSITRecipient = (context.getMode()== FilterProcessingContext.WSDL_POLICY);
        try{
            if(isWSITRecipient){
                int i = context.getInferredSecurityPolicy().size() - 1;
                inferredSignaturePolicy = (SignaturePolicy)context.getInferredSecurityPolicy().get(i);
            }
        } catch(Exception e){
            log.log(Level.SEVERE, LogStringsMessages.WSS_0250_FAILED_PROCESS_STR(), e);
            throw new XWSSecurityException(e);
        }
        // Do a case analysis based on the type of refElement.
        // X509 Token Profile supports 3 kinds of reference mechanisms.
        // Embedded Reference not considered.
        if (refElement instanceof KeyIdentifier) {
            KeyIdentifier keyId = (KeyIdentifier)refElement;
           
            if (MessageConstants.X509SubjectKeyIdentifier_NS.equals(keyId.getValueType()) ||
                    MessageConstants.X509v3SubjectKeyIdentifier_NS.equals(keyId.getValueType())) {
                if(policy != null){
                    AuthenticationTokenPolicy.X509CertificateBinding keyBinding = null;
                    keyBinding = (AuthenticationTokenPolicy.X509CertificateBinding) policy.newX509CertificateKeyBinding();
                    keyBinding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                }
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    x509Binding.setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
                    x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                    if(inferredKB == null){
                        inferredSignaturePolicy.setKeyBinding(x509Binding);
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                    }
                }
                if (sig) {
                    returnKey =
                            context.getSecurityEnvironment().getPublicKey(context.getExtraneousProperties(),
                            getDecodedBase64EncodedData(keyId.getReferenceValue()));
                } else {
                    returnKey =
                            context.getSecurityEnvironment().getPrivateKey(context.getExtraneousProperties(),
                            getDecodedBase64EncodedData(keyId.getReferenceValue()));
                }
               
            } else if (MessageConstants.ThumbPrintIdentifier_NS.equals(keyId.getValueType())) {
                if(policy != null){
                    AuthenticationTokenPolicy.X509CertificateBinding keyBinding = null;
                    keyBinding = (AuthenticationTokenPolicy.X509CertificateBinding) policy.newX509CertificateKeyBinding();
                    keyBinding.setReferenceType(MessageConstants.THUMB_PRINT_TYPE);
                }
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    x509Binding.setValueType(MessageConstants.ThumbPrintIdentifier_NS);
                    x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                    if(inferredKB == null){
                        inferredSignaturePolicy.setKeyBinding(x509Binding);
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                    }
                }
                if (sig) {
                    returnKey =
                            context.getSecurityEnvironment().getPublicKey(
                            context.getExtraneousProperties(),
                            getDecodedBase64EncodedData(keyId.getReferenceValue()),
                            MessageConstants.THUMB_PRINT_TYPE
                            );
                } else {
                    returnKey =
                            context.getSecurityEnvironment().getPrivateKey(
                            context.getExtraneousProperties(),
                            getDecodedBase64EncodedData(keyId.getReferenceValue()),
                            MessageConstants.THUMB_PRINT_TYPE
                            );
                }
               
            } else if(MessageConstants.EncryptedKeyIdentifier_NS.equals(keyId.getValueType())){
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                    SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    skBinding.setKeyBinding(x509Binding);
                    //TODO: ReferenceType and ValueType not set on X509Binding
                    if(inferredKB == null){
                        inferredSignaturePolicy.setKeyBinding(skBinding);
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(skBinding);
                    }
                }
                String ekSha1RefValue = (String)context.getExtraneousProperty("EncryptedKeySHA1");
                Key secretKey = (Key)context.getExtraneousProperty("SecretKey");
                String keyRefValue = keyId.getReferenceValue();
                if(ekSha1RefValue != null && secretKey != null){
                    if(ekSha1RefValue.equals(keyRefValue))
                        returnKey = secretKey;
                } else{
                    log.log(Level.SEVERE, LogStringsMessages.WSS_0240_INVALID_ENCRYPTED_KEY_SHA_1_REFERENCE());
                    String message = "EncryptedKeySHA1 reference not correct";
                    throw new XWSSecurityException(message);
                }
               
            } else if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE.equals(keyId.getValueType()) ||
                    MessageConstants.WSSE_SAML_v2_0_KEY_IDENTIFIER_VALUE_TYPE.equals(keyId.getValueType())) {
                // Its a SAML Assertion, retrieve the assertion
                if(policy != null){
                    AuthenticationTokenPolicy.SAMLAssertionBinding keyBinding = null;
                    keyBinding = (AuthenticationTokenPolicy.SAMLAssertionBinding) policy.newSAMLAssertionKeyBinding();
                    keyBinding.setReferenceType(keyId.getValueType());
                }
               
                String assertionID = keyId.getDecodedReferenceValue();
                Element samlAssertion = resolveSAMLToken(str, assertionID,context);
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                    IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
                    if(inferredKB == null){
                        if (context.hasIssuedToken()){
                            inferredSignaturePolicy.setKeyBinding(itkBinding);
                        }else{
                            inferredSignaturePolicy.setKeyBinding(new AuthenticationTokenPolicy.SAMLAssertionBinding());
                        }
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(itkBinding);
                    }
                }
                returnKey = resolveSamlAssertion(secureMsg,samlAssertion, sig,context, assertionID);
                if (context.hasIssuedToken() && returnKey != null){
                    SecurityUtil.initInferredIssuedTokenContext(context,str, returnKey);
                }
               
            } else {
                if(policy != null){
                    AuthenticationTokenPolicy.SAMLAssertionBinding keyBinding = null;
                    keyBinding = (AuthenticationTokenPolicy.SAMLAssertionBinding) policy.newSAMLAssertionKeyBinding();
                }
                Element samlAssertion = null;
                String assertionID = keyId.getDecodedReferenceValue();
                try{
                    samlAssertion = resolveSAMLToken(str, assertionID,context);
                }catch(Exception ex){
                    //ignore
                }
                if (samlAssertion != null) {
                    if(isWSITRecipient){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
                        if(inferredKB == null){
                            if (context.hasIssuedToken()){
                                inferredSignaturePolicy.setKeyBinding(itkBinding);
                            }else{
                                inferredSignaturePolicy.setKeyBinding(new AuthenticationTokenPolicy.SAMLAssertionBinding());
                            }
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(itkBinding);
                        }
                    }
                    returnKey = resolveSamlAssertion(secureMsg,samlAssertion, sig,context, assertionID);
                    if (context.hasIssuedToken() && returnKey != null){
                        SecurityUtil.initInferredIssuedTokenContext(context,str, returnKey);
                    }
                } else {
                    // now assume its an X509Token
                    // Note: the code below assumes base64 EncodingType for X509 SKI
                    if(isWSITRecipient){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
                        x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                        if(inferredKB == null){
                            inferredSignaturePolicy.setKeyBinding(x509Binding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                        }
                    }
                    if (sig) {
                        returnKey =
                                context.getSecurityEnvironment().getPublicKey(context.getExtraneousProperties(),
                                getDecodedBase64EncodedData(keyId.getReferenceValue()));
                    } else {
                        returnKey =
                                context.getSecurityEnvironment().getPrivateKey(context.getExtraneousProperties(),
                                getDecodedBase64EncodedData(keyId.getReferenceValue()));
                    }
                }
            }
        } else if (refElement instanceof DirectReference) {
            String uri = ((DirectReference) refElement).getURI();
           
            // will be only during verify.
            AuthenticationTokenPolicy.X509CertificateBinding keyBinding = null;
            String valueType = ((DirectReference) refElement).getValueType();
            if (MessageConstants.DKT_VALUETYPE.equals(valueType) ||
                    MessageConstants.DKT_13_VALUETYPE.equals(valueType)){
                //TODO: this will work for now but need to handle this case here later
                valueType = null;
            }
           
            if(policy != null){
                keyBinding = (AuthenticationTokenPolicy.X509CertificateBinding) policy.newX509CertificateKeyBinding();
                keyBinding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                keyBinding.setValueType(valueType);
            }
           
            if (MessageConstants.X509v3_NS.equals(valueType)||MessageConstants.X509v1_NS.equals(valueType)) {
                // its an X509 Token
                HashMap insertedX509Cache = context.getInsertedX509Cache();
                String wsuId = secureMsg.getIdFromFragmentRef(uri);
                X509SecurityToken token = (X509SecurityToken)insertedX509Cache.get(wsuId);
                if(token == null)
                    token =(X509SecurityToken)resolveToken(wsuId,context,secureMsg);
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    x509Binding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                    x509Binding.setValueType(valueType);
                    if(inferredKB == null){
                        inferredSignaturePolicy.setKeyBinding(x509Binding);
                    } else  if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                    }
                }
                returnKey = resolveX509Token(secureMsg, token, sig,context);
               
            } else if(MessageConstants.EncryptedKey_NS.equals(valueType)){
                // Do default processing
                String wsuId = secureMsg.getIdFromFragmentRef(uri);
                SecurityToken token =resolveToken(wsuId,context,secureMsg);
                //TODO: STR is referring to EncryptedKey
                KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken)token).getKeyInfo();
                SecurityTokenReference sectr = kiHB.getSecurityTokenReference(0);
               
                //TODO: PLUGFEST Algorithm hardcoded for now
                //String dataEncAlgo = MessageConstants.AES_BLOCK_ENCRYPTION_128;
                // restore Backward compatibility
                String dataEncAlgo = MessageConstants.DEFAULT_DATA_ENC_ALGO;
                if (context.getAlgorithmSuite() != null) {
                    dataEncAlgo = context.getAlgorithmSuite().getEncryptionAlgorithm();
                }else{
                    if (context.getDataEncryptionAlgorithm() != null){
                        dataEncAlgo = context.getDataEncryptionAlgorithm();
                    }
                }
                try{
                    Element cipherData = (Element)((EncryptedKeyToken)token).getAsSoapElement().getChildElements(new QName(MessageConstants.XENC_NS, "CipherData", MessageConstants.XENC_PREFIX)).next();
                    String cipherValue = cipherData.getElementsByTagNameNS(MessageConstants.XENC_NS, "CipherValue").item(0).getTextContent();
                    byte[] decodedCipher = Base64.decode(cipherValue);
                    byte[] ekSha1 = MessageDigest.getInstance("SHA-1").digest(decodedCipher);
                    String encEkSha1 = Base64.encode(ekSha1);
                    context.setExtraneousProperty(MessageConstants.EK_SHA1_VALUE, encEkSha1);
                } catch(Exception e){
                    log.log(Level.SEVERE, LogStringsMessages.WSS_0241_UNABLETO_SET_EKSHA_1_ON_CONTEXT(), e);
                    throw new XWSSecurityException(e);
                }
                if(isWSITRecipient){
                    MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                    SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    skBinding.setKeyBinding(x509Binding);
                    //TODO: ReferenceType and ValueType not set on X509Binding
                    if(inferredKB == null){
                        inferredSignaturePolicy.setKeyBinding(skBinding);
                    } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                        if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                            ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(skBinding);
                    }
                }
                returnKey = ((EncryptedKeyToken)token).getSecretKey(getKey(kiHB, sig, context), dataEncAlgo);
                context.setExtraneousProperty(MessageConstants.SECRET_KEY_VALUE, returnKey);
               
            } else if (MessageConstants.SCT_VALUETYPE.equals(valueType) || MessageConstants.SCT_13_VALUETYPE.equals(valueType)) {
                // could be wsuId or SCT Session Id
                String sctId = secureMsg.getIdFromFragmentRef(uri);
                SecurityToken token = (SecurityToken)tokenCache.get(sctId);
               
                if(token == null){
                    token = SecurityUtil.locateBySCTId(context, uri);
                    if (token == null) {
                        token = resolveToken(sctId, context, secureMsg);
                    }
                    if(token == null){
                        log.log(Level.SEVERE, LogStringsMessages.WSS_0242_UNABLETO_LOCATE_SCT());
                        throw new XWSSecurityException("SCT Token with Id "+sctId+ "not found");
                    }else{
                        tokenCache.put(sctId, token);
                    }
                }
               
                if (token instanceof SecurityContextToken) {
                    //handling for SecurityContext Token
                    byte[] proofKey = resolveSCT(context, (SecurityContextTokenImpl)token, sig);
                    String encAlgo = "AES"; //hardcoding for now
                    if (context.getAlgorithmSuite() != null) {
                        encAlgo = SecurityUtil.getSecretKeyAlgorithm(context.getAlgorithmSuite().getEncryptionAlgorithm());
                    }
                    if(isWSITRecipient){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        SecureConversationTokenKeyBinding sctBinding = new SecureConversationTokenKeyBinding();
                        if(inferredKB == null){
                            inferredSignaturePolicy.setKeyBinding(sctBinding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(sctBinding);
                        }
                    }
                    returnKey = new SecretKeySpec(proofKey, encAlgo);
                   
                } else {
                    log.log(Level.SEVERE, LogStringsMessages.WSS_0243_INVALID_VALUE_TYPE_NON_SCT_TOKEN());
                    throw new XWSSecurityException("Incorrect ValueType: " + MessageConstants.SCT_VALUETYPE + ", specified for a Non SCT Token");
                }
               
            } else if (null == valueType) {
                // Do default processing
                String wsuId = secureMsg.getIdFromFragmentRef(uri);
                SecurityToken token = SecurityUtil.locateBySCTId(context, wsuId);
                if (token == null) {
                    token =resolveToken(wsuId,context,secureMsg);
                }
                if (token instanceof X509SecurityToken) {
View Full Code Here

        try{
            SignaturePolicy signaturePolicy  = (SignaturePolicy)context.getSecurityPolicy();
            SOAPMessage soapMessage = context.getSOAPMessage();
            //Dependant on secure soap meesage.
            //discuss and refactor.
            SecurableSoapMessage secureMessage = context.getSecurableSoapMessage();
            WSSPolicy keyBinding = (WSSPolicy)signaturePolicy.getKeyBinding();
            if(logger.isLoggable(Level.FINEST)){
                logger.log(Level.FINEST, "KeyBinding is "+keyBinding);
            }
           
            Key signingKey = null;
            Node nextSibling =  null;
            //TODO :: Creation of WSSPolicyConsumerImpl every time.
            WSSPolicyConsumerImpl dsigHelper = WSSPolicyConsumerImpl.getInstance();
            KeyInfo keyInfo = null;
            SecurityHeader securityHeader = secureMessage.findOrCreateSecurityHeader();
           
            SignaturePolicy.FeatureBinding featureBinding =
                    (SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding();
            AlgorithmSuite algSuite = context.getAlgorithmSuite();
           
            boolean wss11Receiver = "true".equals(context.getExtraneousProperty("EnableWSS11PolicyReceiver"));
            boolean wss11Sender = "true".equals(context.getExtraneousProperty("EnableWSS11PolicySender"));
            boolean wss10 = !wss11Sender;
            boolean sendEKSHA1 =  wss11Receiver && wss11Sender && (getEKSHA1Ref(context) != null);
           
            if (PolicyTypeUtil.usernameTokenPolicy(keyBinding)) {
                logger.log(Level.SEVERE, LogStringsMessages.WSS_1326_UNSUPPORTED_USERNAMETOKEN_KEYBINDING());
                throw new XWSSecurityException("UsernameToken as KeyBinding for SignaturePolicy is Not Yet Supported");
            } else if ( PolicyTypeUtil.derivedTokenKeyBinding(keyBinding)) {
                DerivedTokenKeyBinding dtk = (DerivedTokenKeyBinding)keyBinding.clone();
               
                WSSPolicy originalKeyBinding = dtk.getOriginalKeyBinding();
               
                String algorithm = null;
                if(algSuite != null){
                    algorithm = algSuite.getEncryptionAlgorithm();
                }
                String jceAlgo = SecurityUtil.getSecretKeyAlgorithm(algorithm);
                //The offset and length to be used for DKT
                //TODO: PLUGFEST the length here should be set correctly
                long offset = 0; // Default 0
                long length = SecurityUtil.getLengthFromAlgorithm(algorithm);
                if(length == 32) length = 24;
               
                if (PolicyTypeUtil.x509CertificateBinding(originalKeyBinding)) {
                    // this is becuase SecurityPolicy Converter never produces this combination
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1327_UNSUPPORTED_ASYMMETRICBINDING_DERIVEDKEY_X_509_TOKEN());
                    throw new XWSSecurityException("Asymmetric Binding with DerivedKeys under X509Token Policy Not Yet Supported");
                } else if ( PolicyTypeUtil.symmetricKeyBinding(originalKeyBinding)) {
                   
                    SymmetricKeyBinding skb = null;
                    if ( context.getSymmetricKeyBinding() != null) {
                        skb = context.getSymmetricKeyBinding();
                        context.setSymmetricKeyBinding(null);
                    }
                    //Construct a derivedKeyToken to be used
                    Key originalKey = null;
                    if(context.getCurrentSecret() != null){
                        originalKey = context.getCurrentSecret();
                    }else{
                        originalKey = skb.getSecretKey();
                        context.setCurrentSecret(originalKey);
                    }
                    byte[] secret = originalKey.getEncoded();
                    DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, secret);
                    //get the signing key for signature from derivedkeyToken
                    signingKey = dkt.generateSymmetricKey(jceAlgo);
                   
                    Node[] nxtSiblingContainer = new Node[1];
                    keyInfo = prepareForSymmetricKeySignature(context, keyBinding, originalKey, signaturePolicy, nxtSiblingContainer, null, dkt);
                    nextSibling = nxtSiblingContainer[0];
                   
                } else if ( PolicyTypeUtil.issuedTokenKeyBinding(originalKeyBinding)) {
                    byte[] prfKey = context.getTrustContext().getProofKey();
                    if (prfKey == null) {
                        //handle Asymmetric Issued Token
                        X509Certificate cert =
                                context.getTrustContext().getRequestorCertificate();
                        if (cert == null){
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1328_ILLEGAL_CERTIFICATE_KEY_NULL());
                            throw new XWSSecurityException(
                                    "Requestor Certificate and Proof Key are both null for Issued Token");
                        }
                        signingKey = context.getSecurityEnvironment().
                                getPrivateKey(context.getExtraneousProperties(), cert);
                       
                        //Get the IssuedToken and insert it into the message
                        GenericToken issuedToken =
                                (GenericToken)context.getTrustContext().getSecurityToken();
                        Element elem = (Element)issuedToken.getTokenValue();
                        SOAPElement tokenElem =
                                XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                        //FIX for Issue 26: We need an Id to cache and MS is not setting in
                        //some cases
                        String tokId = tokenElem.getAttribute("Id");
                        if ("".equals(tokId) &&
                                MessageConstants.ENCRYPTED_DATA_LNAME.equals(
                                tokenElem.getLocalName())) {
                            tokenElem.setAttribute("Id", secureMessage.generateId());
                        }
                        context.getTokenCache().put(keyBinding.getUUID(), tokenElem);
                        IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)originalKeyBinding;
                        String iTokenType = ikb.getIncludeToken();
                        boolean includeToken =  (ikb.INCLUDE_ALWAYS_TO_RECIPIENT.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS_VER2.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(iTokenType)
                                                );
                        Element strElem = null;
                       
                        if (includeToken) {
                            strElem =(Element)context.getTrustContext().
                                    getAttachedSecurityTokenReference().getTokenValue();
                        }else  {
                            strElem = (Element)context.getTrustContext().
                                    getUnAttachedSecurityTokenReference().getTokenValue();
                        }
                        //TODO: remove these expensive conversions
                        Element imported = (Element)
                        secureMessage.getSOAPPart().importNode(strElem,true);
                        SecurityTokenReference str = new SecurityTokenReference(
                                XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(),
                                (Element)imported.cloneNode(true)), false);
                       
                        if (tokenElem != null) {
                            if(includeToken) {
                                secureMessage.findOrCreateSecurityHeader().
                                        insertHeaderBlockElement(tokenElem);
                                nextSibling = tokenElem.getNextSibling();
                               
                            } else {
                                nextSibling =  null;
                            }
                            context.setIssuedSAMLToken(tokenElem);
                        }
                        keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,str);
                        SecurityUtil.updateSamlVsKeyCache(str, context, cert.getPublicKey());
                    } else {
                        DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, prfKey);
                        signingKey = dkt.generateSymmetricKey(jceAlgo);
                        Node[] nxtSiblingContainer = new Node[1];
                        //NOTE: passing the proofKey here as original key
                        String secretKeyAlg = "AES";
                        if (algSuite != null) {
                            secretKeyAlg = SecurityUtil.getSecretKeyAlgorithm(algSuite.getEncryptionAlgorithm());
                        }
                        Key originalKey = new SecretKeySpec(prfKey, secretKeyAlg);
                        keyInfo = prepareForSymmetricKeySignature(
                                context, keyBinding, originalKey, signaturePolicy, nxtSiblingContainer, null, dkt);
                        nextSibling = nxtSiblingContainer[0];
                    }
                } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(originalKeyBinding)) {
                   
                    DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, context.getSecureConversationContext().getProofKey());
                    //get the signing key for signature from derivedkeyToken
                    signingKey = dkt.generateSymmetricKey(jceAlgo);
                    Node[] nxtSiblingContainer = new Node[1];
                    keyInfo = prepareForSymmetricKeySignature(context, keyBinding, null, signaturePolicy, nxtSiblingContainer, null, dkt);
                    nextSibling = nxtSiblingContainer[0];
                }
               
            } else if ( PolicyTypeUtil.issuedTokenKeyBinding(keyBinding)) {
                Node[] nxtSiblingContainer = new Node[1];
                // look for the proof token inside the IssuedToken
                byte[] proofKey = context.getTrustContext().getProofKey();
                if (proofKey == null) {
                    //handle Asymmetric Issued Token
                    X509Certificate cert =
                            context.getTrustContext().getRequestorCertificate();
                    if (cert == null){
                        logger.log(Level.SEVERE,LogStringsMessages.WSS_1328_ILLEGAL_CERTIFICATE_KEY_NULL());
                        throw new XWSSecurityException(
                                "Requestor Certificate and Proof Key are both null for Issued Token");
                    }
                    signingKey = context.getSecurityEnvironment().
                            getPrivateKey(context.getExtraneousProperties(), cert);
                   
                    //Get the IssuedToken and insert it into the message
                    GenericToken issuedToken =
                            (GenericToken)context.getTrustContext().getSecurityToken();
                    Element elem = (Element)issuedToken.getTokenValue();
                    SOAPElement tokenElem =
                            XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                    //FIX for Issue 26: We need an Id to cache and MS is not setting in
                    //some cases
                    String tokId = tokenElem.getAttribute("Id");
                    if ("".equals(tokId) &&
                            MessageConstants.ENCRYPTED_DATA_LNAME.equals(
                            tokenElem.getLocalName())) {
                        tokenElem.setAttribute("Id", secureMessage.generateId());
                    }
                    context.getTokenCache().put(keyBinding.getUUID(), tokenElem);
                    IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)keyBinding;
                    String iTokenType = ikb.getIncludeToken();
                    boolean includeToken =  (ikb.INCLUDE_ALWAYS_TO_RECIPIENT.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS_VER2.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(iTokenType)
                                                );
                    Element strElem = null;
                   
                    if (includeToken) {
                        strElem =(Element)context.getTrustContext().
                                getAttachedSecurityTokenReference().getTokenValue();
                    }else  {
                        strElem = (Element)context.getTrustContext().
                                getUnAttachedSecurityTokenReference().getTokenValue();
                    }
                    //TODO: remove these expensive conversions
                    Element imported = (Element)
                    secureMessage.getSOAPPart().importNode(strElem,true);
                    SecurityTokenReference str = new SecurityTokenReference(
                            XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(),
                            (Element)imported.cloneNode(true)), false);
                   
                    if (tokenElem != null) {
                        if(includeToken) {
                            secureMessage.findOrCreateSecurityHeader().
                                    insertHeaderBlockElement(tokenElem);
                            nextSibling = tokenElem.getNextSibling();
                           
                        } else {
                            nextSibling =  null;
                        }
                        context.setIssuedSAMLToken(tokenElem);
                    }
                    keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,str);
                    SecurityUtil.updateSamlVsKeyCache(str, context, cert.getPublicKey());
                } else {
                    // symmetric issued
                    String secretKeyAlg = "AES"; // hardcoding to AES for now
                    if (algSuite != null) {
                        secretKeyAlg = SecurityUtil.getSecretKeyAlgorithm(algSuite.getEncryptionAlgorithm());
                    }
                    //TODO: assuming proofkey is a byte array in case of Trust as well
                    signingKey = new SecretKeySpec(proofKey, secretKeyAlg);
                    keyInfo = prepareForSymmetricKeySignature(
                            context, keyBinding, signingKey, signaturePolicy, nxtSiblingContainer, null, null);
                    nextSibling = nxtSiblingContainer[0];
                }
               
            } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(keyBinding)) {
               
                //Hack to get the nextSibling node from prepareForSymmetricKeySignature
                Node[] nxtSiblingContainer = new Node[1];
                keyInfo = prepareForSymmetricKeySignature(
                        context, keyBinding, null, signaturePolicy, nxtSiblingContainer, null, null);
               
                // look for the proof token inside the secureConversationToken
                String secretKeyAlg = "AES"; // hardcoding to AES for now
                if (algSuite != null) {
                    secretKeyAlg = SecurityUtil.getSecretKeyAlgorithm(algSuite.getEncryptionAlgorithm());
                }
                signingKey = new SecretKeySpec(context.getSecureConversationContext().getProofKey(), secretKeyAlg);
                nextSibling = nxtSiblingContainer[0];
               
            } else if(PolicyTypeUtil.x509CertificateBinding(keyBinding)) {
               
                AuthenticationTokenPolicy.X509CertificateBinding certInfo = null;
                if ( context.getX509CertificateBinding() != null ) {
                    certInfo = context.getX509CertificateBinding();
                    context.setX509CertificateBinding(null);
                } else {
                    certInfo = (AuthenticationTokenPolicy.X509CertificateBinding)keyBinding;
                }
               
                PrivateKeyBinding privKBinding  = (PrivateKeyBinding)certInfo.getKeyBinding();
                signingKey = privKBinding.getPrivateKey();
               
                Node[] nxtSiblingContainer = new Node[1];
                keyInfo = handleX509Binding(context, signaturePolicy, certInfo, nxtSiblingContainer);
                nextSibling = nxtSiblingContainer[0];
               
            } else if (PolicyTypeUtil.samlTokenPolicy(keyBinding)) {
                // populate the policy, the handler should also add a privateKey binding for HOK
               
                AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding =
                        (AuthenticationTokenPolicy.SAMLAssertionBinding)keyBinding;
                PrivateKeyBinding privKBinding  = (PrivateKeyBinding)samlBinding.getKeyBinding();
                if (privKBinding == null) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1329_NULL_PRIVATEKEYBINDING_SAML_POLICY());
                    throw new XWSSecurityException("PrivateKey binding not set for SAML Policy by CallbackHandler");
                }
               
                signingKey = privKBinding.getPrivateKey();
               
                if (signingKey == null) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1330_NULL_PRIVATEKEY_SAML_POLICY());
                    throw new XWSSecurityException("PrivateKey null inside PrivateKeyBinding set for SAML Policy ");
                }
               
                String referenceType = samlBinding.getReferenceType();
                if (referenceType.equals(MessageConstants.EMBEDDED_REFERENCE_TYPE)) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1331_UNSUPPORTED_EMBEDDED_REFERENCE_SAML());
                    throw new XWSSecurityException("Embedded Reference Type for SAML Assertions not supported yet");
                }
               
                String assertionId = samlBinding.getAssertionId();
                Element _assertion = samlBinding.getAssertion();
                Element _authorityBinding = samlBinding.getAuthorityBinding();
               
                if (assertionId == null) {
                    if (_assertion == null) {
                        logger.log(Level.SEVERE, LogStringsMessages.WSS_1332_NULL_SAML_ASSERTION_SAML_ASSERTION_ID());
                        throw new XWSSecurityException(
                                "None of SAML Assertion, SAML Assertion Id information was set into " +
                                " the Policy by the CallbackHandler");
                    }
                    if(_assertion.getAttributeNode("ID") != null){
                        assertionId = _assertion.getAttribute("ID");
                    }else{
                        assertionId = _assertion.getAttribute("AssertionID");
                    }
                }
               
                SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                String strId = samlBinding.getSTRID();
                if(strId == null){
                    strId = secureMessage.generateId();
                }
                tokenRef.setWsuId(strId);
                // set wsse11:TokenType to SAML1.1 or SAML2.0
                if(_assertion.getAttributeNode("ID") != null){
                    tokenRef.setTokenType(MessageConstants.WSSE_SAML_v2_0_TOKEN_TYPE);
                }else{
                    tokenRef.setTokenType(MessageConstants.WSSE_SAML_v1_1_TOKEN_TYPE);
                }
               
                if (_authorityBinding != null) {
                    tokenRef.setSamlAuthorityBinding(_authorityBinding,
                            secureMessage.getSOAPPart());
                }
               
                if ((_assertion != null) && (_authorityBinding == null)) {
                    //insert the SAML Assertion
                    SamlAssertionHeaderBlock samlHeaderblock =
                            new SamlAssertionHeaderBlock(_assertion, secureMessage.getSOAPPart());
                    secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(samlHeaderblock);
                    // setting ValueType of Keydentifier to SAML1.1 0r SAML2.0
                    KeyIdentifierStrategy strat = new KeyIdentifierStrategy(assertionId);
                    strat.insertKey(tokenRef, secureMessage);
                    keyInfo = dsigHelper.constructKeyInfo(signaturePolicy, tokenRef);
                   
                    nextSibling = samlHeaderblock.getAsSoapElement().getNextSibling();
                } else {
                    nextSibling = securityHeader.getNextSiblingOfTimestamp();
                }
            }else if(PolicyTypeUtil.symmetricKeyBinding(keyBinding)){
                SymmetricKeyBinding skb = null;
                if ( context.getSymmetricKeyBinding() != null) {
                    skb = context.getSymmetricKeyBinding();
                    context.setSymmetricKeyBinding(null);
                } else {
                    skb = (SymmetricKeyBinding)keyBinding;
                }
               
                // sign method is HMACSHA-1 for symmetric keys
                if(!skb.getKeyIdentifier().equals(MessageConstants._EMPTY)){
                    signingKey = skb.getSecretKey();
                    String symmetricKeyName = skb.getKeyIdentifier();
                   
                    keyInfo = dsigHelper.constructKeyInfo(signaturePolicy, symmetricKeyName);
                    nextSibling = securityHeader.getNextSiblingOfTimestamp();
                } else if(sendEKSHA1){
                    //get the signing key and EKSHA1 reference from the Subject, it was stored from the incoming message
                    String ekSha1Ref = getEKSHA1Ref(context);
                    signingKey = skb.getSecretKey();
                   
                    SecurityTokenReference secTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                   
                    EncryptedKeySHA1Identifier refElem = new EncryptedKeySHA1Identifier(secureMessage.getSOAPPart());
                    refElem.setReferenceValue(ekSha1Ref);
                    secTokenRef.setReference(refElem);
                   
                    //set the wsse11:TokenType attribute as required by WSS 1.1
                    //secTokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
                   
                    keyInfo = dsigHelper.constructKeyInfo(signaturePolicy, secTokenRef);
                    nextSibling = securityHeader.getNextSiblingOfTimestamp();
                   
                    //TODO: the below condition is always true
                }else if(wss11Sender || wss10){
                    signingKey = skb.getSecretKey();
                   
                    AuthenticationTokenPolicy.X509CertificateBinding x509Binding = null;
                    X509Certificate cert = null;
                    if(!skb.getCertAlias().equals(MessageConstants._EMPTY)){
                        x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.newPrivateKeyBinding();
                        x509Binding.setCertificateIdentifier(skb.getCertAlias());
                        cert = context.getSecurityEnvironment().getCertificate(context.getExtraneousProperties(), x509Binding.getCertificateIdentifier(), false);
                        x509Binding.setX509Certificate(cert);
                       
                        x509Binding.setReferenceType("Direct");
                    }else if ( context.getX509CertificateBinding() != null ) {
                        x509Binding = context.getX509CertificateBinding();
                        context.setX509CertificateBinding(null);
                        cert = x509Binding.getX509Certificate();
                    }
                   
                    HashMap tokenCache = context.getTokenCache();
                    HashMap insertedX509Cache = context.getInsertedX509Cache();
                    String x509id = x509Binding.getUUID();
                    if(x509id == null || x509id.equals("")){
                        x509id = secureMessage.generateId();
                    }
                   
                    SecurityUtil.checkIncludeTokenPolicy(context, x509Binding, x509id);
                   
                    String keyEncAlgo = XMLCipher.RSA_v1dot5;  //<--Harcoding of Algo
                    String tmp = null;
                    if(algSuite != null){
                        tmp = algSuite.getAsymmetricKeyAlgorithm();
                    }
                    if(tmp != null && !"".equals(tmp)){
                        keyEncAlgo = tmp;
                    }
                    String referenceType =  x509Binding.getReferenceType();
                    if(referenceType.equals("Identifier") && x509Binding.getValueType().equals(MessageConstants.X509v1_NS)){
                        logger.log(Level.SEVERE, LogStringsMessages.WSS_1333_UNSUPPORTED_KEYIDENTIFER_X_509_V_1());
                        throw new XWSSecurityException("Key Identifier strategy in X509v1 is not supported");
                    }
                    KeyInfoStrategy  strategy = KeyInfoStrategy.getInstance(referenceType);
                    KeyInfoHeaderBlock keyInfoBlock  = null;
                    secureMessage = context.getSecurableSoapMessage();
                    dsigHelper = WSSPolicyConsumerImpl.getInstance();
                   
                    //Check to see if same x509 token used for Signature and Encryption
                    X509SecurityToken token = null;
                    cert = x509Binding.getX509Certificate();
                    String x509TokenId = x509Binding.getUUID();
                    //String x509TokenId = x509Binding.getPolicyToken().getTokenId();
                    boolean tokenInserted = false;
                   
                    //insert x509 token in tokencache always irrespective of reference type
                    if(x509TokenId == null || x509TokenId.equals("")){
                        x509TokenId = secureMessage.generateId();
                    }
                   
                    token = (X509SecurityToken)tokenCache.get(x509TokenId);
                   
                    //reference type adjustment in checkIncludePolicy might
                    // have inserted x509
                    X509SecurityToken insertedx509 =
                            (X509SecurityToken)context.getInsertedX509Cache().get(x509TokenId);
                   
                    if (token == null) {
                        String valueType = x509Binding.getValueType();
                        if(valueType==null||valueType.equals("")){
                            //default valueType for X509 as v3
                            valueType = MessageConstants.X509v3_NS;
                        }
                        token = new X509SecurityToken(secureMessage.getSOAPPart(), cert, x509TokenId, valueType);
                        tokenCache.put(x509TokenId, token);
                    } else{
                        tokenInserted = true;
                    }
                    String id = null;
                    HashMap ekCache = context.getEncryptedKeyCache();
                    if(!tokenInserted){
                        context.setCurrentSecret(signingKey);
                        //Store SymmetricKey generated in ProcessingContext
                        context.setExtraneousProperty("SecretKey", signingKey);
                        keyInfoBlock = new KeyInfoHeaderBlock(secureMessage.getSOAPPart());
                        strategy.setCertificate(cert);
                        strategy.insertKey(keyInfoBlock, secureMessage, x509TokenId);
                        com.sun.org.apache.xml.internal.security.keys.KeyInfo apacheKeyInfo = keyInfoBlock.getKeyInfo();
                        //create an encrypted Key
                        EncryptedKey encryptedKey = null;
                        XMLCipher keyEncryptor = null;
                        try{
                            keyEncryptor = XMLCipher.getInstance(keyEncAlgo);
                            keyEncryptor.init(XMLCipher.WRAP_MODE, cert.getPublicKey());
                            if (keyEncryptor != null) {
                                encryptedKey = keyEncryptor.encryptKey(secureMessage.getSOAPPart(), signingKey);
                            }
                        }catch(Exception e){
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1334_ERROR_CREATING_ENCRYPTEDKEY());
                            throw new XWSSecurityException(e);
                        }
                        id = secureMessage.generateId();
                        encryptedKey.setId(id);
                        ekCache.put(x509TokenId, id);
                        // set its KeyInfo
                        encryptedKey.setKeyInfo(apacheKeyInfo);
                       
                        // insert the EK into the SOAPMessage
                        SOAPElement se = (SOAPElement)keyEncryptor.martial(encryptedKey);
                        if (insertedx509 == null) {
                            secureMessage.findOrCreateSecurityHeader().insertHeaderBlockElement(se);
                        } else {
                            secureMessage.findOrCreateSecurityHeader().insertBefore(se,insertedx509.getNextSibling());
                        }
                       
                        //store EKSHA1 of KeyValue contents in context
                        Element cipherData = (Element)se.getChildElements(new QName(MessageConstants.XENC_NS, "CipherData", MessageConstants.XENC_PREFIX)).next();
                        String cipherValue = cipherData.getElementsByTagNameNS(MessageConstants.XENC_NS, "CipherValue").item(0).getTextContent();
                        byte[] decodedCipher = Base64.decode(cipherValue);
                        byte[] ekSha1 = MessageDigest.getInstance("SHA-1").digest(decodedCipher);
                        String encEkSha1 = Base64.encode(ekSha1);
                        context.setExtraneousProperty("EncryptedKeySHA1", encEkSha1);
                        nextSibling = se.getNextSibling();
                    } else{
                       
                        id = (String)ekCache.get(x509TokenId);
                        signingKey = context.getCurrentSecret();
                        nextSibling = secureMessage.getElementById(id).getNextSibling();
                    }
                    //insert the token as the first child in SecurityHeader -- if same token was not already
                    // inserted by Encryption
                    if (MessageConstants.DIRECT_REFERENCE_TYPE.equals(referenceType) && insertedx509 == null){
                        secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(token);
                        insertedX509Cache.put(x509TokenId, token);
                    }
                   
                    //STR for the KeyInfo of signature
                    SecurityTokenReference secTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    DirectReference reference = new DirectReference();
                    String strId = x509Binding.getSTRID();
                    if(strId == null){
                        strId = secureMessage.generateId();
                    }
                    secTokenRef.setWsuId(strId);
                    //TODO: PLUGFEST Microsoft setting EK on reference inseatd of STR
                    //secTokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
                    //set id of encrypted key
View Full Code Here

        ArrayList optionalReferenceList = new ArrayList();
        //It would have been better If I had optional list
        //seperated
       
        Iterator targetItr = targets.iterator();
        SecurableSoapMessage secureMessage = context.getSecurableSoapMessage();
        while(targetItr.hasNext()){
            SignatureTarget signatureTarget = (SignatureTarget) targetItr.next();
            boolean requiredTarget = signatureTarget.getEnforce();
            List referenceList = null;
            try{
View Full Code Here

        }
       
        String referenceType =  null;
        KeyInfoStrategy  strategy = null;
        KeyInfoHeaderBlock keyInfoBlock  = null;
        SecurableSoapMessage secureMessage = context.getSecurableSoapMessage();
        SecurityHeader securityHeader = secureMessage.findOrCreateSecurityHeader();
       
        WSSPolicyConsumerImpl dsigHelper = WSSPolicyConsumerImpl.getInstance();
       
        boolean wss11Receiver = "true".equals(context.getExtraneousProperty("EnableWSS11PolicyReceiver"));
        boolean wss11Sender = "true".equals(context.getExtraneousProperty("EnableWSS11PolicySender"));
        boolean sendEKSHA1 =  wss11Receiver && wss11Sender&& (getEKSHA1Ref(context) != null);
        boolean wss10 = !wss11Sender;
       
        try {
            if ( PolicyTypeUtil.derivedTokenKeyBinding(keyBinding)) {
                DerivedTokenKeyBinding dtk = (DerivedTokenKeyBinding)keyBinding.clone();
               
                WSSPolicy originalKeyBinding = dtk.getOriginalKeyBinding();
               
                if (PolicyTypeUtil.x509CertificateBinding(originalKeyBinding)) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1327_UNSUPPORTED_ASYMMETRICBINDING_DERIVEDKEY_X_509_TOKEN());
                    throw new XWSSecurityException("Asymmetric Binding with DerivedKeys under X509Token Policy Not Yet Supported");
                } else  if ( PolicyTypeUtil.symmetricKeyBinding(originalKeyBinding)) {
                   
                    if(sendEKSHA1){
                        String ekSha1Ref = getEKSHA1Ref(context);
                       
                        //STR for DerivedKeyToken
                        SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                        EncryptedKeySHA1Identifier refElem = new EncryptedKeySHA1Identifier(secureMessage.getSOAPPart());
                        refElem.setReferenceValue(ekSha1Ref);
                        tokenRef.setReference(refElem);
                        //set the wsse11:TokenType attribute as required by WSS 1.1
                        //tokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
                        //TODO: Temporary fix for signing
                        String dktId = keyBinding.getUUID();
                        if (dktId == null) {
                            dktId = secureMessage.generateId();
                        }
                        String nonce = Base64.encode(dkt.getNonce());
                        DerivedKeyTokenHeaderBlock dktHeadrBlock =
                                new DerivedKeyTokenHeaderBlock(securityHeader.getOwnerDocument(), tokenRef, nonce, dkt.getOffset(), dkt.getLength() ,dktId);
                        // insert the derivedKey into SecurityHeader
                        secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(dktHeadrBlock);
                        // set the next sibling to next sibling of derived key token
                        nextSibling = dktHeadrBlock.getAsSoapElement().getNextSibling();
                        nxtSiblingContainer[0] = nextSibling;
                       
                        //Construct the STR for signature
                        DirectReference reference = new DirectReference();
                        reference.setURI("#"+dktId);
                        SecurityTokenReference sigTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                        sigTokenRef.setReference(reference);
                        keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,sigTokenRef);
                       
                        return keyInfo;
                       
                    } else if(wss11Sender || wss10){
                       
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = null;
                        X509Certificate cert = null;
                        if ( context.getX509CertificateBinding() != null ) {
                            x509Binding = context.getX509CertificateBinding();
                            context.setX509CertificateBinding(null);
                        }
                       
                        HashMap tokenCache = context.getTokenCache();
                        HashMap insertedX509Cache = context.getInsertedX509Cache();
                        String x509id = x509Binding.getUUID();
                        if(x509id == null || x509id.equals("")){
                            x509id = secureMessage.generateId();
                        }
                       
                        SecurityUtil.checkIncludeTokenPolicy(context, x509Binding, x509id);
                       
                        referenceType =  x509Binding.getReferenceType();
                        strategy = KeyInfoStrategy.getInstance(referenceType);
                        X509SecurityToken token = null;
                        cert = x509Binding.getX509Certificate();
                        String x509TokenId = x509Binding.getUUID();
                        //Check to see if same x509 token used for Signature and Encryption
                        boolean tokenInserted = false;
                       
                        if(x509TokenId == null || x509TokenId.equals("")){
                            x509TokenId = secureMessage.generateId();
                        }
                        // ReferenceType adjustment in checkIncludeTokenPolicy is also currently
                        // causing an insertion of the X509 into the Message
                        X509SecurityToken insertedx509 =
                                (X509SecurityToken)context.getInsertedX509Cache().get(x509TokenId);
                       
                        // this one is used to determine if the whole BST + EK + DKT(opt)
                        // has been inserted by another filter such as Encryption running before
                        token = (X509SecurityToken)tokenCache.get(x509TokenId);
                        if (token == null) {
                            if (insertedx509 != null) {
                                token = insertedx509;
                                tokenCache.put(x509TokenId, insertedx509);
                            } else {
                                String valueType = x509Binding.getValueType();
                                if(valueType==null||valueType.equals("")){
                                    //default valueType for X509 as v3
                                    valueType = MessageConstants.X509v3_NS;
                                }
                                token = new X509SecurityToken(secureMessage.getSOAPPart(), cert, x509TokenId, valueType);
                                tokenCache.put(x509TokenId, token);
                            }
                            context.setCurrentSecret(originalKey);
                        } else{
                            tokenInserted = true;
                        }
                       
                        String dktId = keyBinding.getUUID();
                        if (dktId == null) {
                            dktId = secureMessage.generateId();
                        }
                        String nonce = Base64.encode(dkt.getNonce());
                        HashMap ekCache = context.getEncryptedKeyCache();
                        String ekId = (String)ekCache.get(x509TokenId);
                        EncryptedKey encryptedKey = null;
                        XMLCipher keyEncryptor = null;
                        if(!tokenInserted){
                            //Store SymmetricKey generated in ProcessingContext
                            context.setExtraneousProperty("SecretKey", originalKey); //this is the originalKey
                            //keyinfo for encryptedKey
                            keyInfoBlock = new KeyInfoHeaderBlock(secureMessage.getSOAPPart());
                            strategy.setCertificate(cert);
                            strategy.insertKey(keyInfoBlock, secureMessage, x509TokenId);
                            com.sun.org.apache.xml.internal.security.keys.KeyInfo apacheKeyInfo = keyInfoBlock.getKeyInfo();
                           
                           
                            //create an encrypted Key --- it encrypts the original key
                            try{
                                keyEncryptor = XMLCipher.getInstance(keyEncAlgo);
                                keyEncryptor.init(XMLCipher.WRAP_MODE, cert.getPublicKey());
                                if (keyEncryptor != null) {
                                    encryptedKey = keyEncryptor.encryptKey(secureMessage.getSOAPPart(), originalKey);
                                }
                            }catch(Exception e){
                                logger.log(Level.SEVERE, LogStringsMessages.WSS_1335_UNSUPPORTED_KEYBINDING_SIGNATUREPOLICY());
                                throw new XWSSecurityException(e);
                            }
                            ekId = secureMessage.generateId();
                            ekCache.put(x509TokenId, ekId);
                            encryptedKey.setId(ekId);
                            // set its KeyInfo
                            encryptedKey.setKeyInfo(apacheKeyInfo);
                        }
                       
                        //STR for DerivedKeyToken
                        SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                        DirectReference reference = new DirectReference();
                        //TODO: PLUGFEST commenting this as Microsoft puts Value type on reference itself
                        //tokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
                        //set id of encrypted key in STR of DKT
                        reference.setValueType(MessageConstants.EncryptedKey_NS);
                        reference.setURI("#"+ekId);
                        tokenRef.setReference(reference);
                        DerivedKeyTokenHeaderBlock dktHeadrBlock =
                                new DerivedKeyTokenHeaderBlock(securityHeader.getOwnerDocument(), tokenRef, nonce, dkt.getOffset(), dkt.getLength() ,dktId);
                       
                        if(!tokenInserted){
                            Node nsX509 = null;
                            if (insertedx509 != null) {
                                nsX509 = insertedx509.getNextSibling();
                            }
                            // move DKT below X509 if present
                            if (nsX509 == null) {
                                secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(dktHeadrBlock);
                            } else {
                                secureMessage.findOrCreateSecurityHeader().insertBefore(dktHeadrBlock, nsX509);
                            }
                            // move EK above DKT but below X509
                            if (insertedx509 != null) {
                                nsX509 = insertedx509.getNextSibling();
                            }
                           
                            // insert the EK into the SOAPMessage -  this goes on top of DKT Header block
                            SOAPElement se = (SOAPElement)keyEncryptor.martial(encryptedKey);
                            if (nsX509 == null) {
                                secureMessage.findOrCreateSecurityHeader().insertHeaderBlockElement(se);
                            }else {
                                secureMessage.findOrCreateSecurityHeader().insertBefore(se, nsX509);
                            }
                            //insert the token as the first child in SecurityHeader
                            if (MessageConstants.DIRECT_REFERENCE_TYPE.equals(referenceType) && insertedX509Cache.get(x509TokenId) == null){
                                secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(token);
                                insertedX509Cache.put(x509TokenId, token);
                            }
                            //store EKSHA1 of KeyValue contents in context
                            Element cipherData = (Element)se.getChildElements(new QName(MessageConstants.XENC_NS, "CipherData", MessageConstants.XENC_PREFIX)).next();
                            String cipherValue = cipherData.getElementsByTagNameNS(MessageConstants.XENC_NS, "CipherValue").item(0).getTextContent();
                            byte[] decodedCipher = Base64.decode(cipherValue);
                            byte[] ekSha1 = MessageDigest.getInstance("SHA-1").digest(decodedCipher);
                            String encEkSha1 = Base64.encode(ekSha1);
                            context.setExtraneousProperty("EncryptedKeySHA1", encEkSha1);
                        } else{
                            //insert derived key after the existing EK
                            Element ekElem = secureMessage.getElementById(ekId);
                            secureMessage.findOrCreateSecurityHeader().insertBefore(dktHeadrBlock, ekElem.getNextSibling());
                        }
                       
                        //Construct the STR for signature
                        DirectReference refSig = new DirectReference();
                        refSig.setURI("#"+dktId);
                        SecurityTokenReference sigTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                        sigTokenRef.setReference(refSig);
                        keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,sigTokenRef);
                       
                        // set the next sibling to next sibling of derived key token
                        nextSibling = dktHeadrBlock.getAsSoapElement().getNextSibling();
                        nxtSiblingContainer[0] = nextSibling;
                       
                        return keyInfo;
                       
                    }
                } else if ( PolicyTypeUtil.issuedTokenKeyBinding(originalKeyBinding)) {
                   
                    IssuedTokenKeyBinding itk = (IssuedTokenKeyBinding)originalKeyBinding;
                   
                    IssuedTokenContext issuedTokenContext =  context.getTrustContext();
                   
                    //Get the IssuedToken and insert it into the message
                    GenericToken issuedToken = (GenericToken)issuedTokenContext.getSecurityToken();
                    SOAPElement tokenElem =  null;
                    SecurityTokenReference str = null;
                    Element strElem = null;
                   
                    // check if the token is already present
                    IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)originalKeyBinding;
                    //String ikbPolicyId = ikb.getPolicyToken().getTokenId();
                    String ikbPolicyId = ikb.getUUID();
                   
                    //Look for TrustToken in TokenCache
                    HashMap tokCache = context.getTokenCache();
                    Object tok = tokCache.get(ikbPolicyId);
                    SOAPElement issuedTokenElementFromMsg = null;
                    String iTokenType = ikb.getIncludeToken();
                    boolean includeIST =  (ikb.INCLUDE_ALWAYS_TO_RECIPIENT.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS_VER2.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(iTokenType)
                                                );
                   
                    if (includeIST && (issuedToken == null)) {
                        logger.log(Level.SEVERE, LogStringsMessages.WSS_1343_NULL_ISSUED_TOKEN());
                        throw new XWSSecurityException("Issued Token to be inserted into the Message was Null");
                    }
                   
                    if (issuedToken != null) {
                        // treat the token as an Opaque entity and just insert the token into message
                        Element elem = (Element)issuedToken.getTokenValue();
                        if (tok == null) {
                            //TODO: remove these expensive conversions DOM Imports
                            tokenElem = XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                            //FIX for Issue 26: We need an Id to cache and MS is not setting in some cases
                            String tokId = tokenElem.getAttribute("Id");
                            if ("".equals(tokId) &&
                                    MessageConstants.ENCRYPTED_DATA_LNAME.equals(tokenElem.getLocalName())) {
                                tokenElem.setAttribute("Id", secureMessage.generateId());
                            }
                            tokCache.put(ikbPolicyId, tokenElem);
                        } else {
                            // it will be SOAPElement retrieve its wsuId attr
                            String wsuId = SecurityUtil.getWsuIdOrId((Element)tok);
                            issuedTokenElementFromMsg = (SOAPElement)secureMessage.getElementById(wsuId);
                            if (issuedTokenElementFromMsg == null) {
                                logger.log(Level.SEVERE,LogStringsMessages.WSS_1344_ERROR_LOCATE_ISSUE_TOKEN_MESSAGE());
                                throw new XWSSecurityException("Could not locate Issued Token in Message");
                            }
                        }
                    }
                   
                    if (includeIST) {
                        strElem = (Element)issuedTokenContext.getAttachedSecurityTokenReference().getTokenValue();
                    } else {
                        strElem = (Element)issuedTokenContext.getUnAttachedSecurityTokenReference().getTokenValue();
                    }
                   
                    //TODO: remove these expensive conversions
                    Element imported = (Element)secureMessage.getSOAPPart().importNode(strElem,true);
                    str = new SecurityTokenReference(XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), imported), false);
                   
                    if (originalKey != null) {
                        SecurityUtil.updateSamlVsKeyCache(str, context, originalKey);
                    }
                   
                    String dktId = keyBinding.getUUID();
                    if (dktId == null) {
                        dktId = secureMessage.generateId();
                    }
                   
                    DerivedKeyTokenHeaderBlock derivedKeyTokenHeaderBlock =
                            new DerivedKeyTokenHeaderBlock(
                            secureMessage.getSOAPPart(),
                            str,
                            Base64.encode(dkt.getNonce()),
                            dkt.getOffset(),
                            dkt.getLength(),
                            dktId);
                   
                   
                    if (issuedTokenElementFromMsg != null) {
                        SecurityHeader _secHeader = secureMessage.findOrCreateSecurityHeader();
                        _secHeader.insertBefore(derivedKeyTokenHeaderBlock, issuedTokenElementFromMsg.getNextSibling());
                    } else {
                        Node reflist = context.getCurrentRefList();
                        if (reflist != null) {
                            secureMessage.findOrCreateSecurityHeader().insertBefore(derivedKeyTokenHeaderBlock, reflist);
                            context.setCurrentReferenceList(null);
                        } else {
                            secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(derivedKeyTokenHeaderBlock);
                        }
                    }
                   
                    // insert the Issued Token after the DKT
                    if (tokenElem != null) {
                        if (includeIST) {
                            secureMessage.findOrCreateSecurityHeader().insertHeaderBlockElement(tokenElem);
                        }
                        // also store the token in Packet.invocationProperties to be used by
                        // client side response processing
                        context.setIssuedSAMLToken(tokenElem);
                    }
                   
                    //Construct the STR for signature
                    DirectReference refSig = new DirectReference();
                    refSig.setURI("#"+dktId);
                    SecurityTokenReference sigTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    sigTokenRef.setReference(refSig);
                    keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,sigTokenRef);
                   
                    // set the next sibling to next sibling of derived key token
                    nextSibling = derivedKeyTokenHeaderBlock.getAsSoapElement().getNextSibling();
                    nxtSiblingContainer[0] = nextSibling;
                    return keyInfo;
                   
                } else if ( PolicyTypeUtil.samlTokenPolicy(originalKeyBinding)) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1345_UNSUPPORTED_DERIVEDKEYS_SAML_TOKEN());
                    throw new UnsupportedOperationException("DerivedKeys with SAMLToken not yet supported");
                   
                } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(originalKeyBinding)) {
                    SecureConversationTokenKeyBinding sctBinding = (SecureConversationTokenKeyBinding)originalKeyBinding;
                    //STR for DerivedKeyToken
                    SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    SOAPElement sctElement = insertSCT(context, sctBinding, tokenRef);
                    String dktId = keyBinding.getUUID();
                    if (dktId == null) {
                        dktId = secureMessage.generateId();
                    }
                    String nonce = Base64.encode(dkt.getNonce());
                    DerivedKeyTokenHeaderBlock dktHeaderBlock =
                            new DerivedKeyTokenHeaderBlock(
                            securityHeader.getOwnerDocument(), tokenRef, nonce, dkt.getOffset(), dkt.getLength() ,dktId);
                   
                    Node next = (sctElement != null) ? sctElement.getNextSibling() : null;
                   
                    if (next == null) {
                        Node reflist = context.getCurrentRefList();
                        if (reflist != null) {
                            next = reflist;
                            context.setCurrentReferenceList(null);
                        }
                    }
                   
                    SOAPElement dktElem = (SOAPElement)securityHeader.insertBefore(
                            dktHeaderBlock.getAsSoapElement(), next);
                    //Construct the STR for signature
                    DirectReference refSig = new DirectReference();
                    refSig.setURI("#"+dktId);
                    SecurityTokenReference sigTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    sigTokenRef.setReference(refSig);
                   
                    // signature should be below DKT
                    nextSibling = dktElem.getNextSibling();
                    nxtSiblingContainer[0] = nextSibling;
                   
                    keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,sigTokenRef);
                    return keyInfo;
                }
               
            } else if ( PolicyTypeUtil.issuedTokenKeyBinding(keyBinding)) {
                //Get the IssuedToken and insert it into the message
                IssuedTokenContext issuedTokenContext =  context.getTrustContext();
                GenericToken issuedToken = (GenericToken)issuedTokenContext.getSecurityToken();
                SOAPElement tokenElem =  null;
                SecurityTokenReference str = null;
                Element strElem = null;
                SOAPElement issuedTokenElementFromMsg = null;
               
                // check if the token is already present
                IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)keyBinding;
                //String ikbPolicyId = ikb.getPolicyToken().getTokenId();
                String ikbPolicyId = ikb.getUUID();
               
                //Look for TrustToken in TokenCache
                HashMap tokCache = context.getTokenCache();
                Object tok = tokCache.get(ikbPolicyId);
                String iTokenType = ikb.getIncludeToken();
                boolean includeIST = (ikb.INCLUDE_ALWAYS_TO_RECIPIENT.equals(iTokenType) ||
                          ikb.INCLUDE_ALWAYS.equals(iTokenType) ||
                          ikb.INCLUDE_ALWAYS_VER2.equals(iTokenType) ||
                          ikb.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(iTokenType)
                          );
                if (includeIST && (issuedToken == null)) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1343_NULL_ISSUED_TOKEN());
                    throw new XWSSecurityException("Issued Token to be inserted into the Message was Null");
                }
               
                if (issuedToken != null) {
                    // treat the token as an Opaque entity and just insert the token into message
                    Element elem = (Element)issuedToken.getTokenValue();
                    if (tok == null) {
                        //TODO: remove these expensive conversions DOM Imports
                        tokenElem = XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                        //FIX for Issue 26: We need an Id to cache and MS is not setting in some cases
                        String tokId = tokenElem.getAttribute("Id");
                        if ("".equals(tokId) &&
                                MessageConstants.ENCRYPTED_DATA_LNAME.equals(tokenElem.getLocalName())) {
                            tokenElem.setAttribute("Id", secureMessage.generateId());
                        }
                        tokCache.put(ikbPolicyId, tokenElem);
                    } else {
                        // it will be SOAPElement retrieve its wsuId attr
                        String wsuId = SecurityUtil.getWsuIdOrId((Element)tok);
                        issuedTokenElementFromMsg = (SOAPElement)secureMessage.getElementById(wsuId);
                        if (issuedTokenElementFromMsg == null) {
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1344_ERROR_LOCATE_ISSUE_TOKEN_MESSAGE());
                            throw new XWSSecurityException("Could not locate Issued Token in Message");
                        }
                    }
                }
               
                if (includeIST) {
                    strElem = SecurityUtil.convertSTRToElement(issuedTokenContext.getAttachedSecurityTokenReference().getTokenValue(), secureMessage.getSOAPPart());
                } else {
                    strElem = SecurityUtil.convertSTRToElement(issuedTokenContext.getUnAttachedSecurityTokenReference().getTokenValue(), secureMessage.getSOAPPart());
                }
               
                if(strElem == null){
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1378_UNABLETO_REFER_ISSUE_TOKEN());
                    throw new XWSSecurityException("Cannot determine how to reference the Issued Token in the Message");
                }
               
                //TODO: remove these expensive conversions
                Element imported = (Element)secureMessage.getSOAPPart().importNode(strElem,true);
                str = new SecurityTokenReference(
                        XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), (Element)imported.cloneNode(true)), false);
               
                if (originalKey != null) {
                    SecurityUtil.updateSamlVsKeyCache(str, context, originalKey);
                }
               
                if (tokenElem != null) {
                    if(includeIST) {

                        secureMessage.findOrCreateSecurityHeader().insertHeaderBlockElement(tokenElem);
                        nxtSiblingContainer[0] = tokenElem.getNextSibling();
                    } else {
                        nxtSiblingContainer[0] null;
                    }
                    // also store the token in Packet.invocationProperties to be used by
                    // client side response processing
                    context.setIssuedSAMLToken(tokenElem);
                } else if (issuedTokenElementFromMsg != null) {
                    nxtSiblingContainer[0] = issuedTokenElementFromMsg.getNextSibling();
                }
               
                keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,str);
                return keyInfo;
               
            } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(keyBinding)){
               
                SecurityTokenReference secTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                SecureConversationTokenKeyBinding sctBinding = (SecureConversationTokenKeyBinding)keyBinding;
                SOAPElement sctElement = insertSCT(context, sctBinding, secTokenRef);
               
                // signature should be below SCT
                nextSibling = (sctElement != null) ? sctElement.getNextSibling() : null;
View Full Code Here

        return null;
    }
    @SuppressWarnings("unchecked")
    public static SOAPElement insertSCT(FilterProcessingContext context, SecureConversationTokenKeyBinding sctBinding, SecurityTokenReference secTokenRef)
    throws XWSSecurityException {
        SecurableSoapMessage secureMessage = context.getSecurableSoapMessage();
        //String sctPolicyId = sctBinding.getPolicyToken().getTokenId();
        String sctPolicyId = sctBinding.getUUID();
       
        //Look for SCT in TokenCache
        HashMap tokCache = context.getTokenCache();
        SecurityContextTokenImpl sct = null;
        sct = (SecurityContextTokenImpl)tokCache.get(sctPolicyId);
        boolean tokenInserted = false;
        SOAPElement sctElement = null;
       
        IssuedTokenContext ictx = context.getSecureConversationContext();
       
        if (sct == null) {
            SecurityContextToken sct1 =(SecurityContextToken)ictx.getSecurityToken();
            if (sct1 == null) {
                logger.log(Level.SEVERE, LogStringsMessages.WSS_1347_NULL_SECURE_CONVERSATION_TOKEN());
                throw new XWSSecurityException("SecureConversation Token not Found");
            }
           
            sct = new SecurityContextTokenImpl(
                    secureMessage.getSOAPPart(), sct1.getIdentifier().toString(), sct1.getInstance(), sct1.getWsuId(), sct1.getExtElements());
            // put back in token cache
            tokCache.put(sctPolicyId, sct);
        } else {
            tokenInserted = true;
            // record the element
            sctElement = secureMessage.getElementByWsuId(sct.getWsuId());
        }
       
        String sctWsuId = sct.getWsuId();
        if (sctWsuId == null) {
            sct.setId(secureMessage.generateId());
        }
        sctWsuId = sct.getWsuId();
        String iTokenType = sctBinding.getIncludeToken();
        if(sctBinding.INCLUDE_ALWAYS_TO_RECIPIENT.equals(iTokenType) ||
           sctBinding.INCLUDE_ALWAYS.equals(iTokenType) ||
           sctBinding.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(iTokenType) ||
           sctBinding.INCLUDE_ALWAYS_VER2.equals(iTokenType)) {
           
            if (!tokenInserted) {
                secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(sct);
                // record the element
                sctElement = secureMessage.getElementByWsuId(sct.getWsuId());
            }
           
            DirectReference reference = new DirectReference();
           
            reference.setURI("#" + sctWsuId);
View Full Code Here

            AuthenticationTokenPolicy.X509CertificateBinding certInfo,
            Node[] nxtSiblingContainer) throws XWSSecurityException{
       
        Node nextSibling = null;
        KeyInfo keyInfo = null;
        SecurableSoapMessage secureMessage = context.getSecurableSoapMessage();
        SecurityHeader securityHeader = secureMessage.findOrCreateSecurityHeader();
        WSSPolicyConsumerImpl dsigHelper = WSSPolicyConsumerImpl.getInstance();
       
        HashMap tokenCache = context.getTokenCache();
        HashMap insertedX509Cache = context.getInsertedX509Cache();
        String x509id = certInfo.getUUID();
        if(x509id == null || x509id.equals("")){
            x509id = secureMessage.generateId();
        }
       
        SecurityUtil.checkIncludeTokenPolicy(context, certInfo, x509id);
       
        String referenceType = certInfo.getReferenceType();
        String strId = certInfo.getSTRID();
        if(strId == null){
            strId = secureMessage.generateId();
        }
       
        try{
            if(referenceType.equals("Direct")){
                DirectReference reference = new DirectReference();
                // this is an X509 certificate binding
                String valueType= certInfo.getValueType();
                if(valueType==null||valueType.equals("")){
                    valueType=MessageConstants.X509v3_NS;
                   
                }
                reference.setValueType(valueType);
                //Use DirectReferenceStrategy -
                //Revisit :: Move is generation to filters.
                String id = certInfo.getUUID();
                if(id == null || id.equals("")){
                    id = secureMessage.generateId();
                }
                reference.setURI("#"+id);
                SecurityTokenReference secTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                secTokenRef.setReference(reference);
                secTokenRef.setWsuId(strId);
                keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,secTokenRef);
                X509SecurityToken token =  null;
                token = (X509SecurityToken)tokenCache.get(id);
                if(token == null){
                    valueType = certInfo.getValueType();
                    if(valueType==null||valueType.equals("")){
                        //default valueType for X509 as v3
                        valueType = MessageConstants.X509v3_NS;
                    }
                    token = new X509SecurityToken(secureMessage.getSOAPPart(),certInfo.getX509Certificate(),id, valueType);
                    tokenCache.put(id, token);
                }
                if(insertedX509Cache.get(id) == null){
                    secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(token);
                    insertedX509Cache.put(id, token);
                }
                nextSibling = token.getAsSoapElement().getNextSibling();
                nxtSiblingContainer[0] = nextSibling;
                return keyInfo;
            }else if(referenceType.equals("Identifier")){
                String valueType = certInfo.getValueType();
                if(valueType==MessageConstants.X509v1_NS||valueType.equals(MessageConstants.X509v1_NS)) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1333_UNSUPPORTED_KEYIDENTIFER_X_509_V_1());
                    throw new XWSSecurityException("Key Identifier reference Type is not allowed for X509v1 Certificates");
                }
                KeyIdentifierStrategy keyIdentifier =
                        new KeyIdentifierStrategy(certInfo.getCertificateIdentifier(),true);
                keyIdentifier.setCertificate(certInfo.getX509Certificate());
                SecurityTokenReference secTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                keyIdentifier.insertKey(secTokenRef, secureMessage);
                secTokenRef.setWsuId(strId);
                X509SubjectKeyIdentifier re = (X509SubjectKeyIdentifier)secTokenRef.getReference();
                String id = re.getReferenceValue();
                tokenCache.put(id, re);
                re.setCertificate(certInfo.getX509Certificate());
                keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,secTokenRef);
                nextSibling = securityHeader.getNextSiblingOfTimestamp();
                nxtSiblingContainer[0] = nextSibling;
                return keyInfo;
            }else if(referenceType.equals(MessageConstants.THUMB_PRINT_TYPE)){
                String valueType = certInfo.getValueType();
                if(valueType==MessageConstants.X509v1_NS||valueType.equals(MessageConstants.X509v1_NS)) {
                    logger.log(Level.SEVERE,LogStringsMessages.WSS_1348_ILLEGAL_THUMBPRINT_X_509_V_1());
                    throw new XWSSecurityException("Thumb reference Type is not allowed for X509v1 Certificates");
                }
                KeyIdentifierStrategy keyIdentifier = new KeyIdentifierStrategy(certInfo.getCertificateIdentifier(),true, true);
                keyIdentifier.setCertificate(certInfo.getX509Certificate());
                SecurityTokenReference secTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                keyIdentifier.insertKey(secTokenRef, secureMessage);
                secTokenRef.setWsuId(strId);
                X509ThumbPrintIdentifier re = (X509ThumbPrintIdentifier)secTokenRef.getReference();
                String id = re.getReferenceValue();
                tokenCache.put(id, re);
                re.setCertificate(certInfo.getX509Certificate());
                keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,secTokenRef);
                nextSibling = securityHeader.getNextSiblingOfTimestamp();
                nxtSiblingContainer[0] = nextSibling;
                return keyInfo;
            }else if(referenceType.equals(MessageConstants.X509_ISSUER_TYPE)){
                X509Certificate xCert = certInfo.getX509Certificate();
                X509IssuerSerial xis = new X509IssuerSerial(secureMessage.getSOAPPart(),
                        xCert.getIssuerDN().getName(),xCert.getSerialNumber());
                SecurityTokenReference secTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                secTokenRef.setReference(xis);
                secTokenRef.setWsuId(strId);
                xis.setCertificate(xCert);
                tokenCache.put(xis.getIssuerName()+xis.getSerialNumber(),xis);
                keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,secTokenRef);
View Full Code Here

            String valueType = certInfo.getValueType();
            if(valueType==null||valueType.equals("")){
                //default valueType for X509 as v3
                valueType = MessageConstants.X509v3_NS;
            }
            SecurableSoapMessage secureMessage = context.getSecurableSoapMessage();
            X509SecurityToken x509Token = new X509SecurityToken(secureMessage.getSOAPPart(),certInfo.getX509Certificate(), x509id, valueType);
            secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(x509Token);
            insertedX509Cache.put(x509id, x509Token);
            certInfo.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
            //}
        } catch(Exception e){
            throw new XWSSecurityException(e);
View Full Code Here

TOP

Related Classes of com.sun.xml.wss.impl.SecurableSoapMessage

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.