Package com.sun.xml.wss.core

Examples of com.sun.xml.wss.core.ReferenceElement


        FilterProcessingContext filterContext = (FilterProcessingContext)context.get (MessageConstants.WSS_PROCESSING_CONTEXT);
        SecurableSoapMessage secureMessage = filterContext.getSecurableSoapMessage ();
        Document soapDocument = secureMessage.getSOAPPart ();
        SOAPElement soapElem =  XMLUtil.convertToSoapElement (soapDocument, (Element) element);
        SecurityTokenReference tokenRef = new SecurityTokenReference (soapElem);
        ReferenceElement refElement =  tokenRef.getReference ();
        HashMap tokenCache = filterContext.getTokenCache ();
        Element tokenElement = null;
        Element newElement = null;
       
        if (refElement instanceof DirectReference) {
            // isXMLToken = true;
            /* Use the URI value to locate the BST */
            String uri = ((DirectReference) refElement).getURI ();
            String tokenId = uri.substring (1);
            secToken = (SecurityToken)tokenCache.get (tokenId);
            if(secToken == null){
                tokenElement = secureMessage.getElementById (tokenId);
                if(tokenElement == null){
                    throw new URIReferenceException ("Could not locate token with following ID"+tokenId);
                }
            
            } else {
                tokenElement = secToken.getAsSoapElement();
            }
            newElement = (Element)element.getOwnerDocument ().importNode (tokenElement, true);
           
        } else if (refElement instanceof KeyIdentifier) {
            String valueType = ((KeyIdentifier) refElement).getValueType ();
            String keyId = ((KeyIdentifier) refElement).getReferenceValue ();
            if (MessageConstants.X509SubjectKeyIdentifier_NS.
                    equals (valueType) ||
                    MessageConstants.X509v3SubjectKeyIdentifier_NS.
                    equals (valueType)) {
                /* Use the Subject Key Identifier to locate BST */
                //  isXMLToken = false;
                X509Certificate cert = null;
               
                Object token = tokenCache.get (keyId);
                if(token instanceof X509SubjectKeyIdentifier ){
                    if(token != null){
                        cert = ((X509SubjectKeyIdentifier)token).getCertificate ();
                    }
                }
               
                if(cert == null){
                    cert = filterContext.getSecurityEnvironment ().getCertificate (
                            filterContext.getExtraneousProperties (), XMLUtil.getDecodedBase64EncodedData (keyId));
                }
                secToken = new X509SecurityToken (soapDocument, cert);
                tokenElement = secToken.getAsSoapElement ();
                newElement = tokenElement;
                //(Element)element.getOwnerDocument().importNode(tokenElement, true);
                try {
                    // EncodingType should not be set -
                    // As specified by WSS spec
                    newElement.removeAttribute ("EncodingType");
                } catch (DOMException de) {
                    logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0607_STR_TRANSFORM_EXCEPTION());
                    throw new XWSSecurityRuntimeException (de.getMessage (), de);
                }
            } else if (MessageConstants.ThumbPrintIdentifier_NS.equals (valueType)) {
                X509Certificate cert = null;
               
                Object token = tokenCache.get (keyId);
                if(token instanceof X509ThumbPrintIdentifier ){
                    if(token != null){
                        cert = ((X509ThumbPrintIdentifier)token).getCertificate ();
                    }
                }
               
                if(cert == null){
                    cert = filterContext.getSecurityEnvironment ().getCertificate (
                            filterContext.getExtraneousProperties (), XMLUtil.getDecodedBase64EncodedData (keyId), MessageConstants.THUMB_PRINT_TYPE);
                }
                secToken = new X509SecurityToken (soapDocument, cert);
                tokenElement = secToken.getAsSoapElement ();
                newElement = tokenElement;
                //(Element)element.getOwnerDocument().importNode(tokenElement, true);
                try {
                    // EncodingType should not be set -
                    // As specified by WSS spec
                    newElement.removeAttribute ("EncodingType");
                } catch (DOMException de) {
                    logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0607_STR_TRANSFORM_EXCEPTION());
                    throw new XWSSecurityRuntimeException (de.getMessage (), de);
                }
            }else if(MessageConstants.EncryptedKeyIdentifier_NS.equals (valueType)){
                // do something here
                newElement = null;
            } else if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE.equals (valueType) ||
                     MessageConstants.WSSE_SAML_v2_0_KEY_IDENTIFIER_VALUE_TYPE.equals (valueType)) {
               
                //TODO : should we first try locating from the cache
                if (tokenRef.getSamlAuthorityBinding () != null) {
                    tokenElement = filterContext.getSecurityEnvironment ().
                            locateSAMLAssertion (
                            filterContext.getExtraneousProperties(), tokenRef.getSamlAuthorityBinding (), keyId, secureMessage.getSOAPPart ());
                } else {
                    tokenElement = SAMLUtil.locateSamlAssertion (keyId,secureMessage.getSOAPPart ());
                }
                newElement = (Element)element.getOwnerDocument ().importNode (tokenElement, true);
               
                Assertion assertion = null;
                try {
                    assertion = AssertionUtil.fromElement(tokenElement);
                } catch (Exception e) {
                    throw new XWSSecurityException (e);
                }
                tokenCache.put (keyId, assertion);
               
            } else {
                try {
                    tokenElement = resolveSAMLToken (tokenRef, keyId, filterContext);
                } catch (Exception e) {
                    // ignore
                }
                if (tokenElement != null) {
                    newElement = (Element)element.getOwnerDocument ().importNode (tokenElement, true);
                } else {
                    //TODO : there can be a X509 KeyIdentifier without ValueType
                    //    log.log(Level.SEVERE, "WSS0334.unsupported.keyidentifier");
                    XWSSecurityException xwsse =
                            new XWSSecurityException (
                            "WSS_DSIG0008:unsupported KeyIdentifier Reference Type "
                            + valueType);
                    throw SecurableSoapMessage.newSOAPFaultException (
                            MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
                            xwsse.getMessage (),
                            xwsse);
                }
            }
           
        } else if (refElement instanceof X509IssuerSerial) {
            //       isXMLToken = false;
            BigInteger serialNumber =
                    ((X509IssuerSerial) refElement).getSerialNumber ();
            String issuerName = ((X509IssuerSerial) refElement).getIssuerName ();
            X509Certificate cert =  null;
            Object token = tokenCache.get (issuerName+serialNumber);
            if(token instanceof X509IssuerSerial){
                cert = ((X509IssuerSerial)token).getCertificate ();
            }
           
            if(cert == null){
                cert = filterContext.getSecurityEnvironment ().getCertificate (
                        filterContext.getExtraneousProperties (),serialNumber, issuerName);
            }
            secToken = new X509SecurityToken (soapDocument, cert);
            tokenElement = secToken.getAsSoapElement ();
            newElement = tokenElement;
            //(Element)element.getOwnerDocument().importNode(tokenElement, true);
            try {
                // EncodingType should not be set - As specified by WSS spec
                newElement.removeAttribute ("EncodingType");
            } catch (DOMException de) {
                logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0607_STR_TRANSFORM_EXCEPTION());
                throw new XWSSecurityException (de.getMessage (), de);
            }
        } else {
            logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0608_DIAG_CAUSE_1());
            throw new XWSSecurityException (
                    "Cannot handle reference mechanism: " +
                    refElement.getTagName ());
        }
        Attr attr = newElement.getOwnerDocument ().createAttributeNS (MessageConstants.NAMESPACES_NS, "xmlns");
        attr.setValue ("");
        if (newElement != null) {
            newElement.setAttributeNodeNS (attr);
View Full Code Here


            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) {
                    if(isWSITRecipient){
                        MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                        if(inferredKB == null){
                            inferredEncryptionPolicy.setKeyBinding(x509Binding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                        }
                    }
                    returnKey = resolveX509Token(secureMsg, (X509SecurityToken)token, sig,context);
                } else if (token instanceof EncryptedKeyToken) {
                    //TODO: STR is referring to EncryptedKey
                    KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken)token).getKeyInfo();
                    SecurityTokenReference sectr = kiHB.getSecurityTokenReference(0);
                    ReferenceElement refElem = sectr.getReference();
                    String dataEncAlgo = MessageConstants.DEFAULT_DATA_ENC_ALGO;
                    // 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.AES_BLOCK_ENCRYPTION_128;
                    if (context.getAlgorithmSuite() != null) {
View Full Code Here

        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();
View Full Code Here

            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) {
                    if(isWSITRecipient){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                        if(inferredKB == null){
                            inferredSignaturePolicy.setKeyBinding(x509Binding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                        }
                    }
                    returnKey = resolveX509Token(secureMsg, (X509SecurityToken)token, sig,context);
                } else if (token instanceof EncryptedKeyToken) {
                    //TODO: STR is referring to EncryptedKey
                    KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken)token).getKeyInfo();
                    SecurityTokenReference sectr = kiHB.getSecurityTokenReference(0);
                    ReferenceElement refElem = sectr.getReference();
                    String dataEncAlgo = MessageConstants.DEFAULT_DATA_ENC_ALGO;
                    //restoring BC
                    //String dataEncAlgo = MessageConstants.AES_BLOCK_ENCRYPTION_128;
                    if (context.getAlgorithmSuite() != null) {
                        dataEncAlgo = context.getAlgorithmSuite().getEncryptionAlgorithm();
View Full Code Here

        Key returnKey = null;
       
        SecurityEnvironment secEnv = new DefaultSecurityEnvironmentImpl(callbackHandler);
       
        SecurityTokenReference str = keyInfo.getSecurityTokenReference(0);
        ReferenceElement refElement = str.getReference();
       
        if (refElement instanceof KeyIdentifier) {
            KeyIdentifier keyId = (KeyIdentifier)refElement;
            byte[] decodedValue = keyId.getDecodedReferenceValue().getBytes();
            if (MessageConstants.X509SubjectKeyIdentifier_NS.equals(keyId.getValueType()) ||
View Full Code Here

        FilterProcessingContext filterContext = (FilterProcessingContext)context.get (MessageConstants.WSS_PROCESSING_CONTEXT);
        SecurableSoapMessage secureMessage = filterContext.getSecurableSoapMessage ();
        Document soapDocument = secureMessage.getSOAPPart ();
        SOAPElement soapElem =  XMLUtil.convertToSoapElement (soapDocument, (Element) element);
        SecurityTokenReference tokenRef = new SecurityTokenReference (soapElem);
        ReferenceElement refElement =  tokenRef.getReference ();
        HashMap tokenCache = filterContext.getTokenCache ();
        Element tokenElement = null;
        Element newElement = null;
       
        if (refElement instanceof DirectReference) {
            // isXMLToken = true;
            /* Use the URI value to locate the BST */
            String uri = ((DirectReference) refElement).getURI ();
            String tokenId = uri.substring (1);
            secToken = (SecurityToken)tokenCache.get (tokenId);
            if(secToken == null){
                tokenElement = secureMessage.getElementById (tokenId);
                if(tokenElement == null){
                    throw new URIReferenceException ("Could not locate token with following ID"+tokenId);
                }
            
            } else {
                tokenElement = secToken.getAsSoapElement();
            }
            newElement = (Element)element.getOwnerDocument ().importNode (tokenElement, true);
           
        } else if (refElement instanceof KeyIdentifier) {
            String valueType = ((KeyIdentifier) refElement).getValueType ();
            String keyId = ((KeyIdentifier) refElement).getReferenceValue ();
            if (MessageConstants.X509SubjectKeyIdentifier_NS.
                    equals (valueType) ||
                    MessageConstants.X509v3SubjectKeyIdentifier_NS.
                    equals (valueType)) {
                /* Use the Subject Key Identifier to locate BST */
                //  isXMLToken = false;
                X509Certificate cert = null;
               
                Object token = tokenCache.get (keyId);
                if(token instanceof X509SubjectKeyIdentifier ){
                    if(token != null){
                        cert = ((X509SubjectKeyIdentifier)token).getCertificate ();
                    }
                }
               
                if(cert == null){
                    cert = filterContext.getSecurityEnvironment ().getCertificate (
                            filterContext.getExtraneousProperties (), XMLUtil.getDecodedBase64EncodedData (keyId));
                }
                secToken = new X509SecurityToken (soapDocument, cert);
                tokenElement = secToken.getAsSoapElement ();
                newElement = tokenElement;
                //(Element)element.getOwnerDocument().importNode(tokenElement, true);
                try {
                    // EncodingType should not be set -
                    // As specified by WSS spec
                    newElement.removeAttribute ("EncodingType");
                } catch (DOMException de) {
                    logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0607_STR_TRANSFORM_EXCEPTION());
                    throw new XWSSecurityRuntimeException (de.getMessage (), de);
                }
            } else if (MessageConstants.ThumbPrintIdentifier_NS.equals (valueType)) {
                X509Certificate cert = null;
               
                Object token = tokenCache.get (keyId);
                if(token instanceof X509ThumbPrintIdentifier ){
                    if(token != null){
                        cert = ((X509ThumbPrintIdentifier)token).getCertificate ();
                    }
                }
               
                if(cert == null){
                    cert = filterContext.getSecurityEnvironment ().getCertificate (
                            filterContext.getExtraneousProperties (), XMLUtil.getDecodedBase64EncodedData (keyId), MessageConstants.THUMB_PRINT_TYPE);
                }
                secToken = new X509SecurityToken (soapDocument, cert);
                tokenElement = secToken.getAsSoapElement ();
                newElement = tokenElement;
                //(Element)element.getOwnerDocument().importNode(tokenElement, true);
                try {
                    // EncodingType should not be set -
                    // As specified by WSS spec
                    newElement.removeAttribute ("EncodingType");
                } catch (DOMException de) {
                    logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0607_STR_TRANSFORM_EXCEPTION());
                    throw new XWSSecurityRuntimeException (de.getMessage (), de);
                }
            }else if(MessageConstants.EncryptedKeyIdentifier_NS.equals (valueType)){
                // do something here
                newElement = null;
            } else if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE.equals (valueType) ||
                     MessageConstants.WSSE_SAML_v2_0_KEY_IDENTIFIER_VALUE_TYPE.equals (valueType)) {
               
                //TODO : should we first try locating from the cache
                if (tokenRef.getSamlAuthorityBinding () != null) {
                    tokenElement = filterContext.getSecurityEnvironment ().
                            locateSAMLAssertion (
                            filterContext.getExtraneousProperties(), tokenRef.getSamlAuthorityBinding (), keyId, secureMessage.getSOAPPart ());
                } else {
                    tokenElement = SAMLUtil.locateSamlAssertion (keyId,secureMessage.getSOAPPart ());
                }
                newElement = (Element)element.getOwnerDocument ().importNode (tokenElement, true);
               
                Assertion assertion = null;
                try {
                    assertion = AssertionUtil.fromElement(tokenElement);
                } catch (Exception e) {
                    throw new XWSSecurityException (e);
                }
                tokenCache.put (keyId, assertion);
               
            } else {
                try {
                    tokenElement = resolveSAMLToken (tokenRef, keyId, filterContext);
                } catch (Exception e) {
                    // ignore
                }
                if (tokenElement != null) {
                    newElement = (Element)element.getOwnerDocument ().importNode (tokenElement, true);
                } else {
                    //TODO : there can be a X509 KeyIdentifier without ValueType
                    //    log.log(Level.SEVERE, "WSS0334.unsupported.keyidentifier");
                    XWSSecurityException xwsse =
                            new XWSSecurityException (
                            "WSS_DSIG0008:unsupported KeyIdentifier Reference Type "
                            + valueType);
                    throw SecurableSoapMessage.newSOAPFaultException (
                            MessageConstants.WSSE_INVALID_SECURITY_TOKEN,
                            xwsse.getMessage (),
                            xwsse);
                }
            }
           
        } else if (refElement instanceof X509IssuerSerial) {
            //       isXMLToken = false;
            BigInteger serialNumber =
                    ((X509IssuerSerial) refElement).getSerialNumber ();
            String issuerName = ((X509IssuerSerial) refElement).getIssuerName ();
            X509Certificate cert =  null;
            Object token = tokenCache.get (issuerName+serialNumber);
            if(token instanceof X509IssuerSerial){
                cert = ((X509IssuerSerial)token).getCertificate ();
            }
           
            if(cert == null){
                cert = filterContext.getSecurityEnvironment ().getCertificate (
                        filterContext.getExtraneousProperties (),serialNumber, issuerName);
            }
            secToken = new X509SecurityToken (soapDocument, cert);
            tokenElement = secToken.getAsSoapElement ();
            newElement = tokenElement;
            //(Element)element.getOwnerDocument().importNode(tokenElement, true);
            try {
                // EncodingType should not be set - As specified by WSS spec
                newElement.removeAttribute ("EncodingType");
            } catch (DOMException de) {
                logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0607_STR_TRANSFORM_EXCEPTION());
                throw new XWSSecurityException (de.getMessage (), de);
            }
        } else {
            logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0608_DIAG_CAUSE_1());
            throw new XWSSecurityException (
                    "Cannot handle reference mechanism: " +
                    refElement.getTagName ());
        }
        Attr attr = element.getOwnerDocument ().createAttributeNS (MessageConstants.NAMESPACES_NS, "xmlns");
        attr.setValue ("");
        if (newElement != null) {
            newElement.setAttributeNodeNS (attr);
View Full Code Here

                    isBSP = ((WSSPolicy)securityPolicy).isBSP();
                }
            }
           
            SecurityTokenReference str = new SecurityTokenReference(securityTokenReference, isBSP);
            ReferenceElement refElement = str.getReference();
            HashMap tokenCache = wssContext.getTokenCache();
            HashMap insertedX509Cache = wssContext.getInsertedX509Cache();
            SignaturePolicy policy = (SignaturePolicy)wssContext.getInferredPolicy();
            SignaturePolicy inferredSignaturePolicy = null;
            if(isPolicyRecipient){
                int i = wssContext.getInferredSecurityPolicy().size() - 1;
                //When we call SigProc.verifySignature for a SAMLAssertion from KeyResolver
                if (PolicyTypeUtil.signaturePolicy(wssContext.getInferredSecurityPolicy().get(i))) {
                    inferredSignaturePolicy = (SignaturePolicy)wssContext.getInferredSecurityPolicy().get(i);
                }
            } 
            // will be only during verify.
            AuthenticationTokenPolicy.X509CertificateBinding keyBinding = null;
           
            //TODO: what is this case here
            if(policy != null) {
                keyBinding = (AuthenticationTokenPolicy.X509CertificateBinding) policy.newX509CertificateKeyBinding();
            }
           
            Key returnKey = null;
            boolean isSymmetric = false;
            if (refElement instanceof KeyIdentifier) {
                KeyIdentifier keyId = (KeyIdentifier)refElement;
                if(keyBinding != null){
                    keyBinding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                    keyBinding.setValueType(keyId.getValueType());
                }
               
               
                if (MessageConstants.X509SubjectKeyIdentifier_NS.equals(keyId.getValueType()) ||
                        MessageConstants.X509v3SubjectKeyIdentifier_NS.equals(keyId.getValueType())) {
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        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.symmetricKeyBinding(inferredKB)){
                            ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                            isSymmetric = true;
                        } 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);
                                isSymmetric = true;
                            }
                        }

                    }                  
                    if (purpose == Purpose.VERIFY) {
                        byte[] keyIdBytes = XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue());
                        wssContext.setExtraneousProperty(MessageConstants.REQUESTER_KEYID, new String(keyIdBytes));
                        // add missing update to other party certificate
                        X509Certificate cert = wssContext.getSecurityEnvironment().getCertificate(
                                wssContext.getExtraneousProperties(),keyIdBytes);
                        if (!isSymmetric) {
                            wssContext.getSecurityEnvironment().updateOtherPartySubject(
                                    DefaultSecurityEnvironmentImpl.getSubject(wssContext), cert);
                        }
                        returnKey = cert.getPublicKey();
                    } else if(purpose == Purpose.SIGN){
                        returnKey =wssContext.getSecurityEnvironment().getPrivateKey(
                                wssContext.getExtraneousProperties(),
                                XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue()));
                    }
                   
                   
                } else if (MessageConstants.ThumbPrintIdentifier_NS.equals(keyId.getValueType())) {
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        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.symmetricKeyBinding(inferredKB)){
                            ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                            isSymmetric = true;
                        } 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);
                                isSymmetric = true;
                            }
                        }

                    }                   
                    if (purpose == Purpose.VERIFY) {
                        byte[] keyIdBytes = XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue());
                        wssContext.setExtraneousProperty(MessageConstants.REQUESTER_KEYID, new String(keyIdBytes));
                        //update other party subject
                        X509Certificate cert = wssContext.getSecurityEnvironment().getCertificate(
                                wssContext.getExtraneousProperties(),keyIdBytes, MessageConstants.THUMB_PRINT_TYPE);
                        if (!isSymmetric) {
                            wssContext.getSecurityEnvironment().updateOtherPartySubject(
                                    DefaultSecurityEnvironmentImpl.getSubject(wssContext), cert);
                        }
                        returnKey = cert.getPublicKey();
                    } else if(purpose == Purpose.SIGN){
                        returnKey =wssContext.getSecurityEnvironment().getPrivateKey(
                                wssContext.getExtraneousProperties(),
                                XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue()), MessageConstants.THUMB_PRINT_TYPE);
                    }
                   
                }else if (MessageConstants.EncryptedKeyIdentifier_NS.equals(keyId.getValueType())){
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        MLSPolicy inferredKB = inferredSignaturePolicy.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){
                            inferredSignaturePolicy.setKeyBinding(skBinding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(skBinding);
                        }
                    }
                    //Set return key here
                    String ekSha1RefValue = (String)wssContext.getExtraneousProperty("EncryptedKeySHA1");
                    Key secretKey = (Key)wssContext.getExtraneousProperty("SecretKey");
                    String keyRefValue = keyId.getReferenceValue();
                    if(ekSha1RefValue != null && secretKey != null){
                        if(ekSha1RefValue.equals(keyRefValue))
                            returnKey = secretKey;
                    }else{
                        String message = "EncryptedKeySHA1 reference not correct";
                        logger.log(Level.SEVERE,LogStringsMessages.WSS_1306_UNSUPPORTED_KEY_IDENTIFIER_REFERENCE_TYPE(), new Object[] {message});
                        throw new KeySelectorException(message);
                    }
                    //returnKey = null;
                } else if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE.equals(keyId.getValueType()) ||
                        MessageConstants.WSSE_SAML_v2_0_KEY_IDENTIFIER_VALUE_TYPE.equals (keyId.getValueType ())) {
                   
                    String assertionID = keyId.getReferenceValue();
                    Element tokenElement = wssContext.getIssuedSAMLToken();
                    if (tokenElement == null) {
                        Assertion samlAssertion = (Assertion)tokenCache.get(assertionID);
                        if (samlAssertion == null) {
                            if (str.getSamlAuthorityBinding() != null) {
                                tokenElement = wssContext.getSecurityEnvironment().
                                        locateSAMLAssertion(
                                        wssContext.getExtraneousProperties(), str.getSamlAuthorityBinding(), assertionID, secureMsg.getSOAPPart());
                            } else {
                                tokenElement = SAMLUtil.locateSamlAssertion(assertionID,secureMsg.getSOAPPart());
                                if (!("true".equals((String)wssContext.getExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED))) ||
                                        "false".equals((String)wssContext.getExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED))){
                                    wssContext.setExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED,"false");
                                }
                            }
                        } else {
                            try {
                                tokenElement = samlAssertion.toElement(null);
                            } catch (Exception e) {
                                logger.log(Level.SEVERE,LogStringsMessages.WSS_1355_UNABLETO_RESOLVE_SAML_ASSERTION(),e.getMessage());
                                throw new KeySelectorException(e);
                            }
                        }
                   }
                   
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
                        if(inferredKB == null){  
                            if (wssContext.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(context,tokenElement, purpose, assertionID);
                    addAuthorityId(tokenElement,wssContext);
                    if (wssContext.hasIssuedToken() && returnKey != null){
                        SecurityUtil.initInferredIssuedTokenContext(wssContext, str, returnKey);   
                    }                   

                } else {
                   
                    // it could be SAML AssertionID without ValueType on KeyIdentifier
                    String assertionID = keyId.getDecodedReferenceValue();
                    Element samlAssertion = null;
                    try {
                        samlAssertion = resolveSAMLToken(str, assertionID, wssContext);
                    } catch (Exception e) {
                        if(logger.isLoggable(Level.FINEST)){
                        logger.log(Level.FINEST,"Error occurred while trying " +
                                "to resolve SAML assertion"+e.getMessage());
                        }
                    }
                   
                    if (samlAssertion != null) {
                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                            IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
                            if(inferredKB == null){
                                if (wssContext.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(context,samlAssertion, purpose, assertionID);
                        addAuthorityId(samlAssertion,wssContext);

                        //whenever we have SAML we want to record the proofkey and str
                        if (wssContext.hasIssuedToken() && returnKey != null){
                            SecurityUtil.initInferredIssuedTokenContext(wssContext, str, returnKey);                       
                        }
                    
                    } else {
                        // now assume its an X509Token
                        // Note: the code below assumes base64 EncodingType for X509 SKI
                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            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.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 (purpose == Purpose.VERIFY) {
                            byte[] keyIdBytes = XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue());
                            wssContext.setExtraneousProperty(MessageConstants.REQUESTER_KEYID, new String(keyIdBytes));
                            //update other party certificate
                            X509Certificate cert = wssContext.getSecurityEnvironment().getCertificate(
                                    wssContext.getExtraneousProperties(),
                                    XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue()));
                            wssContext.getSecurityEnvironment().updateOtherPartySubject(
                                DefaultSecurityEnvironmentImpl.getSubject(wssContext), cert);
                            returnKey = cert.getPublicKey();
                           
                        } else if(purpose == Purpose.SIGN){
                            returnKey =wssContext.getSecurityEnvironment().getPrivateKey(
                                    wssContext.getExtraneousProperties(),
                                    XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue()));
                        }
                    }

                }
               
            } else if (refElement instanceof DirectReference) {
                if(keyBinding != null){
                    keyBinding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                   
                }
                String uri = ((DirectReference) refElement).getURI();
                if (isBSP && !uri.startsWith("#")) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1356_VIOLATION_BSP_R_5204());
                    throw new XWSSecurityException("Violation of BSP R5204 "
                            + ": When a SECURITY_TOKEN_REFERENCE uses a Direct Reference to an INTERNAL_SECURITY_TOKEN, it MUST use a Shorthand XPointer Reference");
                }
               
                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 (MessageConstants.X509v3_NS.equals(valueType)||MessageConstants.X509v1_NS.equals(valueType)) {
                    // its an X509 Token
                    if(keyBinding != null){
                        keyBinding.setValueType(valueType);
                    }
                    String wsuId = secureMsg.getIdFromFragmentRef(uri);
                    X509SecurityToken token = (X509SecurityToken) insertedX509Cache.get(wsuId);              
                    //if(token == null)
                    //    token =(X509SecurityToken) tokenCache.get(wsuId);
                   
                    if(token == null){
                        token = (X509SecurityToken)resolveToken(wsuId,context);
                        if(token == null){
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1357_UNABLETO_LOCATE_TOKEN());
                            throw new KeySelectorException("Token with Id "+wsuId+ "not found");
                        }else{
                            tokenCache.put(wsuId, token);
                        }
                    }
                   
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        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.symmetricKeyBinding(inferredKB)){
                            ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                            isSymmetric = true;
                        } 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);
                                isSymmetric = true;
                            }
                        }

                    }
                   
                    returnKey = resolveX509Token(wssContext,  token, purpose, isSymmetric);
                   
                } else if(MessageConstants.EncryptedKey_NS.equals(valueType)) {
                    String wsuId = secureMsg.getIdFromFragmentRef(uri);
                    SecurityToken token = (SecurityToken)tokenCache.get(wsuId);
                    if(token == null){
                        token = resolveToken(wsuId, context);
                        if(token == null){
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1357_UNABLETO_LOCATE_TOKEN());
                            throw new KeySelectorException("Token with Id "+wsuId+ "not found");//TODO LOG ::Venu
                        }else{
                            tokenCache.put(wsuId, token);
                        }
                    }
                        KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken)token).getKeyInfo();
                        SecurityTokenReference sectr = kiHB.getSecurityTokenReference(0);
                        SOAPElement se = sectr.getAsSoapElement();
                        ReferenceElement refElem = sectr.getReference();
                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            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);

                            }
                        }
                       
                        Key privKey  = resolve(se, context, Purpose.SIGN);
                        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);
                        wssContext.setExtraneousProperty(MessageConstants.EK_SHA1_VALUE, encEkSha1);

                        returnKey = ((EncryptedKeyToken)token).getSecretKey(privKey, encAlgo);    
                        wssContext.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(wssContext, uri);
                        if (token == null) {
                            token = resolveToken(sctId, context);
                        }

                        if(token == null){
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1358_UNABLETO_LOCATE_SCT_TOKEN());
                            throw new KeySelectorException("SCT Token with Id "+sctId+ "not found");
                        }else{
                            tokenCache.put(sctId, token);
                        }
                    }

                    if (token instanceof SecurityContextToken) {
                        //handling for SecurityContext Token
                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                            SecureConversationTokenKeyBinding sctBinding = new SecureConversationTokenKeyBinding();
                            if(inferredKB == null){
                                inferredSignaturePolicy.setKeyBinding(sctBinding);
                            } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(sctBinding);
                            }
                        }                      
                        returnKey = resolveSCT(wssContext, (SecurityContextTokenImpl)token, purpose);
                       
                    } else {
                        logger.log(Level.SEVERE, LogStringsMessages.WSS_1359_INVALID_VALUETYPE_NON_SC_TTOKEN());
                        throw new KeySelectorException("Incorrect ValueType: " + MessageConstants.SCT_VALUETYPE + ", specified for a Non SCT Token");
                    }

                } else if (null == valueType) {
                    // Log fails BSP:R3059 and R3058
                    //logger.log(Level.WARNING, "Fails BSP requirements R3058 and 3059");
                   
                    // Do default processing
                    String wsuId = secureMsg.getIdFromFragmentRef(uri);
                    SecurityToken token = (SecurityToken)tokenCache.get(wsuId);
                   
                    if(token == null){
                        token = resolveToken(wsuId, context);
                        if (token == null) {
                            token = SecurityUtil.locateBySCTId(wssContext, uri);
                        }

                        if(token == null){
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1357_UNABLETO_LOCATE_TOKEN());
                            throw new KeySelectorException("Token with Id "+wsuId+ "not found");
                        }else{
                            tokenCache.put(wsuId, token);
                        }
                    }
                   
                    if (token instanceof X509SecurityToken) {
                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                            AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                            x509Binding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                            if(inferredKB == null){ 
                                inferredSignaturePolicy.setKeyBinding(x509Binding);
                             } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                                ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                                isSymmetric = true;
                            } 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);
                                    isSymmetric = true;
                                }
                            }

                        }                       
                        returnKey =  resolveX509Token(wssContext,(X509SecurityToken)token, purpose, isSymmetric);
                       
                    } else if (token instanceof EncryptedKeyToken) {

                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            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);
                            }
                        }

                        KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken)token).getKeyInfo();
                        SecurityTokenReference sectr = kiHB.getSecurityTokenReference(0);
                        SOAPElement se = sectr.getAsSoapElement();
                        ReferenceElement refElem = sectr.getReference();
                        Key privKey  = resolve(se, context, Purpose.SIGN);
                   
                        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);
View Full Code Here

        Key returnKey = null;
       
        SecurityEnvironment secEnv = new DefaultSecurityEnvironmentImpl(callbackHandler);
       
        SecurityTokenReference str = keyInfo.getSecurityTokenReference(0);
        ReferenceElement refElement = str.getReference();
       
        if (refElement instanceof KeyIdentifier) {
            KeyIdentifier keyId = (KeyIdentifier)refElement;
            byte[] decodedValue = keyId.getDecodedReferenceValue().getBytes();
            if (MessageConstants.X509SubjectKeyIdentifier_NS.equals(keyId.getValueType()) ||
View Full Code Here

            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) {
                    if(isWSITRecipient){
                        MLSPolicy inferredKB = inferredEncryptionPolicy.getKeyBinding();
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                        if(inferredKB == null){
                            inferredEncryptionPolicy.setKeyBinding(x509Binding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                        }
                    }
                    returnKey = resolveX509Token(secureMsg, (X509SecurityToken)token, sig,context);
                } else if (token instanceof EncryptedKeyToken) {
                    //TODO: STR is referring to EncryptedKey
                    KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken)token).getKeyInfo();
                    SecurityTokenReference sectr = kiHB.getSecurityTokenReference(0);
                    ReferenceElement refElem = sectr.getReference();
                    String dataEncAlgo = MessageConstants.DEFAULT_DATA_ENC_ALGO;
                    // 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.AES_BLOCK_ENCRYPTION_128;
                    if (context.getAlgorithmSuite() != null) {
View Full Code Here

        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();
View Full Code Here

TOP

Related Classes of com.sun.xml.wss.core.ReferenceElement

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.