Package org.apache.ws.security.handler

Examples of org.apache.ws.security.handler.RequestData


        Signature signature,
        Document doc,
        Crypto sigCrypto,
        CallbackHandler callbackHandler
    ) throws WSSecurityException {
        RequestData requestData = new RequestData();
        requestData.setSigCrypto(sigCrypto);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        requestData.setWssConfig(wssConfig);
        requestData.setCallbackHandler(callbackHandler);
        WSDocInfo docInfo = new WSDocInfo(doc);
       
        KeyInfo keyInfo = signature.getKeyInfo();
        SAMLKeyInfo samlKeyInfo = null;
        try {
            samlKeyInfo =
                SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), requestData, docInfo,
                    requestData.getWssConfig().isWsiBSPCompliant()
                );
        } catch (WSSecurityException ex) {
            LOG.log(Level.FINE, "Error in getting KeyInfo from SAML Response: " + ex.getMessage(), ex);
            throw ex;
        }
View Full Code Here


        Document doc
    ) throws WSSecurityException {
        Credential credential = new Credential();
        credential.setAssertion(assertion);
       
        RequestData requestData = new RequestData();
        requestData.setSigCrypto(sigCrypto);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        requestData.setWssConfig(wssConfig);
        requestData.setCallbackHandler(callbackHandler);
       
        if (assertion.isSigned()) {
            if (assertion.getSaml1() != null) {
                assertion.getSaml1().getDOM().setIdAttributeNS(null, "AssertionID", true);
            } else {
View Full Code Here

    protected WSSecurityEngineResult validateToken(Element tokenElement, final SoapMessage message)
        throws WSSecurityException {
        UsernameTokenProcessor p = new UsernameTokenProcessor();
        WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument());
        RequestData data = new RequestData() {
            public CallbackHandler getCallbackHandler() {
                return getCallback(message);
            }
            public Validator getValidator(QName qName) throws WSSecurityException {
                Object validator =
                    message.getContextualProperty(SecurityConstants.USERNAME_TOKEN_VALIDATOR);
                if (validator == null) {
                    return super.getValidator(qName);
                }
                return (Validator)validator;
            }
        };
       
        // Configure replay caching
        ReplayCache nonceCache =
            WSS4JUtils.getReplayCache(
                message, SecurityConstants.ENABLE_NONCE_CACHE, SecurityConstants.NONCE_CACHE_INSTANCE
            );
        data.setNonceReplayCache(nonceCache);
       
        WSSConfig config = WSSConfig.getNewInstance();
        boolean bspCompliant = isWsiBSPCompliant(message);
        boolean allowNoPassword = isAllowNoPassword(message.get(AssertionInfoMap.class));
        config.setWsiBSPCompliant(bspCompliant);
        config.setAllowUsernameTokenNoPassword(allowNoPassword);
        data.setWssConfig(config);
        List<WSSecurityEngineResult> results =
            p.handleToken(tokenElement, data, wsDocInfo);
       
        return results.get(0);
    }
View Full Code Here

       
        boolean utWithCallbacks =
            MessageUtils.getContextualBoolean(msg, SecurityConstants.VALIDATE_TOKEN, true);
        translateProperties(msg);
       
        RequestData reqData = new CXFRequestData();

        WSSConfig config = (WSSConfig)msg.getContextualProperty(WSSConfig.class.getName());
        WSSecurityEngine engine;
        if (config != null) {
            engine = new WSSecurityEngine();
            engine.setWssConfig(config);
        } else {
            engine = getSecurityEngine(utWithCallbacks);
            if (engine == null) {
                engine = new WSSecurityEngine();
            }
            config = engine.getWssConfig();
        }
        reqData.setWssConfig(config);
       
               
        SOAPMessage doc = getSOAPMessage(msg);
       
        boolean doDebug = LOG.isLoggable(Level.FINE);

        SoapVersion version = msg.getVersion();
        if (doDebug) {
            LOG.fine("WSS4JInInterceptor: enter handleMessage()");
        }

        /*
         * The overall try, just to have a finally at the end to perform some
         * housekeeping.
         */
        try {
            reqData.setMsgContext(msg);
            setAlgorithmSuites(msg, reqData);
            computeAction(msg, reqData);
            List<Integer> actions = new ArrayList<Integer>();
            String action = getAction(msg, version);

            int doAction = WSSecurityUtil.decodeAction(action, actions);

            String actor = (String)getOption(WSHandlerConstants.ACTOR);
            if (actor == null) {
                actor = (String)msg.getContextualProperty(SecurityConstants.ACTOR);
            }

            reqData.setCallbackHandler(getCallback(reqData, doAction, utWithCallbacks));
           
            String passwordTypeStrict = (String)getOption(WSHandlerConstants.PASSWORD_TYPE_STRICT);
            if (passwordTypeStrict == null) {
                setProperty(WSHandlerConstants.PASSWORD_TYPE_STRICT, "true");
            }
           
            // Configure replay caching
            configureReplayCaches(reqData, doAction, msg);
           
            /*
             * Get and check the Signature specific parameters first because
             * they may be used for encryption too.
             */
            doReceiverAction(doAction, reqData);
           
            /*get chance to check msg context enableRevocation setting
             *when use policy based ws-security where the WSHandler configuration
             *isn't available
             */
            boolean enableRevocation = reqData.isRevocationEnabled()
                || MessageUtils.isTrue(msg.getContextualProperty(SecurityConstants.ENABLE_REVOCATION));
            reqData.setEnableRevocation(enableRevocation);
           
            Element elem = WSSecurityUtil.getSecurityHeader(doc.getSOAPPart(), actor);

            List<WSSecurityEngineResult> wsResult = engine.processSecurityHeader(
                elem, reqData
            );

            if (wsResult != null && !wsResult.isEmpty()) { // security header found
                if (reqData.getWssConfig().isEnableSignatureConfirmation()) {
                    checkSignatureConfirmation(reqData, wsResult);
                }

                storeSignature(msg, reqData, wsResult);
                storeTimestamp(msg, reqData, wsResult);
                checkActions(msg, reqData, wsResult, actions, SAAJUtils.getBody(doc));
                doResults(
                    msg, actor,
                    SAAJUtils.getHeader(doc),
                    SAAJUtils.getBody(doc),
                    wsResult, utWithCallbacks
                );
            } else { // no security header found
                // Create an empty result list to pass into the required validation
                // methods.
                wsResult = new ArrayList<WSSecurityEngineResult>();
                if (doc.getSOAPPart().getEnvelope().getBody().hasFault()) {
                    LOG.warning("Request does not contain Security header, "
                                + "but it's a fault.");
                    // We allow lax action matching here for backwards compatibility
                    // with manually configured WSS4JInInterceptors that previously
                    // allowed faults to pass through even if their actions aren't
                    // a strict match against those configured.  In the WS-SP case,
                    // we will want to still call doResults as it handles asserting
                    // certain assertions that do not require a WS-S header such as
                    // a sp:TransportBinding assertion.  In the case of WS-SP,
                    // the unasserted assertions will provide confirmation that
                    // security was not sufficient.
                    // checkActions(msg, reqData, wsResult, actions);
                    doResults(msg, actor,
                              SAAJUtils.getHeader(doc),
                              SAAJUtils.getBody(doc),
                              wsResult);
                } else {
                    checkActions(msg, reqData, wsResult, actions, SAAJUtils.getBody(doc));
                    doResults(msg, actor,
                              SAAJUtils.getHeader(doc),
                              SAAJUtils.getBody(doc),
                              wsResult);
                }
            }
            advanceBody(msg, SAAJUtils.getBody(doc));
            SAAJInInterceptor.replaceHeaders(doc, msg);

            if (doDebug) {
                LOG.fine("WSS4JInInterceptor: exit handleMessage()");
            }
            msg.put(SECURITY_PROCESSED, Boolean.TRUE);

        } catch (WSSecurityException e) {
            LOG.log(Level.WARNING, "", e);
            SoapFault fault = createSoapFault(msg, version, e);
            throw fault;
        } catch (XMLStreamException e) {
            throw new SoapFault(new Message("STAX_EX", LOG), e, version.getSender());
        } catch (SOAPException e) {
            throw new SoapFault(new Message("SAAJ_EX", LOG), e, version.getSender());
        } finally {
            reqData.clear();
            reqData = null;
        }
    }
View Full Code Here

            return cipherValue;
        } else {
            try {
                EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
                WSDocInfo docInfo = new WSDocInfo(child.getOwnerDocument());
                RequestData data = new RequestData();
                data.setWssConfig(WSSConfig.getNewInstance());
                data.setDecCrypto(createCrypto(true));
                data.setCallbackHandler(createHandler());
                List<WSSecurityEngineResult> result =
                    proc.handleToken(child, data, docInfo);
                return
                    (byte[])result.get(0).get(
                        WSSecurityEngineResult.TAG_SECRET
View Full Code Here

        }
    }

    protected void validateToken(Message message, AssertionWrapper assertion) {
        try {
            RequestData data = new RequestData();
            if (assertion.isSigned()) {
                WSSConfig cfg = WSSConfig.getNewInstance();
                data.setWssConfig(cfg);
                data.setCallbackHandler(SecurityUtils.getCallbackHandler(message, this.getClass()));
                try {
                    data.setSigCrypto(new CryptoLoader().getCrypto(message,
                                                SecurityConstants.SIGNATURE_CRYPTO,
                                                SecurityConstants.SIGNATURE_PROPERTIES));
                } catch (IOException ex) {
                    throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
                }
                data.setEnableRevocation(MessageUtils.isTrue(
                    message.getContextualProperty(WSHandlerConstants.ENABLE_REVOCATION)));
                assertion.verifySignature(data, null);
            } else if (getTLSCertificates(message) == null) {
                throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
            }
View Full Code Here

        assertFalse(tokenString.contains(SAML2Constants.CONF_BEARER));
        assertTrue(tokenString.contains(SAML2Constants.CONF_HOLDER_KEY));
       
        // Test that the (encrypted) secret sent in Entropy was used in the SAML Subject KeyInfo
        AssertionWrapper assertionWrapper = new AssertionWrapper(assertion);
        RequestData data = new RequestData();
       
        Properties properties = new Properties();
        properties.put(
            "org.apache.ws.security.crypto.provider", "org.apache.ws.security.components.crypto.Merlin"
        );
        properties.put("org.apache.ws.security.crypto.merlin.keystore.password", "sspass");
        properties.put("org.apache.ws.security.crypto.merlin.keystore.file", "servicestore.jks");
       
        data.setDecCrypto(CryptoFactory.getInstance(properties));
        data.setCallbackHandler(new PasswordCallbackHandler());
        data.setWssConfig(WSSConfig.getNewInstance());
       
        assertionWrapper.parseHOKSubject(data, new WSDocInfo(assertion.getOwnerDocument()));
        SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
        assertTrue(Arrays.equals(secret, samlKeyInfo.getSecret()));
    }
View Full Code Here

    public Crypto loadSignatureCrypto(RequestData reqData) throws WSSecurityException {
        return crypto;
    }
   
    public void onReceive(Context context) throws Exception {
        RequestData reqData = new RequestData();
        init(context);
        try {
            reqData.setNoSerialization(true);
            reqData.setMsgContext(context);

            Vector actions = new Vector();
            String action = this.receiveAction;
            if (action == null) {
                throw new IllegalStateException("WSSecurityHandler: No receiveAction defined");
            }
            int doAction = WSSecurityUtil.decodeAction(action, actions);

            Document doc = context.getInMessage().getDocument();
            if (doc == null) {
                throw new IllegalStateException("WSSecurityHandler: The soap message has not been parsed using DOM");
            }

            /*
             * Get and check the Signature specific parameters first because
             * they may be used for encryption too.
             */
            doReceiverAction(doAction, reqData);

            Vector wsResult = null;

            try {
                wsResult = secEngine.processSecurityHeader(
                                doc, actor, handler,
                                reqData.getSigCrypto(),
                                reqData.getDecCrypto());
            } catch (WSSecurityException ex) {
                throw new SoapFault(ex);
            }

            if (wsResult == null) { // no security header found
                if (doAction == WSConstants.NO_SECURITY) {
                    return;
                } else {
                    throw new SoapFault(new WSSecurityException(
                                    "WSSecurityHandler: Request does not contain required Security header"));
                }
            }

            if (reqData.getWssConfig().isEnableSignatureConfirmation()) {
                checkSignatureConfirmation(reqData, wsResult);
            }

            /*
             * Now we can check the certificate used to sign the message. In the
             * following implementation the certificate is only trusted if
             * either it itself or the certificate of the issuer is installed in
             * the keystore.
             *
             * Note: the method verifyTrust(X509Certificate) allows custom
             * implementations with other validation algorithms for subclasses.
             */

            // Extract the signature action result from the action vector
            WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.SIGN);

            if (actionResult != null) {
                X509Certificate returnCert = actionResult.getCertificate();

                if (returnCert != null) {
                    if (!verifyTrust(returnCert, reqData)) {
                        throw new SoapFault(new WSSecurityException(
                                        "WSSecurityHandler: the certificate used for the signature is not trusted"));
                    }
                }
            }

            /*
             * Perform further checks on the timestamp that was transmitted in
             * the header. In the following implementation the timestamp is
             * valid if it was created after (now-ttl), where ttl is set on
             * server side, not by the client.
             *
             * Note: the method verifyTimestamp(Timestamp) allows custom
             * implementations with other validation algorithms for subclasses.
             */

            // Extract the timestamp action result from the action vector
            actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS);

            if (actionResult != null) {
                Timestamp timestamp = actionResult.getTimestamp();

                if (timestamp != null) {
                    if (!verifyTimestamp(timestamp, decodeTimeToLive(reqData))) {
                        throw new SoapFault(new WSSecurityException(
                                        "WSSecurityHandler: the timestamp could not be validated"));
                    }
                }
            }

            /*
             * now check the security actions: do they match, in right order?
             */
            if (!checkReceiverResults(wsResult, actions)) {
                throw new SoapFault(new WSSecurityException(
                                "WSSecurityHandler: security processing failed (actions mismatch)"));

            }
            /*
             * All ok up to this point. Now construct and setup the security
             * result structure. The service may fetch this and check it.
             */
            Vector results = null;
            if ((results = (Vector) context.getProperty(WSHandlerConstants.RECV_RESULTS)) == null) {
                results = new Vector();
                context.setProperty(WSHandlerConstants.RECV_RESULTS, results);
            }
            WSHandlerResult rResult = new WSHandlerResult(actor, wsResult);
            results.add(0, rResult);

            // Add principals to the message
            for (Iterator iter = results.iterator(); iter.hasNext();) {
                WSHandlerResult hr = (WSHandlerResult) iter.next();
                for (Iterator it = hr.getResults().iterator(); it.hasNext();) {
                    WSSecurityEngineResult er = (WSSecurityEngineResult) it.next();
                    if (er.getPrincipal() != null) {
                        context.getInMessage().addPrincipal(er.getPrincipal());
                    }
                }
            }
            Subject s = (Subject) currentSubject.get();
            if (s != null) {
                for (Iterator iterator = s.getPrincipals().iterator(); iterator.hasNext();) {
                    Principal p = (Principal) iterator.next();
                    context.getInMessage().addPrincipal(p);
                }
            }

        } finally {
            reqData.clear();
            currentSubject.set(null);
            currentHandler.set(null);
        }
    }
View Full Code Here

        // TODO Auto-generated method stub

    }

    public void onSend(Context context) throws Exception {
        RequestData reqData = new RequestData();
        reqData.setMsgContext(context);
        init(context);
        /*
         * The overall try, just to have a finally at the end to perform some
         * housekeeping.
         */
        try {
            /*
             * Get the action first.
             */
            Vector actions = new Vector();
            String action = this.sendAction;
            if (action == null) {
                throw new IllegalStateException("WSSecurityHandler: No sendAction defined");
            }
           
            int doAction = WSSecurityUtil.decodeAction(action, actions);
            if (doAction == WSConstants.NO_SECURITY) {
                return;
            }

            /*
             * For every action we need a username, so get this now. The
             * username defined in the deployment descriptor takes precedence.
             */
            reqData.setUsername((String) getOption(WSHandlerConstants.USER));
            if (reqData.getUsername() == null || reqData.getUsername().equals("")) {
                String username = (String) getProperty(reqData.getMsgContext(), WSHandlerConstants.USER);
                if (username != null) {
                    reqData.setUsername(username);
                } else {
                    reqData.setUsername(this.username);
                }
            }
           
            /*
             * Now we perform some set-up for UsernameToken and Signature
             * functions. No need to do it for encryption only. Check if
             * username is available and then get a passowrd.
             */
            if ((doAction & (WSConstants.SIGN | WSConstants.UT | WSConstants.UT_SIGN)) != 0) {
                /*
                 * We need a username - if none throw an XFireFault. For
                 * encryption there is a specific parameter to get a username.
                 */
                if (reqData.getUsername() == null || reqData.getUsername().equals("")) {
                    throw new IllegalStateException("WSSecurityHandler: Empty username for specified action");
                }
            }
            /*
             * Now get the SOAP part from the request message and convert it
             * into a Document.
             *
             * Now we can perform our security operations on this request.
             */
            Document doc = context.getInMessage().getDocument();
            if (doc == null) {
                throw new IllegalStateException("WSSecurityHandler: The soap message has not been parsed using DOM");
            }
           
            doSenderAction(doAction, doc, reqData, actions, true);
        }
        catch (WSSecurityException e) {
            throw new SoapFault(e);
        }
        finally {
            reqData.clear();
            reqData = null;
            currentHandler.set(null);
        }
    }
View Full Code Here

        if (doTimeLog) {
            t0 = System.currentTimeMillis();
        }

        RequestData reqData = new RequestData();
        /*
         * The overall try, just to have a finally at the end to perform some
         * housekeeping.
         */
        try {
            reqData.setMsgContext(msg);

            Vector actions = new Vector();
            String action = getAction(msg, version);

            int doAction = WSSecurityUtil.decodeAction(action, actions);

            String actor = (String)getOption(WSHandlerConstants.ACTOR);

            CallbackHandler cbHandler = getCallback(reqData, doAction);

            /*
             * Get and check the Signature specific parameters first because
             * they may be used for encryption too.
             */
            doReceiverAction(doAction, reqData);
           
            Vector wsResult = null;
            if (doTimeLog) {
                t1 = System.currentTimeMillis();
            }

            wsResult = getSecurityEngine().processSecurityHeader(
                doc.getSOAPPart(),
                actor,
                cbHandler,
                reqData.getSigCrypto(),
                reqData.getDecCrypto()
            );

            if (doTimeLog) {
                t2 = System.currentTimeMillis();
            }

            if (wsResult == null) { // no security header found
                if (doAction == WSConstants.NO_SECURITY) {
                    return;
                } else if (doc.getSOAPPart().getEnvelope().getBody().hasFault()) {
                    LOG.warning("Request does not contain required Security header, "
                                + "but it's a fault.");
                    return;
                } else {
                    LOG.warning("Request does not contain required Security header");
                    throw new WSSecurityException(WSSecurityException.INVALID_SECURITY);
                }
            }
            if (reqData.getWssConfig().isEnableSignatureConfirmation()) {
                checkSignatureConfirmation(reqData, wsResult);
            }

            /*
             * Now we can check the certificate used to sign the message. In the
             * following implementation the certificate is only trusted if
             * either it itself or the certificate of the issuer is installed in
             * the keystore. Note: the method verifyTrust(X509Certificate)
             * allows custom implementations with other validation algorithms
             * for subclasses.
             */

            // Extract the signature action result from the action vector
            WSSecurityEngineResult actionResult = WSSecurityUtil
                .fetchActionResult(wsResult, WSConstants.SIGN);

            if (actionResult != null) {
                X509Certificate returnCert = (X509Certificate)actionResult
                    .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);

                if (returnCert != null && !verifyTrust(returnCert, reqData)) {
                    LOG.warning("The certificate used for the signature is not trusted");
                    throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
                }
                msg.put(SIGNATURE_RESULT, actionResult);
            }

            /*
             * Perform further checks on the timestamp that was transmitted in
             * the header. In the following implementation the timestamp is
             * valid if it was created after (now-ttl), where ttl is set on
             * server side, not by the client. Note: the method
             * verifyTimestamp(Timestamp) allows custom implementations with
             * other validation algorithms for subclasses.
             */

            // Extract the timestamp action result from the action vector
            actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS);

            if (actionResult != null) {
                Timestamp timestamp = (Timestamp)actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);

                if (timestamp != null && !verifyTimestamp(timestamp, decodeTimeToLive(reqData))) {
                    LOG.warning("The timestamp could not be validated");
                    throw new WSSecurityException(WSSecurityException.MESSAGE_EXPIRED);
                }
                msg.put(TIMESTAMP_RESULT, actionResult);
            }

            /*
             * now check the security actions: do they match, in right order?
             */
            if (!checkReceiverResults(wsResult, actions)) {
                LOG.warning("Security processing failed (actions mismatch)");
                throw new WSSecurityException(WSSecurityException.INVALID_SECURITY);
            }

            doResults(msg, actor, doc, wsResult);

            if (doTimeLog) {
                t3 = System.currentTimeMillis();
                TIME_LOG.fine("Receive request: total= " + (t3 - t0)
                        + " request preparation= " + (t1 - t0)
                        + " request processing= " + (t2 - t1)
                        + " header, cert verify, timestamp= " + (t3 - t2) + "\n");
            }

            if (doDebug) {
                LOG.fine("WSS4JInInterceptor: exit handleMessage()");
            }

        } catch (WSSecurityException e) {
            LOG.log(Level.WARNING, "", e);
            SoapFault fault = createSoapFault(version, e);
            throw fault;
        } catch (XMLStreamException e) {
            throw new SoapFault(new Message("STAX_EX", LOG), e, version.getSender());
        } catch (SOAPException e) {
            throw new SoapFault(new Message("SAAJ_EX", LOG), e, version.getSender());
        } finally {
            reqData.clear();
            reqData = null;
        }
    }
View Full Code Here

TOP

Related Classes of org.apache.ws.security.handler.RequestData

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.