Examples of RampartPolicyData


Examples of org.apache.rampart.policy.RampartPolicyData

     * @throws WSSecurityException
     * @throws RampartException
     */
    protected WSSecEncryptedKey getEncryptedKeyBuilder(RampartMessageData rmd, Token token) throws RampartException {
       
        RampartPolicyData rpd = rmd.getPolicyData();
        Document doc = rmd.getDocument();
       
        WSSecEncryptedKey encrKey = new WSSecEncryptedKey();
       
        try {
            RampartUtil.setKeyIdentifierType(rmd, encrKey, token);
            RampartUtil.setEncryptionUser(rmd, encrKey);
            encrKey.setKeySize(rpd.getAlgorithmSuite().getMaximumSymmetricKeyLength());
            encrKey.setKeyEncAlgo(rpd.getAlgorithmSuite().getAsymmetricKeyWrap());
           
            encrKey.prepare(doc, RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(), rmd.getCustomClassLoader()));
           
            return encrKey;
        } catch (WSSecurityException e) {
            throw new RampartException("errorCreatingEncryptedKey", e);
        }
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

    }
   
    protected WSSecSignature getSignatureBuilder(RampartMessageData rmd, Token token,
                                                 String userCertAlias) throws RampartException {

        RampartPolicyData rpd = rmd.getPolicyData();
       
        WSSecSignature sig = new WSSecSignature();
        checkForX509PkiPath(sig, token);
        sig.setWsConfig(rmd.getConfig());

        if (log.isDebugEnabled()) {
            log.debug("Token inclusion: " + token.getInclusion());
        }

        RampartUtil.setKeyIdentifierType(rmd, sig, token);

        String user = null;
       
        if (userCertAlias != null) {
            user = userCertAlias;
        }

        // Get the user - First check whether userCertAlias present
        if (user == null) {
            user = rpd.getRampartConfig().getUserCertAlias();
        }
       
        // If userCertAlias is not present, use user property as Alias
       
        if (user == null) {
            user = rpd.getRampartConfig().getUser();
        }
           
        String password = null;

        if(user != null && !"".equals(user)) {
            if (log.isDebugEnabled()) {
                log.debug("User : " + user);
            }

            //Get the password
            CallbackHandler handler = RampartUtil.getPasswordCB(rmd);
           
            if(handler == null) {
                //If the callback handler is missing
                throw new RampartException("cbHandlerMissing");
            }
           
            WSPasswordCallback[] cb = { new WSPasswordCallback(user,
                    WSPasswordCallback.SIGNATURE) };
           
            try {
                handler.handle(cb);
                if(cb[0].getPassword() != null && !"".equals(cb[0].getPassword())) {
                    password = cb[0].getPassword();
                    if (log.isDebugEnabled()) {
                        log.debug("Password : " + password);
                    }
                } else {
                    //If there's no password then throw an exception
                    throw new RampartException("noPasswordForUser",
                            new String[]{user});
                }
            } catch (IOException e) {
                throw new RampartException("errorInGettingPasswordForUser",
                        new String[]{user}, e);
            } catch (UnsupportedCallbackException e) {
                throw new RampartException("errorInGettingPasswordForUser",
                        new String[]{user}, e);
            }
           
        } else {
            log.debug("No user value specified in the configuration");
            throw new RampartException("userMissing");
        }
       
        sig.setUserInfo(user, password);
        sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getAsymmetricSignature());
        sig.setSigCanonicalization(rpd.getAlgorithmSuite().getInclusiveC14n());
       
        try {
            sig.prepare(rmd.getDocument(), RampartUtil.getSignatureCrypto(rpd
                    .getRampartConfig(), rmd.getCustomClassLoader()),
                    rmd.getSecHeader());
        } catch (WSSecurityException e) {
            throw new RampartException("errorInSignatureWithX509Token", e);
        }
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

   
    protected byte[] doSymmSignature(RampartMessageData rmd, Token policyToken, org.apache.rahas.Token tok, Vector sigParts) throws RampartException {
       
        Document doc = rmd.getDocument();
       
        RampartPolicyData rpd = rmd.getPolicyData();
       
        if(policyToken.isDerivedKeys()) {
            try {
                WSSecDKSign dkSign = new WSSecDKSign()
               
                //Check whether it is security policy 1.2 and use the secure conversation accordingly
                if (SPConstants.SP_V12 == policyToken.getVersion()) {
                    dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
                }
                             
                //Check for whether the token is attached in the message or not
                boolean attached = false;
               
                if (SPConstants.INCLUDE_TOEKN_ALWAYS == policyToken.getInclusion() ||
                    SPConstants.INCLUDE_TOKEN_ONCE == policyToken.getInclusion() ||
                    (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT
                            == policyToken.getInclusion())) {
                    attached = true;
                }
               
                // Setting the AttachedReference or the UnattachedReference according to the flag
                OMElement ref;
                if (attached == true) {
                    ref = tok.getAttachedReference();
                } else {
                    ref = tok.getUnattachedReference();
                }
               
                if(ref != null) {
                    dkSign.setExternalKey(tok.getSecret(), (Element)
                            doc.importNode((Element) ref, true));
                } else if (!rmd.isInitiator() && policyToken.isDerivedKeys()) {
                 
                  // If the Encrypted key used to create the derived key is not
                  // attached use key identifier as defined in WSS1.1 section
                  // 7.7 Encrypted Key reference
                  SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
                  if(tok instanceof EncryptedKeyToken) {
                      tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken)tok).getSHA1());;
                  }
                  dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
               
                } else {
                    dkSign.setExternalKey(tok.getSecret(), tok.getId());
                }

                //Set the algo info
                dkSign.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
                dkSign.setDerivedKeyLength(rpd.getAlgorithmSuite().getSignatureDerivedKeyLength()/8);
                if(tok instanceof EncryptedKeyToken) {
                    //Set the value type of the reference
                    dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
                        + WSConstants.ENC_KEY_VALUE_TYPE);
                }
               
                dkSign.prepare(doc, rmd.getSecHeader());
               
                if(rpd.isTokenProtection()) {

                    //Hack to handle reference id issues
                    //TODO Need a better fix
                    String sigTokId = tok.getId();
                    if(sigTokId.startsWith("#")) {
                        sigTokId = sigTokId.substring(1);
                    }
                    sigParts.add(new WSEncryptionPart(sigTokId));
                }
               
                dkSign.setParts(sigParts);
               
                dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
               
                //Do signature
                dkSign.computeSignature();

                //Add elements to header
               
                if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING) &&
                        this.getInsertionLocation() == null ) {
                    this.setInsertionLocation(RampartUtil
                           
                            .insertSiblingBefore(rmd,
                                    this.mainRefListElement,
                                    dkSign.getdktElement()));

                        this.setInsertionLocation(RampartUtil.insertSiblingAfter(
                                rmd,
                                this.getInsertionLocation(),
                                dkSign.getSignatureElement()));               
                } else {
                    this.setInsertionLocation(RampartUtil
               
                        .insertSiblingAfter(rmd,
                                this.getInsertionLocation(),
                                dkSign.getdktElement()));

                    this.setInsertionLocation(RampartUtil.insertSiblingAfter(
                            rmd,
                            this.getInsertionLocation(),
                            dkSign.getSignatureElement()));
                }

                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());
               
                // If a EncryptedKeyToken is used, set the correct value type to
                // be used in the wsse:Reference in ds:KeyInfo
                if (policyToken instanceof X509Token) {
                    if (rmd.isInitiator()) {
                        sig.setCustomTokenValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
                                + WSConstants.ENC_KEY_VALUE_TYPE);
                        sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                    } else {
                        // the tok has to be an EncryptedKey token
                        sig.setEncrKeySha1value(((EncryptedKeyToken) tok).getSHA1());
                        sig.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                    }

                } else if (policyToken instanceof IssuedToken) {
                    sig.setCustomTokenValueType(WSConstants.WSS_SAML_NS
                            + WSConstants.SAML_ASSERTION_ID);
                    sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                }
               
                String sigTokId;
               
                if ( policyToken instanceof SecureConversationToken) {
                    sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                    OMElement ref = tok.getAttachedReference();
                    if(ref == null) {
                        ref = tok.getUnattachedReference();
                    }
                   
                    if (ref != null) {
                        sigTokId = SimpleTokenStore.getIdFromSTR(ref);
                    } else {
                        sigTokId = tok.getId();
                    }
                } else {
                    sigTokId = tok.getId();
                }
                              
                //Hack to handle reference id issues
                //TODO Need a better fix
                if(sigTokId.startsWith("#")) {
                    sigTokId = sigTokId.substring(1);
                }
               
                sig.setCustomTokenId(sigTokId);
                sig.setSecretKey(tok.getSecret());
                sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getAsymmetricSignature());
                sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
                sig.prepare(rmd.getDocument(), RampartUtil.getSignatureCrypto(rpd
                        .getRampartConfig(), rmd.getCustomClassLoader()),
                        rmd.getSecHeader());

                sig.setParts(sigParts);
                sig.addReferencesToSign(sigParts, rmd.getSecHeader());

                //Do signature
                sig.computeSignature();

                if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING) &&
                        this.getInsertionLocation() == null) {
                    this.setInsertionLocation(RampartUtil.insertSiblingBefore(
                            rmd,
                            this.mainRefListElement,
                            sig.getSignatureElement()));                   
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

   
    log.debug("Enter process(MessageContext msgCtx)");

    RampartMessageData rmd = new RampartMessageData(msgCtx, false);

    RampartPolicyData rpd = rmd.getPolicyData();
   
    msgCtx.setProperty(RampartMessageData.RAMPART_POLICY_DATA, rpd);

        RampartUtil.validateTransport(rmd);

        // If there is no policy information return immediately
        if (rpd == null) {
           return null;
        }


        //TODO these checks have to be done before the convertion to avoid unnecessary convertion to LLOM -> DOOM
        // If the message is a security fault or no security
        // header required by the policy
        if(isSecurityFault(rmd) || !RampartUtil.isSecHeaderRequired(rpd,rmd.isInitiator(),true)) {
      SOAPEnvelope env = Axis2Util.getSOAPEnvelopeFromDOMDocument(rmd.getDocument(), true);

      //Convert back to llom since the inflow cannot use llom
      msgCtx.setEnvelope(env);
      Axis2Util.useDOOM(false);
            log.debug("Return process MessageContext msgCtx)");
            return null;
    }


    Vector results = null;

    WSSecurityEngine engine = new WSSecurityEngine();

    ValidatorData data = new ValidatorData(rmd);

    SOAPHeader header = rmd.getMsgContext().getEnvelope().getHeader();
    if(header == null) {
        throw new RampartException("missingSOAPHeader");
    }
   
                ArrayList headerBlocks = header.getHeaderBlocksWithNSURI(WSConstants.WSSE_NS);
    SOAPHeaderBlock secHeader = null;
    //Issue is axiom - a returned collection must not be null
    if(headerBlocks != null) {
        Iterator headerBlocksIterator = headerBlocks.iterator();
        while (headerBlocksIterator.hasNext()) {
          SOAPHeaderBlock elem = (SOAPHeaderBlock) headerBlocksIterator.next();
          if(elem.getLocalName().equals(WSConstants.WSSE_LN)) {
            secHeader = elem;
            break;
          }
        }
    }
   
    if(secHeader == null) {
        throw new RampartException("missingSecurityHeader");
    }
   
    long t0=0, t1=0, t2=0, t3=0;
    if(dotDebug){
      t0 = System.currentTimeMillis();
    }

    String actorValue = secHeader.getAttributeValue(new QName(rmd
        .getSoapConstants().getEnvelopeURI(), "actor"));

    Crypto signatureCrypto = RampartUtil.getSignatureCrypto(rpd.getRampartConfig(),
            msgCtx.getAxisService().getClassLoader());
        TokenCallbackHandler tokenCallbackHandler = new TokenCallbackHandler(rmd.getTokenStorage(), RampartUtil.getPasswordCB(rmd));
        if(rpd.isSymmetricBinding()) {
      //Here we have to create the CB handler to get the tokens from the
      //token storage
      log.debug("Processing security header using SymetricBinding");
      results = engine.processSecurityHeader(rmd.getDocument(),
          actorValue,
          tokenCallbackHandler,
          signatureCrypto,
                  RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(),
                          msgCtx.getAxisService().getClassLoader()));

            // Remove encryption tokens if this is the initiator and if initiator is receiving a message

            if (rmd.isInitiator() && (msgCtx.getFLOW() == MessageContext.IN_FLOW ||
                    msgCtx.getFLOW() == MessageContext.IN_FAULT_FLOW)) {
                tokenCallbackHandler.removeEncryptedToken();
            }

    } else {
      log.debug("Processing security header in normal path");
      results = engine.processSecurityHeader(rmd.getDocument(),
          actorValue,
          tokenCallbackHandler,
          signatureCrypto,
              RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(),
                  msgCtx.getAxisService().getClassLoader()));
    }

    if(dotDebug){
      t1 = System.currentTimeMillis();
    }

                //Store symm tokens
                //Pick the first SAML token
                //TODO : This is a hack , MUST FIX
                //get the sec context id from the req msg ctx
   
    //Store username in MessageContext property

        for (int j = 0; j < results.size(); j++) {
            WSSecurityEngineResult wser = (WSSecurityEngineResult) results.get(j);
            final Integer actInt =
                    (Integer) wser.get(WSSecurityEngineResult.TAG_ACTION);
            if (WSConstants.ST_UNSIGNED == actInt.intValue()) {

                // If this is a SAML2.0 assertion
                if (wser.get(WSSecurityEngineResult.TAG_SAML_ASSERTION) instanceof Assertion) {
                    final Assertion assertion = (Assertion) wser.get(
                            WSSecurityEngineResult.TAG_SAML_ASSERTION);

                    // if the subject confirmation method is Bearer, do not try to get the KeyInfo
                    if(TrustUtil.getSAML2SubjectConfirmationMethod(assertion).equals(
                            RahasConstants.SAML20_SUBJECT_CONFIRMATION_BEARER)){
                        break;
                    }

                    String id = assertion.getID();
                    Subject subject = assertion.getSubject();

                    Date dateOfCreation = null;
                    Date dateOfExpiration = null;

                    //Read the validity period from the 'Conditions' element, else read it from SC Data
                    if (assertion.getConditions() != null) {
                        Conditions conditions = assertion.getConditions();
                        if (conditions.getNotBefore() != null) {
                            dateOfCreation = conditions.getNotBefore().toDate();
                        }
                        if (conditions.getNotOnOrAfter() != null) {
                            dateOfExpiration = conditions.getNotOnOrAfter().toDate();
                        }
                    } else {
                        SubjectConfirmationData scData = subject.getSubjectConfirmations()
                                .get(0).getSubjectConfirmationData();
                        if (scData.getNotBefore() != null) {
                            dateOfCreation = scData.getNotBefore().toDate();
                        }
                        if (scData.getNotOnOrAfter() != null) {
                            dateOfExpiration = scData.getNotOnOrAfter().toDate();
                        }
                    }

                    // TODO : SAML2KeyInfo element needs to be moved to WSS4J.
                    SAML2KeyInfo saml2KeyInfo = SAML2Utils.
                            getSAML2KeyInfo(assertion, signatureCrypto, tokenCallbackHandler);

                    //Store the token
                    try {
                        TokenStorage store = rmd.getTokenStorage();
                        if (store.getToken(id) == null) {
                            Token token = new Token(id, (OMElement) SAML2Utils.getElementFromAssertion(assertion), dateOfCreation, dateOfExpiration);
                            token.setSecret(saml2KeyInfo.getSecret());
                            store.add(token);
                        }
                    } catch (Exception e) {
                        throw new RampartException(
                                "errorInAddingTokenIntoStore", e);
                    }

                }
                //if this is a SAML1.1 assertion
                else {
                    final SAMLAssertion assertion = ((SAMLAssertion) wser.get(
                            WSSecurityEngineResult.TAG_SAML_ASSERTION));

                    // if the subject confirmation method is Bearer, do not try to get the KeyInfo
                    if(RahasConstants.SAML11_SUBJECT_CONFIRMATION_BEARER.equals(
                            TrustUtil.getSAML11SubjectConfirmationMethod(assertion))){
                        break;
                    }

                    String id = assertion.getId();
                    Date created = assertion.getNotBefore();
                    Date expires = assertion.getNotOnOrAfter();
                    SAMLKeyInfo samlKi = SAMLUtil.getSAMLKeyInfo(assertion,
                            signatureCrypto, tokenCallbackHandler);
                    try {
                        TokenStorage store = rmd.getTokenStorage();
                        if (store.getToken(id) == null) {
                            Token token = new Token(id, (OMElement) assertion.toDOM(), created, expires);
                            token.setSecret(samlKi.getSecret());
                            store.add(token);
                        }
                    } catch (Exception e) {
                        throw new RampartException(
                                "errorInAddingTokenIntoStore", e);
                    }

                }
            } else if (WSConstants.UT == actInt.intValue()) {

            WSUsernameTokenPrincipal userNameTokenPrincipal = (WSUsernameTokenPrincipal)wser.get(WSSecurityEngineResult.TAG_PRINCIPAL);

                String username = userNameTokenPrincipal.getName();
                msgCtx.setProperty(RampartMessageData.USERNAME, username);
               
                if (userNameTokenPrincipal.getNonce() != null) {
                    // Check whether this is a replay attack. To verify that we need to check whether nonce value
                    // is a repeating one
                    int nonceLifeTimeInSeconds = 0;

                    if (rpd.getRampartConfig() != null) {
                       
                        String stringLifeTime = rpd.getRampartConfig().getNonceLifeTime();

                        try {
                            nonceLifeTimeInSeconds = Integer.parseInt(stringLifeTime);

                        } catch (NumberFormatException e) {
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

    public void validate(ValidatorData data, Vector results)
    throws RampartException {
       
        RampartMessageData rmd = data.getRampartMessageData();
       
        RampartPolicyData rpd = rmd.getPolicyData();
       
        //If there's Security policy present and no results
        //then we should throw an error
        if(rpd != null && results == null) {
            throw new RampartException("noSecurityResults");
        }
       
        //Check presence of timestamp
        WSSecurityEngineResult tsResult = null;
        if(rpd != null &&  rpd.isIncludeTimestamp()) {
            tsResult =
                WSSecurityUtil.fetchActionResult(results, WSConstants.TS);
            if(tsResult == null && !rpd.isIncludeTimestampOptional()) {
                throw new RampartException("timestampMissing");
            }
           
        }
       
        //sig/encr
        Vector encryptedParts = RampartUtil.getEncryptedParts(rmd);
        if(rpd != null && rpd.isSignatureProtection() && isSignatureRequired(rmd)) {
           
            String sigId = RampartUtil.getSigElementId(rmd);
           
            encryptedParts.add(new WSEncryptionPart(WSConstants.SIG_LN,
                    WSConstants.SIG_NS, "Element"));
        }
       
        Vector signatureParts = RampartUtil.getSignedParts(rmd);

        //Timestamp is not included in sig parts
    if (tsResult != null || !rpd.isIncludeTimestampOptional()) {
      if (rpd != null && rpd.isIncludeTimestamp()
          && !rpd.isTransportBinding()) {
        signatureParts.add(new WSEncryptionPart("timestamp"));
      }
    }
       
        if(!rmd.isInitiator()) {
                       
            //Just an indicator for EndorsingSupportingToken signature
            SupportingToken endSupportingToken = rpd.getEndorsingSupportingTokens();
            if(endSupportingToken !=  null && !endSupportingToken.isOptional()) {
                SignedEncryptedParts endSignedParts = endSupportingToken.getSignedParts();
                if((endSignedParts != null && !endSignedParts.isOptional() &&
                        (endSignedParts.isBody() ||
                                endSignedParts.getHeaders().size() > 0)) ||
                                rpd.isIncludeTimestamp()) {
                    signatureParts.add(
                            new WSEncryptionPart("EndorsingSupportingTokens"));
                }
            }
            //Just an indicator for SignedEndorsingSupportingToken signature
            SupportingToken sgndEndSupportingToken = rpd.getSignedEndorsingSupportingTokens();
            if(sgndEndSupportingToken != null && !sgndEndSupportingToken.isOptional()) {
                SignedEncryptedParts sgndEndSignedParts = sgndEndSupportingToken.getSignedParts();
                if((sgndEndSignedParts != null && !sgndEndSignedParts.isOptional() &&
                        (sgndEndSignedParts.isBody() ||
                                sgndEndSignedParts.getHeaders().size() > 0)) ||
                                rpd.isIncludeTimestamp()) {
                    signatureParts.add(
                            new WSEncryptionPart("SignedEndorsingSupportingTokens"));
                }
            }
           
            Vector supportingToks = rpd.getSupportingTokensList();
            for (int i = 0; i < supportingToks.size(); i++) {
                SupportingToken supportingToken = (SupportingToken) supportingToks.get(i);
                if (supportingToken != null && !supportingToken.isOptional()) {
                    SupportingPolicyData policyData = new SupportingPolicyData();
                    policyData.build(supportingToken);
                    encryptedParts.addAll(RampartUtil.getSupportingEncryptedParts(rmd, policyData));
                    signatureParts.addAll(RampartUtil.getSupportingSignedParts(rmd, policyData));
                }
            }
        }
       
        validateEncrSig(data,encryptedParts, signatureParts, results);
       
        if(!rpd.isTransportBinding()) {
            validateProtectionOrder(data, results);
       
       
        validateEncryptedParts(data, encryptedParts, results);
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

        long t0 = 0, t1 = 0;
      if(tlog.isDebugEnabled()){
        t1 = System.currentTimeMillis();
      }
       
        RampartPolicyData rpd = rmd.getPolicyData();
       
        if (rpd.isIncludeTimestamp()) {
          addTimestamp(rmd);
        }
      
        /*
         * Process Supporting tokens
         */
        if(rmd.isInitiator()) {
            Vector signatureValues = new Vector();
           
            SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
           
            if(sgndSuppTokens != null && sgndSuppTokens.getTokens() != null &&
                    sgndSuppTokens.getTokens().size() > 0) {

                log.debug("Processing signed supporting tokens");

                ArrayList tokens = sgndSuppTokens.getTokens();
                for (Iterator iter = tokens.iterator(); iter.hasNext();) {
                   
                    Token token = (Token) iter.next();
                    if(token instanceof UsernameToken) {
                        WSSecUsernameToken utBuilder = addUsernameToken(rmd,(UsernameToken)token);
                       
                        utBuilder.prepare(rmd.getDocument());
                       
                        //Add the UT
                        utBuilder.appendToHeader(rmd.getSecHeader());
                       
                    } else {
                        throw new RampartException("unsupportedSignedSupportingToken",
                                new String[]{"{" +token.getName().getNamespaceURI()
                                + "}" + token.getName().getLocalPart()});
                    }
                }
            }
           
            SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();
            if(sgndEndSuppTokens != null && sgndEndSuppTokens.getTokens() != null &&
                    sgndEndSuppTokens.getTokens().size() > 0) {

                log.debug("Processing endorsing signed supporting tokens");

                ArrayList tokens = sgndEndSuppTokens.getTokens();
                SignedEncryptedParts signdParts = sgndEndSuppTokens.getSignedParts();
                for (Iterator iter = tokens.iterator(); iter.hasNext();) {
                    Token token = (Token) iter.next();
                    if(token instanceof IssuedToken && rmd.isInitiator()) {
                        signatureValues.add(doIssuedTokenSignature(rmd, token, signdParts));
                    } else if(token instanceof X509Token) {
                        signatureValues.add(doX509TokenSignature(rmd, token, signdParts));
                    }
                }
            }
   
            SupportingToken endSupptokens = rpd.getEndorsingSupportingTokens();
            if(endSupptokens != null && endSupptokens.getTokens() != null &&
                    endSupptokens.getTokens().size() > 0) {
                log.debug("Processing endorsing supporting tokens");
                ArrayList tokens = endSupptokens.getTokens();
                SignedEncryptedParts signdParts = endSupptokens.getSignedParts();
                for (Iterator iter = tokens.iterator(); iter.hasNext();) {
                    Token token = (Token) iter.next();
                    if(token instanceof IssuedToken && rmd.isInitiator()){
                        signatureValues.add(doIssuedTokenSignature(rmd, token, signdParts));
                    } else if(token instanceof X509Token) {
                        signatureValues.add(doX509TokenSignature(rmd, token, signdParts));
                    } else if (token instanceof SecureConversationToken) {
                        handleSecureConversationTokens(rmd, (SecureConversationToken)token);
                        signatureValues.add(doSecureConversationSignature(rmd, token, signdParts));                                              
                    }
                }
            }
           
           
            Vector supportingToks = rpd.getSupportingTokensList();
            for (int i = 0; i < supportingToks.size(); i++) {
                this.handleSupportingTokens(rmd, (SupportingToken)supportingToks.get(i));
            }
           
           
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

     * @param token
     * @param signdParts
     */
    private byte[] doX509TokenSignature(RampartMessageData rmd, Token token, SignedEncryptedParts signdParts) throws RampartException {
       
        RampartPolicyData rpd = rmd.getPolicyData();
        Document doc = rmd.getDocument();
       
        Vector sigParts = new Vector();
       
        if(this.timestampElement != null){
            sigParts.add(new WSEncryptionPart(rmd.getTimestampId()));                         
        }
       
        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);
            }
        }
        if(token.isDerivedKeys()) {
            //In this case we will have to encrypt the ephmeral key with the
            //other party's key and then use it as the parent key of the
            // derived keys
            try {
               
                WSSecEncryptedKey encrKey = getEncryptedKeyBuilder(rmd, token);
               
                Element bstElem = encrKey.getBinarySecurityTokenElement();
                if(bstElem != null) {
                   RampartUtil.appendChildToSecHeader(rmd, bstElem);
                }
               
                encrKey.appendToHeader(rmd.getSecHeader());
               
                WSSecDKSign dkSig = new WSSecDKSign();
               
                dkSig.setWsConfig(rmd.getConfig());
               
                dkSig.setSigCanonicalization(rpd.getAlgorithmSuite().getInclusiveC14n());
                dkSig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
                dkSig.setDerivedKeyLength(rpd.getAlgorithmSuite().getSignatureDerivedKeyLength()/8);
               
                dkSig.setExternalKey(encrKey.getEphemeralKey(), encrKey.getId());
               
                dkSig.prepare(doc, rmd.getSecHeader());
               
               
                if(rpd.isTokenProtection()) {
                    sigParts.add(new WSEncryptionPart(encrKey.getBSTTokenId()));
                }
               
                dkSig.setParts(sigParts);
               
                dkSig.addReferencesToSign(sigParts, rmd.getSecHeader());
               
                //Do signature
                dkSig.computeSignature();
               
                dkSig.appendDKElementToHeader(rmd.getSecHeader());

                dkSig.appendSigToHeader(rmd.getSecHeader());
               
                return dkSig.getSignatureValue();
               
            } catch (WSSecurityException e) {
                throw new RampartException("errorInDerivedKeyTokenSignature", e);
            } catch (ConversationException e) {
                throw new RampartException("errorInDerivedKeyTokenSignature", e);
            }
           
        } else {
           
            try {
                WSSecSignature sig = this.getSignatureBuilder(rmd, token);
               

                sig.appendBSTElementToHeader(rmd.getSecHeader());
               
                if (rpd.isTokenProtection()
                        && !(SPConstants.INCLUDE_TOKEN_NEVER == token.getInclusion())) {
                    sigParts.add(new WSEncryptionPart(sig.getBSTTokenId()));
                }
               
                sig.addReferencesToSign(sigParts, rmd.getSecHeader());
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

            } else if(act.intValue() == WSConstants.ENCR) {
                encr = true;
            }
        }
       
        RampartPolicyData rpd = data.getRampartMessageData().getPolicyData();
       
        SupportingToken sgndSupTokens = rpd.getSignedSupportingTokens();
        SupportingToken sgndEndorSupTokens = rpd.getSignedEndorsingSupportingTokens();
       
        if(sig && signatureParts.size() == 0
                && (sgndSupTokens == null || sgndSupTokens.getTokens().size() == 0)
                 && (sgndEndorSupTokens == null || sgndEndorSupTokens.getTokens().size() == 0)) {
           
View Full Code Here

Examples of org.apache.rampart.policy.RampartPolicyData

     * @param signdParts
     * @throws RampartException
     */
    private byte[] doIssuedTokenSignature(RampartMessageData rmd, Token token, SignedEncryptedParts signdParts) throws RampartException {
       
        RampartPolicyData rpd = rmd.getPolicyData();
        Document doc= rmd.getDocument();
       
        //Get the issued token
        String id = RampartUtil.getIssuedToken(rmd, (IssuedToken)token);
  
        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());
                String tokId = tok.getId();
                if (tokId.charAt(0) == '#') {
        tokId = tokId.substring(1);
                }
                sig.setCustomTokenId(tokId);
                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

     */
    protected void validateSupportingTokens(ValidatorData data, Vector results)
    throws RampartException {
       
        //Check for UsernameToken
        RampartPolicyData rpd = data.getRampartMessageData().getPolicyData();
        Vector supportingToks = rpd.getSupportingTokensList();
        for (int i = 0; i < supportingToks.size(); i++) {
            SupportingToken suppTok = (SupportingToken) supportingToks.get(i);
            handleSupportingTokens(results, suppTok);
        }
        SupportingToken signedSuppToken = rpd.getSignedSupportingTokens();
        handleSupportingTokens(results, signedSuppToken);
        SupportingToken signedEndSuppToken = rpd.getSignedEndorsingSupportingTokens();
        handleSupportingTokens(results, signedEndSuppToken);
        SupportingToken endSuppToken = rpd.getEndorsingSupportingTokens();
        handleSupportingTokens(results, endSuppToken);
    }
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.