Package org.apache.rampart.policy

Examples of org.apache.rampart.policy.RampartPolicyData


      
    }

    public static void validateTransport(RampartMessageData rmd) throws RampartException {

        RampartPolicyData rpd = rmd.getPolicyData();

        if (rpd == null) {
            return;
        }

        if (rpd.isTransportBinding() && !rmd.isInitiator()) {
            if (rpd.getTransportToken() instanceof HttpsToken) {
                String incomingTransport = rmd.getMsgContext().getIncomingTransportName();
                if (!incomingTransport.equals(org.apache.axis2.Constants.TRANSPORT_HTTPS)) {
                    throw new RampartException("invalidTransport",
                            new String[]{incomingTransport});
                }
                if (((HttpsToken) rpd.getTransportToken()).isRequireClientCertificate()) {

                    MessageContext messageContext = rmd.getMsgContext();
                    HttpServletRequest request = ((HttpServletRequest) messageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST));
                    if (request == null || request.getAttribute("javax.servlet.request.X509Certificate") == null) {
                        throw new RampartException("clientAuthRequired");
View Full Code Here


        if (servicePolicy == null) {
          //Missing service policy means no security requirement
          return null;
        }
        List it = (List) servicePolicy.getAlternatives().next();
        RampartPolicyData rpd = RampartPolicyBuilder.build(it);

        SecureConversationToken secConvTok = null;

        org.apache.ws.secpolicy.model.Token encrtok = rpd
            .getEncryptionToken();
        secConvTok = (encrtok != null && encrtok instanceof SecureConversationToken) ? (SecureConversationToken) encrtok
            : null;

        if (secConvTok == null) {
          org.apache.ws.secpolicy.model.Token sigtok = rpd
              .getSignatureToken();
          secConvTok = (sigtok != null && sigtok instanceof SecureConversationToken) ? (SecureConversationToken) sigtok
              : null;
        }

        if (secConvTok != null) {

          Policy issuerPolicy = secConvTok.getBootstrapPolicy();
          issuerPolicy.addAssertion(rpd.getRampartConfig());

          STSClient client = new STSClient(message
              .getConfigurationContext());
          Options op = new Options();
          op.setProperty(SandeshaClientConstants.UNRELIABLE_MESSAGE,
              Constants.VALUE_TRUE);
          client.setOptions(op);
          client.setAction(action);
          client.setRstTemplate(rstTmpl);
          client.setCryptoInfo(RampartUtil.getEncryptionCrypto(rpd
              .getRampartConfig(), message.getAxisService()
              .getClassLoader()), RampartUtil.getPasswordCB(
              message, rpd));
          String address = message.getTo().getAddress();
          Token tok = client.requestSecurityToken(servicePolicy,
View Full Code Here

     */
    protected WSSecUsernameToken addUsernameToken(RampartMessageData rmd, UsernameToken token) throws RampartException {
      
        log.debug("Adding a UsernameToken");
       
        RampartPolicyData rpd = rmd.getPolicyData();
       
        //Get the user
        //First try options
        Options options = rmd.getMsgContext().getOptions();
        String user = options.getUserName();
        if(user == null || user.length() == 0) {
            //Then try RampartConfig
            if(rpd.getRampartConfig() != null) {
                user = rpd.getRampartConfig().getUser();
            }
        }
       
        if(user != null && !"".equals(user)) {
            log.debug("User : " + user);
View Full Code Here

     * @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(rpd, 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

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

        RampartPolicyData rpd = rmd.getPolicyData();
       
        WSSecSignature sig = new WSSecSignature();
        checkForX509PkiPath(sig, token);
        sig.setWsConfig(rmd.getConfig());
       
        log.debug("Token inclusion: " + token.getInclusion());
       
        RampartUtil.setKeyIdentifierType(rpd, 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)) {
            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();
                    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

   
    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

      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);
      if(doDebug){
        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
      if(doDebug){
        log.debug("Processing security header using SymetricBinding");
      }
      results = engine.processSecurityHeader(rmd.getDocument(),
          actorValue,
          tokenCallbackHandler,
          signatureCrypto,
                  RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(),
                          msgCtx.getAxisService().getClassLoader()));
    } else {
      if(doDebug){
        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();
View Full Code Here

    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) {
                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(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) {
                SignedEncryptedParts endSignedParts = endSupportingToken.getSignedParts();
                if((endSignedParts != null &&
                        (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) {
                SignedEncryptedParts sgndEndSignedParts = sgndEndSupportingToken.getSignedParts();
                if((sgndEndSignedParts != null &&
                        (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) {
                    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

            } 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

        try {
            Iterator alternatives = policy.getAlternatives();
            if (alternatives.hasNext()) {
                List it = (List) alternatives.next();

                RampartPolicyData rampartPolicyData = RampartPolicyBuilder.build(it);
                if (rampartPolicyData.isTransportBinding()) {
                    httpsRequired = true;
                } else if (rampartPolicyData.isSymmetricBinding()) {
                    Token encrToken = rampartPolicyData.getEncryptionToken();
                    if (encrToken instanceof SecureConversationToken) {
                        Policy bsPol = ((SecureConversationToken) encrToken).getBootstrapPolicy();
                        Iterator alts = bsPol.getAlternatives();
                        if (alts.hasNext()) {
                        }
                        List bsIt = (List) alts.next();
                        RampartPolicyData bsRampartPolicyData = RampartPolicyBuilder.build(bsIt);
                        httpsRequired = bsRampartPolicyData.isTransportBinding();
                    }
                }
            }
        } catch (WSSPolicyException e) {
            log.error(e);
View Full Code Here

TOP

Related Classes of org.apache.rampart.policy.RampartPolicyData

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.