Examples of RampartPolicyData


Examples of org.apache.rampart.policy.RampartPolicyData

        }
    }
   
    private byte[] doSecureConversationSignature(RampartMessageData rmd, Token token, SignedEncryptedParts signdParts) throws RampartException {
       
        RampartPolicyData rpd = rmd.getPolicyData();
        Document doc= rmd.getDocument();
       
        //Get the issued token
        String id = rmd.getSecConvTokenId();
  
        int inclusion = token.getInclusion();
        org.apache.rahas.Token tok = null;
        try {
          tok = rmd.getTokenStorage().getToken(id);
        } catch (TrustException e) {
          throw new RampartException("errorExtractingToken",
                  new String[]{id} ,e);
        }
  
        boolean tokenIncluded = false;
       
        if(inclusion == SPConstants.INCLUDE_TOEKN_ALWAYS ||
        ((inclusion == SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT
                || inclusion == SPConstants.INCLUDE_TOKEN_ONCE)
                && rmd.isInitiator())) {
         
            //Add the token
            rmd.getSecHeader().getSecurityHeader().appendChild(
                  doc.importNode((Element) tok.getToken(), true));
         
            tokenIncluded = true;
        }

        Vector sigParts = new Vector();
       
        if(this.timestampElement != null){
            sigParts.add(new WSEncryptionPart(rmd.getTimestampId()));                         
        }
       
       
        if(rpd.isTokenProtection() && tokenIncluded) {
            sigParts.add(new WSEncryptionPart(id));
        }
       
        if(signdParts != null) {
            if(signdParts.isBody()) {
                SOAPEnvelope env = rmd.getMsgContext().getEnvelope();
                sigParts.add(new WSEncryptionPart(RampartUtil.addWsuIdToElement(env.getBody())));
            }
   
            ArrayList headers = signdParts.getHeaders();
            for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
                Header header = (Header) iterator.next();
                WSEncryptionPart wep = new WSEncryptionPart(header.getName(),
                        header.getNamespace(),
                        "Content");
                sigParts.add(wep);
            }
        }
       
        //check for derived keys
        AlgorithmSuite algorithmSuite = rpd.getAlgorithmSuite();
        if(token.isDerivedKeys()) {
          //Create a derived key and add
          try {
  
              //Do Signature with derived keys
              WSSecDKSign dkSign = new WSSecDKSign();
             
              // Setting the AttachedReference or the UnattachedReference according to the flag
              OMElement ref;
              if (tokenIncluded == true) {
                  ref = tok.getAttachedReference();
              } else {
                  ref = tok.getUnattachedReference();
              }
             
              if(ref != null) {
                  dkSign.setExternalKey(tok.getSecret(), (Element)
                          doc.importNode((Element) ref, true));
              } else {
                  dkSign.setExternalKey(tok.getSecret(), tok.getId());
              }
             
              //Set the algo info
              dkSign.setSignatureAlgorithm(algorithmSuite.getSymmetricSignature());
              dkSign.setDerivedKeyLength(algorithmSuite.getSignatureDerivedKeyLength());
             
              dkSign.prepare(doc);
             
              dkSign.appendDKElementToHeader(rmd.getSecHeader());
             
              dkSign.setParts(sigParts);
             
              dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
             
              //Do signature
              dkSign.computeSignature();
             
              dkSign.appendSigToHeader(rmd.getSecHeader());
             
              return dkSign.getSignatureValue();
             
          } catch (ConversationException e) {
              throw new RampartException(
                      "errorInDerivedKeyTokenSignature", e);
          } catch (WSSecurityException e) {
              throw new RampartException(
                      "errorInDerivedKeyTokenSignature", e);
          }
         
        } else {
            try {
                WSSecSignature sig = new WSSecSignature();
                sig.setWsConfig(rmd.getConfig());
                sig.setCustomTokenId(tok.getId().substring(1));
                sig.setCustomTokenValueType(WSConstants.WSS_SAML_NS +
                        WSConstants.SAML_ASSERTION_ID);
                sig.setSecretKey(tok.getSecret());
                sig.setSignatureAlgorithm(algorithmSuite.getAsymmetricSignature());
                sig.setSignatureAlgorithm(algorithmSuite.getSymmetricSignature());
                sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                sig.prepare(rmd.getDocument(), RampartUtil.getSignatureCrypto(rpd
                        .getRampartConfig(), rmd.getCustomClassLoader()),
                        rmd.getSecHeader());

                sig.setParts(sigParts);
                sig.addReferencesToSign(sigParts, rmd.getSecHeader());
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

       
        RampartMessageData rmd = data.getRampartMessageData();
       
        ArrayList encrRefs = getEncryptedReferences(results);
       
        RampartPolicyData rpd = rmd.getPolicyData();

        // build the list of encrypted nodes based on the dataRefs xpath expressions
        SOAPEnvelope envelope = rmd.getMsgContext().getEnvelope();
        Set namespaces = RampartUtil.findAllPrefixNamespaces(envelope,
                                                             rpd.getDeclaredNamespaces());

        Map decryptedElements = new HashMap();
        for (int i = 0; i < encrRefs.size() ; i++) {
            WSDataRef dataRef = (WSDataRef)encrRefs.get(i);

            if(dataRef == null || dataRef.getXpath() == null) {
                continue;
            }

            try {
                XPath xp = new AXIOMXPath(dataRef.getXpath());

                Iterator nsIter = namespaces.iterator();

                while (nsIter.hasNext())
                {
                    OMNamespace tmpNs = (OMNamespace)nsIter.next();
                    xp.addNamespace(tmpNs.getPrefix(), tmpNs.getNamespaceURI());
                }

                Iterator nodesIterator = xp.selectNodes(envelope).iterator();

                while (nodesIterator.hasNext()) {
                    decryptedElements.put(nodesIterator.next(), Boolean.valueOf(dataRef.isContent()));
                }


            } catch (JaxenException e) {
                // This has to be changed to propagate an instance of a RampartException up
                throw new RampartException("An error occurred while searching for decrypted elements.", e);
            }

        }

       
        //Check for encrypted body
        if(rpd.isEncryptBody()&& !rpd.isEncryptBodyOptional()) {
           
            if( !isRefIdPresent(encrRefs, data.getBodyEncrDataId())){
                throw new RampartException("encryptedPartMissing",
                        new String[]{data.getBodyEncrDataId()});
            }
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

   
    public void validateRequiredElements(ValidatorData data) throws RampartException {
       
        RampartMessageData rmd = data.getRampartMessageData();
       
        RampartPolicyData rpd = rmd.getPolicyData();
       
        SOAPEnvelope envelope = rmd.getMsgContext().getEnvelope();
       
        Iterator elementsIter = rpd.getRequiredElements().iterator();
       
        while (elementsIter.hasNext()) {
           
            String expression = (String) elementsIter.next();
           
            if ( !RampartUtil.checkRequiredElements(envelope, rpd.getDeclaredNamespaces(), expression)) {
                throw new RampartException("requiredElementsMissing", new String[] { expression } );
            }
        }
       
    }
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

        }
    }

   
    protected boolean isSignatureRequired(RampartMessageData rmd) {
        RampartPolicyData rpd = rmd.getPolicyData();
        return (rpd.isSymmetricBinding() && rpd.getSignatureToken() != null) ||
                (!rpd.isSymmetricBinding() && !rpd.isTransportBinding() &&
                        ((rpd.getInitiatorToken() != null && rmd.isInitiator())
                                || rpd.getRecipientToken() != null && !rmd.isInitiator()));
    }
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

    protected boolean isUsernameTokenPresent(ValidatorData data) {
       
        //TODO This can be integrated with supporting token processing
        // which also checks whether Username Tokens present
       
        RampartPolicyData rpd = data.getRampartMessageData().getPolicyData();
       
        Vector supportingToks = rpd.getSupportingTokensList();
        for (int i = 0; i < supportingToks.size(); i++) {
            SupportingToken suppTok = (SupportingToken) supportingToks.get(i);
            if (isUsernameTokenPresent(suppTok)) {
                return true;
            }
        }
       
        SupportingToken signedSuppToken = rpd.getSignedSupportingTokens();
        if(isUsernameTokenPresent(signedSuppToken)) {
            return true;
        }
       
        SupportingToken signedEndSuppToken = rpd.getSignedEndorsingSupportingTokens();
        if(isUsernameTokenPresent(signedEndSuppToken)) {
            return true;
        }
       
        SupportingToken endSuppToken = rpd.getEndorsingSupportingTokens();
        if(isUsernameTokenPresent(endSuppToken)){
            return true;
        }
       
        return false;
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

        Axis2Util.useDOOM(true);
       
        RampartMessageData rmd = new RampartMessageData(msgCtx, true);
       
       
        RampartPolicyData rpd = rmd.getPolicyData();
        if(rpd == null || isSecurityValidationFault(msgCtx) ||
                !RampartUtil.isSecHeaderRequired(rpd, rmd.isInitiator(),false)) {
           
            Document doc = rmd.getDocument();
            WSSecHeader secHeader = rmd.getSecHeader();
           
            if ( secHeader != null && secHeader.isEmpty(doc) ) {
                secHeader.removeSecurityHeader(doc);
            }
           
            return;
        }
       
        //Copy the RECV_RESULTS if available
        if(!rmd.isInitiator()) {
            OperationContext opCtx = msgCtx.getOperationContext();
            MessageContext inMsgCtx;
            if(opCtx != null &&
                    (inMsgCtx = opCtx.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE)) != null) {
                msgCtx.setProperty(WSHandlerConstants.RECV_RESULTS,
                        inMsgCtx.getProperty(WSHandlerConstants.RECV_RESULTS));
            }
        }
       
       
        String isCancelreq = (String)msgCtx.getProperty(RampartMessageData.CANCEL_REQUEST);
        if(isCancelreq != null && Constants.VALUE_TRUE.equals(isCancelreq)) {
            try {
               
                String cancelAction = TrustUtil.getWSTNamespace(rmd.getWstVersion()) + RahasConstants.RST_ACTION_CANCEL_SCT;
                //Set action
                msgCtx.getOptions().setAction(cancelAction);
               
                //Change the wsa:Action header
                String wsaNs = Final.WSA_NAMESPACE;
                Object addressingVersionFromCurrentMsgCtxt = msgCtx.getProperty(AddressingConstants.WS_ADDRESSING_VERSION);
                if (Submission.WSA_NAMESPACE.equals(addressingVersionFromCurrentMsgCtxt)) {
                    wsaNs = Submission.WSA_NAMESPACE;
                }
                OMElement header = msgCtx.getEnvelope().getHeader();
                if(header != null) {
                    OMElement actionElem = header.getFirstChildWithName(new QName(wsaNs, AddressingConstants.WSA_ACTION));
                    if(actionElem != null) {
                        actionElem.setText(cancelAction);
                    }
                }
               
                //set payload to a cancel request
                String ctxIdKey = RampartUtil.getContextIdentifierKey(msgCtx);
                String tokenId = (String)RampartUtil.getContextMap(msgCtx).get(ctxIdKey);
               
                if(tokenId != null && RampartUtil.isTokenValid(rmd, tokenId)) {
                    OMElement bodyElem = msgCtx.getEnvelope().getBody();
                    OMElement child = bodyElem.getFirstElement();
                    SecurityContextToken sct = new SecurityContextToken(
                            (Element) rmd.getTokenStorage().getToken(tokenId)
                                    .getToken());
                    OMElement newChild = TrustUtil.createCancelRequest(sct
                            .getIdentifier(), rmd.getWstVersion());
                    Element newDomChild = XMLUtils.toDOM(newChild);
                    Node importedNode = rmd.getDocument().importNode((Element) newDomChild, true);
                    ((Element) bodyElem).replaceChild(importedNode, (Element) child);
                } else {
                    throw new RampartException("tokenToBeCancelledInvalid");
                }
               
            } catch (Exception e) {
                e.printStackTrace();
                throw new RampartException("errorInTokenCancellation");
            }
        }
       
       if(rpd.isTransportBinding()) {
           log.debug("Building transport binding");
           TransportBindingBuilder building = new TransportBindingBuilder();
           building.build(rmd);
        } else if(rpd.isSymmetricBinding()) {
           log.debug("Building SymmetricBinding");
           SymmetricBindingBuilder builder = new SymmetricBindingBuilder();
           builder.build(rmd);
        } else {
            AsymmetricBindingBuilder builder = new AsymmetricBindingBuilder();
            builder.build(rmd);
        }
      
       //TODO remove following check, we don't need this check here as we do a check to see whether
       // security header required
      
       Document doc = rmd.getDocument();
       WSSecHeader secHeader = rmd.getSecHeader();
      
       if ( secHeader != null && secHeader.isEmpty(doc) ) {
           secHeader.removeSecurityHeader(doc);
       }
       
       /*
        * Checking whether MTOMSerializable is there. If so set optimizeElement.
        * */
        if(rpd.isMTOMSerialize()){
          msgCtx.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
          OptimizePartsConfig config= rpd.getOptimizePartsConfig();
          if(config != null){
            MessageOptimizer.optimize(msgCtx.getEnvelope(), config.getExpressions(), config.getNamespaces());
          }
        }
       
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

    public void build(RampartMessageData rmd) throws RampartException {

        log.debug("SymmetricBindingBuilder build invoked");

        RampartPolicyData rpd = rmd.getPolicyData();
        if(rpd.isIncludeTimestamp()) {
            this.addTimestamp(rmd);
        }
       
        if(rmd.isInitiator()) {
            //Setup required tokens
            initializeTokens(rmd);
        }
       
           
        if(SPConstants.ENCRYPT_BEFORE_SIGNING.equals(rpd.getProtectionOrder())) {
            this.doEncryptBeforeSig(rmd);
        } else {
            this.doSignBeforeEncrypt(rmd);
        }
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

   
    private void doEncryptBeforeSig(RampartMessageData rmd) throws RampartException {
       
      long t0 = 0, t1 = 0, t2 = 0;
              
        RampartPolicyData rpd = rmd.getPolicyData();
       
        Vector signatureValues = new Vector();
       
      if(tlog.isDebugEnabled()){
        t0 = System.currentTimeMillis();
      }
       
        Token encryptionToken = rpd.getEncryptionToken();
        Vector encrParts = RampartUtil.getEncryptedParts(rmd);

        Vector sigParts = RampartUtil.getSignedParts(rmd);
       
        if(encryptionToken == null && encrParts.size() > 0) {
            throw new RampartException("encryptionTokenMissing");
        }
       
        if(encryptionToken != null && encrParts.size() > 0) {
            //The encryption token can be an IssuedToken or a
             //SecureConversationToken
            String tokenId = null;
            org.apache.rahas.Token tok = null;
           
            if(encryptionToken instanceof IssuedToken) {
                tokenId = rmd.getIssuedEncryptionTokenId();
                if (log.isDebugEnabled()) {
                    log.debug("Issued EncryptionToken Id : " + tokenId);
                }
            } else if(encryptionToken instanceof SecureConversationToken) {
                tokenId = rmd.getSecConvTokenId();
                if (log.isDebugEnabled()) {
                    log.debug("SCT Id : " + tokenId);
                }
            } else if (encryptionToken instanceof X509Token) {
              if (rmd.isInitiator()) {
                tokenId = setupEncryptedKey(rmd, encryptionToken);
              } else {
                tokenId = getEncryptedKey(rmd);
              }
            } //TODO SAMLToken
           
            if(tokenId == null || tokenId.length() == 0) {
                throw new RampartException("noSecurityToken");
            }
           
            //Hack to handle reference id issues
            //TODO Need a better fix
            if(tokenId.startsWith("#")) {
                tokenId = tokenId.substring(1);
            }
           
            /*
             * Get hold of the token from the token storage
             */
            tok = this.getToken(rmd, tokenId);

            /*
             * Attach the token into the message based on token inclusion
             * values
             */
            boolean attached = false;
            Element encrTokenElement = null;
            Element refList = null;
            WSSecDKEncrypt dkEncr = null;
            WSSecEncrypt encr = null;
            Element encrDKTokenElem = null;
           
            if(SPConstants.INCLUDE_TOEKN_ALWAYS == encryptionToken.getInclusion() ||
                    SPConstants.INCLUDE_TOKEN_ONCE == encryptionToken.getInclusion() ||
                    (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == encryptionToken.getInclusion())) {
                encrTokenElement = RampartUtil.appendChildToSecHeader(rmd, tok.getToken());
                attached = true;
            } else if(encryptionToken instanceof X509Token && rmd.isInitiator()) {
              encrTokenElement = RampartUtil.appendChildToSecHeader(rmd, tok.getToken());
            }
           
            Document doc = rmd.getDocument();

            AlgorithmSuite algorithmSuite = rpd.getAlgorithmSuite();
            if(encryptionToken.isDerivedKeys()) {
                log.debug("Use drived keys");

                dkEncr = new WSSecDKEncrypt();
               
                if(attached && tok.getAttachedReference() != null) {
                   
                    dkEncr.setExternalKey(tok.getSecret(), (Element) doc
                            .importNode((Element) tok.getAttachedReference(),
                                    true));
                   
                } else if(tok.getUnattachedReference() != null) {
                    dkEncr.setExternalKey(tok.getSecret(), (Element) doc
                            .importNode((Element) tok.getUnattachedReference(),
                                    true));
                } else {
                    dkEncr.setExternalKey(tok.getSecret(), tok.getId());
                }
                try {
                    dkEncr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
                    dkEncr.setDerivedKeyLength(algorithmSuite.getEncryptionDerivedKeyLength()/8);
                    dkEncr.prepare(doc);
                    encrDKTokenElem = dkEncr.getdktElement();
                    RampartUtil.appendChildToSecHeader(rmd, encrDKTokenElem);
                   
                    refList = dkEncr.encryptForExternalRef(null, encrParts);
                   
                } catch (WSSecurityException e) {
                    throw new RampartException("errorInDKEncr");
                } catch (ConversationException e) {
                    throw new RampartException("errorInDKEncr");
                }
            } else {
                log.debug("NO derived keys, use the shared secret");
                encr = new WSSecEncrypt();
               
                encr.setWsConfig(rmd.getConfig());
                encr.setEncKeyId(tokenId);
                RampartUtil.setEncryptionUser(rmd, encr);
                encr.setEphemeralKey(tok.getSecret());
                encr.setDocument(doc);
                encr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
                // SymmKey is already encrypted, no need to do it again
                encr.setEncryptSymmKey(false);
                if (!rmd.isInitiator() && tok instanceof EncryptedKeyToken) {
                    encr.setUseKeyIdentifier(true);
                    encr.setCustomReferenceValue(((EncryptedKeyToken)tok).getSHA1());
                    encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                }
               
                try {
                 
                    encr.prepare(doc, RampartUtil.getEncryptionCrypto(rpd
                            .getRampartConfig(), rmd.getCustomClassLoader()));
                    //Encrypt, get hold of the ref list and add it
                    refList = encr.encryptForExternalRef(null, encrParts);
                } catch (WSSecurityException e) {
                    throw new RampartException("errorInEncryption", e);
                }
            }
           
            this.mainRefListElement = RampartUtil.appendChildToSecHeader(rmd, refList);
           
            if(tlog.isDebugEnabled()){
              t1 = System.currentTimeMillis();
            }
           
            // Sometimes encryption token is not included in the the message
            if (encrTokenElement != null) {
                this.setInsertionLocation(encrTokenElement);
            } else if (timestampElement != null) {
              this.setInsertionLocation(timestampElement);
            }
           
            RampartUtil.handleEncryptedSignedHeaders(encrParts, sigParts, doc);
           
            HashMap sigSuppTokMap = null;
            HashMap endSuppTokMap = null;
            HashMap sgndEndSuppTokMap = null;
            HashMap sgndEncSuppTokMap = null;
            HashMap endEncSuppTokMap = null;
            HashMap sgndEndEncSuppTokMap = null;
           
           
            if(this.timestampElement != null){
              sigParts.add(new WSEncryptionPart(RampartUtil
                    .addWsuIdToElement((OMElement) this.timestampElement)));
            }
           
            if(rmd.isInitiator()) {
           
                // Now add the supporting tokens
                SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
                sigSuppTokMap = this.handleSupportingTokens(rmd, sgndSuppTokens);          
               
                SupportingToken endSuppTokens = rpd.getEndorsingSupportingTokens();
                endSuppTokMap = this.handleSupportingTokens(rmd, endSuppTokens);
               
                SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();          
                sgndEndSuppTokMap = this.handleSupportingTokens(rmd, sgndEndSuppTokens);
               
                SupportingToken sgndEncryptedSuppTokens = rpd.getSignedEncryptedSupportingTokens();
                sgndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEncryptedSuppTokens);
               
                SupportingToken endorsingEncryptedSuppTokens = rpd.getEndorsingEncryptedSupportingTokens();
                endEncSuppTokMap = this.handleSupportingTokens(rmd, endorsingEncryptedSuppTokens);
               
                SupportingToken sgndEndEncSuppTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();          
                sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);
               
                Vector supportingToks = rpd.getSupportingTokensList();
                for (int i = 0; i < supportingToks.size(); i++) {
                    this.handleSupportingTokens(rmd, (SupportingToken)supportingToks.get(i));
                }
               
                SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
                this.handleSupportingTokens(rmd, encryptedSupportingToks);
       
                //Setup signature parts
                sigParts = addSignatureParts(sigSuppTokMap, sigParts);
                sigParts = addSignatureParts(sgndEncSuppTokMap, sigParts);
                sigParts = addSignatureParts(sgndEndSuppTokMap, sigParts);
                sigParts = addSignatureParts(sgndEndEncSuppTokMap, sigParts);
               
            } else {
                addSignatureConfirmation(rmd, sigParts);
            }
   
           
            //Sign the message
            //We should use the same key in the case of EncryptBeforeSig
            if ( sigParts.size() > 0) {
                signatureValues.add(this.doSymmSignature(rmd, encryptionToken, tok, sigParts));
                this.mainSigId = RampartUtil.addWsuIdToElement((OMElement)this.getInsertionLocation());        
            }
           
            if(rmd.isInitiator()) {
               
                endSuppTokMap.putAll(endEncSuppTokMap);
                //Do endorsed signatures
                Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);
                for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
                    signatureValues.add(iter.next());
                }
               
                sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
                //Do signed endorsing signatures
                Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
                for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
                    signatureValues.add(iter.next());
                }
            }
           
            if(tlog.isDebugEnabled()){
              t2 = System.currentTimeMillis();
              tlog.debug("Encryption took :" + (t1 - t0)
                    +", Signature tool :" + (t2 - t1) );
            }
           
            //Check for signature protection and encryption of UsernameToken
            if(rpd.isSignatureProtection() && this.mainSigId != null ||
                    encryptedTokensIdList.size() > 0 && rmd.isInitiator()) {
              long t3 = 0, t4 = 0;
              if(tlog.isDebugEnabled()){
                t3 = System.currentTimeMillis();
              }
                log.debug("Signature protection");
                Vector secondEncrParts = new Vector();
               
                //Now encrypt the signature using the above token
                if(rpd.isSignatureProtection()) {
                    secondEncrParts.add(new WSEncryptionPart(this.mainSigId, "Element"));
                }
               
                if(rmd.isInitiator()) {
                    for (int i = 0 ; i < encryptedTokensIdList.size(); i++) {
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

    private void doSignBeforeEncrypt(RampartMessageData rmd) throws RampartException {
     
      long t0 = 0, t1 = 0, t2 = 0;
               
        RampartPolicyData rpd = rmd.getPolicyData();
        Document doc = rmd.getDocument();
       
        if(tlog.isDebugEnabled()){
        t0 = System.currentTimeMillis();
      }
        Token sigToken = rpd.getSignatureToken();
       
        String encrTokId = null;
        String sigTokId = null;
       
        org.apache.rahas.Token encrTok = null;
        org.apache.rahas.Token sigTok = null;
       
        Element sigTokElem = null;
       
        Vector signatureValues = new Vector();
       
        if(sigToken != null) {
            if(sigToken instanceof SecureConversationToken) {
                sigTokId = rmd.getSecConvTokenId();
            } else if(sigToken instanceof IssuedToken) {
                sigTokId = rmd.getIssuedSignatureTokenId();
            } else if(sigToken instanceof X509Token) {
              if (rmd.isInitiator()) {
                sigTokId = setupEncryptedKey(rmd, sigToken);
              } else {
                sigTokId = getEncryptedKey(rmd);
              }
            }
        } else {
            throw new RampartException("signatureTokenMissing");
        }
       
        if(sigTokId == null || sigTokId.length() == 0) {
            throw new RampartException("noSecurityToken");
        }
       
        sigTok = this.getToken(rmd, sigTokId);

        if(SPConstants.INCLUDE_TOEKN_ALWAYS == sigToken.getInclusion() ||
                SPConstants.INCLUDE_TOKEN_ONCE == sigToken.getInclusion() ||
                (rmd.isInitiator() &&
                        SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == sigToken.getInclusion())) {
            sigTokElem = RampartUtil.appendChildToSecHeader(rmd,
                                                            sigTok.getToken());
            this.setInsertionLocation(sigTokElem);
        } else if ((rmd.isInitiator() && sigToken instanceof X509Token)
                || sigToken instanceof SecureConversationToken) {
            sigTokElem = RampartUtil.appendChildToSecHeader(rmd, sigTok.getToken());
           
            //Set the insertion location
            this.setInsertionLocation(sigTokElem);
        }
       

        HashMap sigSuppTokMap = null;
        HashMap endSuppTokMap = null;
        HashMap sgndEndSuppTokMap = null;
        HashMap sgndEncSuppTokMap = null;
        HashMap endEncSuppTokMap = null;
        HashMap sgndEndEncSuppTokMap = null;
       
        Vector sigParts = RampartUtil.getSignedParts(rmd);
       
        if(this.timestampElement != null){
          sigParts.add(new WSEncryptionPart(RampartUtil
                .addWsuIdToElement((OMElement) this.timestampElement)));
        }
       
        if(rmd.isInitiator()) {
    //      Now add the supporting tokens
            SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
            sigSuppTokMap = this.handleSupportingTokens(rmd, sgndSuppTokens);          
           
            SupportingToken endSuppTokens = rpd.getEndorsingSupportingTokens();
            endSuppTokMap = this.handleSupportingTokens(rmd, endSuppTokens);
           
            SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();          
            sgndEndSuppTokMap = this.handleSupportingTokens(rmd, sgndEndSuppTokens);
           
            SupportingToken sgndEncryptedSuppTokens = rpd.getSignedEncryptedSupportingTokens();
            sgndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEncryptedSuppTokens);
           
            SupportingToken endorsingEncryptedSuppTokens = rpd.getEndorsingEncryptedSupportingTokens();
            endEncSuppTokMap = this.handleSupportingTokens(rmd, endorsingEncryptedSuppTokens);
           
            SupportingToken sgndEndEncSuppTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();          
            sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);
           
            Vector supportingToks = rpd.getSupportingTokensList();
            for (int i = 0; i < supportingToks.size(); i++) {
                this.handleSupportingTokens(rmd, (SupportingToken)supportingToks.get(i));
            }
           
            SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
            this.handleSupportingTokens(rmd, encryptedSupportingToks);
   
            //Setup signature parts
            sigParts = addSignatureParts(sigSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEncSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEndSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEndEncSuppTokMap, sigParts);
           
        } else {
            addSignatureConfirmation(rmd, sigParts);
        }
       
        if (sigParts.size() > 0 ) {
            //Sign the message
            signatureValues.add(this.doSymmSignature(rmd, sigToken, sigTok, sigParts));
   
            this.mainSigId = RampartUtil.addWsuIdToElement((OMElement)this.getInsertionLocation());

        }
       
        if(rmd.isInitiator()) {
            // Adding the endorsing encrypted supporting tokens to endorsing supporting tokens
            endSuppTokMap.putAll(endEncSuppTokMap);
            //Do endorsed signatures
            Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);
           
            for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
                signatureValues.add(iter.next());
            }
            
            //Adding the signed endorsed encrypted tokens to signed endorsed supporting tokens
            sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
            //Do signed endorsing signatures
            Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
            for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
                signatureValues.add(iter.next());
            }
        }
       
        if(tlog.isDebugEnabled()){
        t1 = System.currentTimeMillis();
      }
       
        //Encryption
        Token encrToken = rpd.getEncryptionToken();
        Element encrTokElem = null;
        if(sigToken.equals(encrToken)) {
            //Use the same token
            encrTokId = sigTokId;
            encrTok = sigTok;
            encrTokElem = sigTokElem;
        } else {
            encrTokId = rmd.getIssuedEncryptionTokenId();
            encrTok = this.getToken(rmd, encrTokId);
           
            if(SPConstants.INCLUDE_TOEKN_ALWAYS == encrToken.getInclusion() ||
                    SPConstants.INCLUDE_TOKEN_ONCE == encrToken.getInclusion() ||
                    (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == encrToken.getInclusion())) {
                encrTokElem = (Element)encrTok.getToken();
               
                //Add the encrToken element before the sigToken element
                RampartUtil.insertSiblingBefore(rmd, sigTokElem, encrTokElem);
            }
           
        }
   
        Vector encrParts = RampartUtil.getEncryptedParts(rmd);
       
        //Check for signature protection
        if(rpd.isSignatureProtection() && this.mainSigId != null) {
            //Now encrypt the signature using the above token
            encrParts.add(new WSEncryptionPart(this.mainSigId, "Element"));
        }
       
        if(rmd.isInitiator()) {
            for (int i = 0 ; i < encryptedTokensIdList.size(); i++) {
                encrParts.add(new WSEncryptionPart((String)encryptedTokensIdList.get(i),"Element"));
            }
        }
       
        Element refList = null;
        if(encrParts.size() > 0) {
            //The sec conv token can be used without derived keys
            if(encrToken.isDerivedKeys()) {
               
                try {
                    WSSecDKEncrypt dkEncr = new WSSecDKEncrypt();
                   
                    //Check whether it is security policy 1.2 and use the secure conversation accordingly
                    if (SPConstants.SP_V12 == encrToken.getVersion()) {
                        dkEncr.setWscVersion(ConversationConstants.VERSION_05_12);
                    }                   
                   
                    if(encrTokElem != null && encrTok.getAttachedReference() != null) {
                       
                        dkEncr.setExternalKey(encrTok.getSecret(), (Element) doc
                                .importNode((Element) encrTok.getAttachedReference(),
                                        true));
                    } else if(encrTok.getUnattachedReference() != null) {
                        dkEncr.setExternalKey(encrTok.getSecret(), (Element) doc
                                .importNode((Element) encrTok.getUnattachedReference(),
                                        true));
                    } else if (!rmd.isInitiator() && encrToken.isDerivedKeys()) {
                     
                      // If the Encrypted key used to create the derived key is not
                      // attached use key identifier as defined in WSS1.1 section
                      // 7.7 Encrypted Key reference
                      SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
                      if(encrTok instanceof EncryptedKeyToken) {
                          tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken)encrTok).getSHA1());
                      }
                      dkEncr.setExternalKey(encrTok.getSecret(), tokenRef.getElement());
                     
                    } else {
                        dkEncr.setExternalKey(encrTok.getSecret(), encrTok.getId());
                    }
                   
                    if(encrTok instanceof EncryptedKeyToken) {
                        dkEncr.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
                                + WSConstants.ENC_KEY_VALUE_TYPE);
                    }
                   
                    dkEncr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                    dkEncr.setDerivedKeyLength(rpd.getAlgorithmSuite().getEncryptionDerivedKeyLength()/8);
                    dkEncr.prepare(doc);
                    Element encrDKTokenElem = null;
                    encrDKTokenElem = dkEncr.getdktElement();
                    if(encrTokElem != null) {
                        RampartUtil.insertSiblingAfter(rmd, encrTokElem, encrDKTokenElem);
                    } else if (timestampElement != null){
                        RampartUtil.insertSiblingAfter(rmd, this.timestampElement, encrDKTokenElem);
                    } else {
                        RampartUtil.insertSiblingBefore(rmd, this.getInsertionLocation(), encrDKTokenElem);
                    }
                   
                    refList = dkEncr.encryptForExternalRef(null, encrParts);
                   
                    RampartUtil.insertSiblingAfter(rmd,
                                                    encrDKTokenElem,
                                                    refList);
   
                } catch (WSSecurityException e) {
                    throw new RampartException("errorInDKEncr");
                } catch (ConversationException e) {
                    throw new RampartException("errorInDKEncr");
                }               
            } else {
                try {
                   
                    WSSecEncrypt encr = new WSSecEncrypt();
                   
                    encr.setWsConfig(rmd.getConfig());
                    //Hack to handle reference id issues
                    //TODO Need a better fix
                    if(encrTokId.startsWith("#")) {
                        encrTokId = encrTokId.substring(1);
                    }
                    encr.setEncKeyId(encrTokId);
                   
                    encr.setEphemeralKey(encrTok.getSecret());
                    RampartUtil.setEncryptionUser(rmd, encr);
                    encr.setDocument(doc);
                    encr.setEncryptSymmKey(false);
                    encr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                    // Use key identifier in the KeyInfo in server side
                    if (!rmd.isInitiator()) {
                        if(encrTok instanceof EncryptedKeyToken) {
                            encr.setUseKeyIdentifier(true);
                            encr.setCustomReferenceValue(((EncryptedKeyToken)encrTok).getSHA1());
                            encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                        }
                    }
                    encr.prepare(doc, RampartUtil.getEncryptionCrypto(rpd
                            .getRampartConfig(), rmd.getCustomClassLoader()));
                                      
                    //Encrypt, get hold of the ref list and add it
                    refList = encr.encryptForExternalRef(null, encrParts);                                       
   
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

     * @param rmd
     * @throws RampartException
     */
    private void initializeTokens(RampartMessageData rmd) throws RampartException {
       
        RampartPolicyData rpd = rmd.getPolicyData();
       
        MessageContext msgContext = rmd.getMsgContext();
        if(rpd.isSymmetricBinding() && !msgContext.isServerSide()) {
            if (log.isDebugEnabled()) {
                log.debug("Processing symmetric binding: " +
                        "Setting up encryption token and signature token");
            }
            //Setting up encryption token and signature token
           
            Token sigTok = rpd.getSignatureToken();
            Token encrTok = rpd.getEncryptionToken();
            if(sigTok instanceof IssuedToken) {
                log.debug("SignatureToken is an IssuedToken");
                if(rmd.getIssuedSignatureTokenId() == null) {
                    log.debug("No Issuedtoken found, requesting a new token");

View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.