Search in sources :

Example 6 with ExactlyOne

use of org.apache.neethi.ExactlyOne in project cxf by apache.

the class SpnegoTokenInterceptorProvider method setupClient.

static String setupClient(STSClient client, SoapMessage message, AssertionInfoMap aim) {
    client.setTrust(NegotiationUtils.getTrust10(aim));
    client.setTrust(NegotiationUtils.getTrust13(aim));
    Policy p = new Policy();
    ExactlyOne ea = new ExactlyOne();
    p.addPolicyComponent(ea);
    All all = new All();
    all.addPolicyComponent(NegotiationUtils.getAddressingPolicy(aim, false));
    ea.addPolicyComponent(all);
    client.setPolicy(p);
    client.setSoap11(message.getVersion() == Soap11.getInstance());
    client.setSpnego(true);
    WSSConfig config = WSSConfig.getNewInstance();
    String context = config.getIdAllocator().createSecureId("_", null);
    client.setContext(context);
    String s = message.getContextualProperty(Message.ENDPOINT_ADDRESS).toString();
    client.setLocation(s);
    AlgorithmSuite suite = NegotiationUtils.getAlgorithmSuite(aim);
    if (suite != null) {
        client.setAlgorithmSuite(suite);
        int x = suite.getAlgorithmSuiteType().getMaximumSymmetricKeyLength();
        if (x < 256) {
            client.setKeySize(x);
        }
    }
    Map<String, Object> ctx = client.getRequestContext();
    mapSecurityProps(message, ctx);
    return s;
}
Also used : Policy(org.apache.neethi.Policy) All(org.apache.neethi.All) AlgorithmSuite(org.apache.wss4j.policy.model.AlgorithmSuite) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) ExactlyOne(org.apache.neethi.ExactlyOne)

Example 7 with ExactlyOne

use of org.apache.neethi.ExactlyOne in project wso2-synapse by wso2.

the class ThrottlePolicyProcessor method processPolicy.

/**
 * @param policy - policy for throttle
 * @return Throttle        - An object which holds Mata-Data about throttle
 * @throws ThrottleException - throws for errors in policy processing - ex : invalid policy
 * @deprecated process policy and returns throttle object
 */
public static Throttle processPolicy(Policy policy) throws ThrottleException {
    if (policy == null) {
        // no policy is available in the module description
        return null;
    }
    Throttle th = new Throttle();
    // configuration data
    ThrottleConfiguration tc = null;
    List al = policy.getPolicyComponents();
    if (al == null || (al != null && al.isEmpty())) {
        handleException("Empty the policy components" + " as ThrottleAssertion's children");
    }
    for (Iterator i = al.iterator(); i.hasNext(); ) {
        Object tp = i.next();
        if (tp instanceof All) {
            // boolean isOtherConfiguration = false;
            // // To track default cn for all ips
            // To create a
            CallerConfiguration cn = null;
            // configurationbean object
            boolean isIPRangeFound = false;
            boolean isExactlyOneFound = false;
            ExactlyOne cp = null;
            List cL = ((All) tp).getAssertions();
            if (cL != null) {
                for (Iterator ci = cL.iterator(); ci.hasNext(); ) {
                    Object ca = ci.next();
                    if (ca instanceof XmlPrimtiveAssertion) {
                        XmlPrimtiveAssertion id = (XmlPrimtiveAssertion) ca;
                        OMElement el = id.getValue();
                        String t = el.getAttributeValue(ThrottleConstants.THROTTLE_TYPE_ATTRIBUTE_QNAME);
                        if (t == null) {
                            handleException("Type of Throtle " + "in the policy cannot be null");
                        }
                        if (t.equals("IP")) {
                            // create a ip based throttle context and configuration
                            tc = th.getThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY);
                            if (tc == null) {
                                tc = ThrottleConfigurationFactory.createThrottleConfiguration(ThrottleConstants.IP_BASE);
                                th.addThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY, ThrottleContextFactory.createThrottleContext(ThrottleConstants.IP_BASE, tc));
                                th.addThrottleConfiguration(ThrottleConstants.IP_BASED_THROTTLE_KEY, tc);
                            }
                            // create a callercontext for ip based throttle
                            cn = CallerConfigurationFactory.createCallerConfiguration(ThrottleConstants.IP_BASE);
                        } else if (t.equals("DOMAIN")) {
                            // create a domain based throttle context and configuration
                            tc = th.getThrottleConfiguration(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY);
                            if (tc == null) {
                                tc = ThrottleConfigurationFactory.createThrottleConfiguration(ThrottleConstants.DOMAIN_BASE);
                                th.addThrottleContext(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY, ThrottleContextFactory.createThrottleContext(ThrottleConstants.DOMAIN_BASE, tc));
                                th.addThrottleConfiguration(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY, tc);
                            }
                            // create a callercontext for domain based throttl
                            cn = CallerConfigurationFactory.createCallerConfiguration(ThrottleConstants.DOMAIN_BASE);
                        } else {
                            handleException("Unsupported throttle type : " + t);
                        }
                        if (cn != null) {
                            // Name of the policy assertion
                            String n = el.getLocalName();
                            // Value of the policy assertion
                            String v = el.getText();
                            // then it is a invalid policy config
                            if (n == null || v == null) {
                                handleException("Either Value or" + " Name of the policy cannot be null");
                            } else if (n.equals(ThrottleConstants.ID_PARAMETER_NAME)) {
                                if (!v.equals("")) {
                                    isIPRangeFound = true;
                                    cn.setID(v);
                                } else {
                                    handleException("Value of ID cannot find " + "- invalid configuration");
                                }
                            } else {
                                handleException("Undefined pocilcy property for" + " throttle - Expect ID  ");
                            }
                        }
                    } else if (ca instanceof ExactlyOne) {
                        cp = (ExactlyOne) ca;
                    }
                }
            }
            if (cn != null) {
                if (cp != null) {
                    List cal = cp.getPolicyComponents();
                    boolean haveSelectOneFromExactlyOne = false;
                    for (Iterator ci = cal.iterator(); ci.hasNext() && !haveSelectOneFromExactlyOne; ) {
                        Object co = ci.next();
                        if (co instanceof All) {
                            haveSelectOneFromExactlyOne = true;
                            boolean isFoundMaxCount = false;
                            boolean isFoundUnitTime = false;
                            All childAll = (All) co;
                            List cd = childAll.getPolicyComponents();
                            for (Iterator cdl = cd.iterator(); cdl.hasNext(); ) {
                                Object d = cdl.next();
                                if (d instanceof XmlPrimtiveAssertion) {
                                    XmlPrimtiveAssertion adx = (XmlPrimtiveAssertion) d;
                                    OMElement el = adx.getValue();
                                    // Name of the policy assertion
                                    String n = el.getLocalName();
                                    // Value of the policy assertion
                                    String v = el.getText();
                                    // invalid policy config
                                    if (n == null || v == null) {
                                        handleException("Either Value or " + "Name of the policy cannot be null");
                                    }
                                    if (!v.equals("")) {
                                        if (n.equals(ThrottleConstants.MAXIMUM_COUNT_PARAMETER_NAME)) {
                                            isFoundMaxCount = true;
                                            try {
                                                cn.setMaximumRequestPerUnitTime(Integer.parseInt(v.trim()));
                                            } catch (NumberFormatException ignored) {
                                                log.error("Error occurred - " + "Invalid number for maximum " + "request number ", ignored);
                                                if (log.isDebugEnabled()) {
                                                    log.debug("Access" + " will be fully allowed");
                                                }
                                                cn.setAccessState(ThrottleConstants.ACCESS_ALLOWED);
                                            }
                                        } else if (n.equals(ThrottleConstants.UNIT_TIME_PARAMETER_NAME)) {
                                            // TODO need to verify that value is in milisecond
                                            long timeInMiliSec = 0;
                                            try {
                                                timeInMiliSec = Long.parseLong(v.trim());
                                            } catch (NumberFormatException ignored) {
                                                log.error("Error occurred " + "- Invalid number for unit time", ignored);
                                            }
                                            if (timeInMiliSec == 0) {
                                                handleException("Unit Time cannot " + "find - invalid throttle " + "policy configuration");
                                            }
                                            isFoundUnitTime = true;
                                            cn.setUnitTime(timeInMiliSec);
                                        } else if (n.equals(ThrottleConstants.PROHIBIT_TIME_PERIOD_PARAMETER_NAME)) {
                                            try {
                                                cn.setProhibitTimePeriod(Long.parseLong(v.trim()));
                                            } catch (NumberFormatException ignored) {
                                                log.error("Error occurred - Invalid" + " number for prohibit time ", ignored);
                                            }
                                        } else {
                                            handleException("Undefined Policy" + " property for Throttle Policy");
                                        }
                                    } else {
                                        if (!n.equals(ThrottleConstants.PROHIBIT_TIME_PERIOD_PARAMETER_NAME)) {
                                            handleException("The policy which have " + " defined as optional " + "should have value ");
                                        }
                                    }
                                }
                            }
                            if (isFoundUnitTime && isFoundMaxCount) {
                                isExactlyOneFound = true;
                            } else {
                                handleException("Maximum Count and UnitTime are " + "Mandatory in Throttle Policy ");
                            }
                        } else if (co instanceof XmlPrimtiveAssertion) {
                            haveSelectOneFromExactlyOne = true;
                            XmlPrimtiveAssertion alx = (XmlPrimtiveAssertion) co;
                            OMElement ele = alx.getValue();
                            // Name of the policy assertion
                            String n = ele.getLocalName();
                            // Value of the policy assertion
                            String v = ele.getText();
                            // then it is a invalid policy config
                            if (n == null || v == null) {
                                handleException("Either Value or" + " Name of the policy cannot be null");
                            } else if (n.equals(ThrottleConstants.ISALLOW_PARAMETER_NAME)) {
                                if (v.equals(Boolean.toString(true))) {
                                    isExactlyOneFound = true;
                                    cn.setAccessState(ThrottleConstants.ACCESS_ALLOWED);
                                } else if (v.equals(Boolean.toString(false))) {
                                    isExactlyOneFound = true;
                                    cn.setAccessState(ThrottleConstants.ACCESS_DENIED);
                                } else {
                                    handleException("Value for isAllow " + " component is invalied");
                                }
                            } else {
                                handleException("Invalied Throttle" + " Policy configuration");
                            }
                        }
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Couldn't find a cn for a throttle configuration" + " for an one caller  ");
                }
            }
            if (isIPRangeFound && isExactlyOneFound) {
                // If the Throttle Configuration is valid
                tc.addCallerConfiguration(cn);
            } else {
                handleException("ID and one of Valid Control policy component are " + "Mandatory in Throttle Policy");
            }
        } else if (tp instanceof XmlPrimtiveAssertion) {
            XmlPrimtiveAssertion mca = (XmlPrimtiveAssertion) tp;
            OMElement ele = mca.getValue();
            // Name of the policy assertion
            String n = ele.getLocalName();
            // Value of the policy assertion
            String v = ele.getText();
            // it is a invalid policy configuration
            if (n == null || v == null) {
                handleException("Either Value or Name of the policy cannot be null");
            } else if (n.equals(ThrottleConstants.MAXIMUM_CONCURRENT_ACCESS_PARAMETER_NAME)) {
                int intvalue = 0;
                try {
                    intvalue = Integer.parseInt(v.trim());
                } catch (NumberFormatException ignored) {
                    log.error("Error occurred - Invalid number for maximum " + "concurrent access ", ignored);
                }
                if (intvalue > 0) {
                    th.setConcurrentAccessController(new ConcurrentAccessController(intvalue));
                }
            } else {
                handleException("Invalied Throttle Policy configuration");
            }
        }
    }
    return th;
}
Also used : All(org.apache.neethi.All) OMElement(org.apache.axiom.om.OMElement) ExactlyOne(org.apache.neethi.ExactlyOne) Iterator(java.util.Iterator) List(java.util.List) XmlPrimtiveAssertion(org.apache.neethi.builders.xml.XmlPrimtiveAssertion)

Example 8 with ExactlyOne

use of org.apache.neethi.ExactlyOne in project cxf by apache.

the class AbstractSTSClient method validate.

/**
 * Make an "Validate" invocation and return the response as a STSResponse Object
 */
protected STSResponse validate(SecurityToken tok, String tokentype) throws Exception {
    createClient();
    if (tokentype == null) {
        tokentype = tokenType;
    }
    if (tokentype == null) {
        tokentype = namespace + "/RSTR/Status";
    }
    Policy validatePolicy = new Policy();
    ExactlyOne one = new ExactlyOne();
    validatePolicy.addPolicyComponent(one);
    All all = new All();
    one.addPolicyComponent(all);
    all.addAssertion(getAddressingAssertion());
    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    BindingOperationInfo boi = findOperation("/RST/Validate");
    if (boi == null) {
        boi = findOperation("/RST/Issue");
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, validatePolicy);
    }
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/Validate");
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Validate");
    writer.writeEndElement();
    writer.writeStartElement("wst", "TokenType", namespace);
    writer.writeCharacters(tokentype);
    writer.writeEndElement();
    if (tokentype.endsWith("/RSTR/Status")) {
        addClaims(writer);
        writer.writeStartElement("wst", "ValidateTarget", namespace);
        Element el = tok.getToken();
        if (el != null) {
            StaxUtils.copy(el, writer);
        }
        writer.writeEndElement();
        writer.writeEndElement();
        Object[] o = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
        return new STSResponse((DOMSource) o[0], null);
    }
    if (enableLifetime) {
        addLifetime(writer);
    }
    // Default to Bearer KeyType
    String keyTypeTemplate = keyType;
    if (keyTypeTemplate == null) {
        keyTypeTemplate = namespace + "/Bearer";
    }
    keyTypeTemplate = writeKeyType(writer, keyTypeTemplate);
    byte[] requestorEntropy = null;
    X509Certificate cert = null;
    Crypto crypto = null;
    if (keySize <= 0) {
        keySize = 256;
    }
    if (keyTypeTemplate != null && keyTypeTemplate.endsWith("SymmetricKey")) {
        requestorEntropy = writeElementsForRSTSymmetricKey(writer, false);
    } else if (keyTypeTemplate != null && keyTypeTemplate.endsWith("PublicKey")) {
        // Use the given cert, or else get it from a Crypto instance
        if (useKeyCertificate != null) {
            cert = useKeyCertificate;
        } else {
            crypto = createCrypto(false);
            cert = getCert(crypto);
        }
        writeElementsForRSTPublicKey(writer, cert);
    }
    writeRenewalSemantics(writer);
    addClaims(writer);
    writer.writeStartElement("wst", "ValidateTarget", namespace);
    Element el = tok.getToken();
    StaxUtils.copy(el, writer);
    writer.writeEndElement();
    writer.writeEndElement();
    Object[] o = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    return new STSResponse((DOMSource) o[0], requestorEntropy, cert, crypto);
}
Also used : Policy(org.apache.neethi.Policy) EffectivePolicy(org.apache.cxf.ws.policy.EffectivePolicy) All(org.apache.neethi.All) W3CDOMStreamWriter(org.apache.cxf.staxutils.W3CDOMStreamWriter) BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) DOMSource(javax.xml.transform.dom.DOMSource) ExtensibilityElement(javax.wsdl.extensions.ExtensibilityElement) Element(org.w3c.dom.Element) ExactlyOne(org.apache.neethi.ExactlyOne) X509Certificate(java.security.cert.X509Certificate) Crypto(org.apache.wss4j.common.crypto.Crypto)

Example 9 with ExactlyOne

use of org.apache.neethi.ExactlyOne in project cxf by apache.

the class AbstractSTSClient method cancel.

/**
 * Make an "Cancel" invocation and return the response as a STSResponse Object
 */
protected STSResponse cancel(SecurityToken token) throws Exception {
    createClient();
    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, token);
    BindingOperationInfo boi = findOperation("/RST/Cancel");
    boolean attachTokenDirectly = true;
    if (boi == null) {
        attachTokenDirectly = false;
        boi = findOperation("/RST/Issue");
        Policy cancelPolicy = new Policy();
        ExactlyOne one = new ExactlyOne();
        cancelPolicy.addPolicyComponent(one);
        All all = new All();
        one.addPolicyComponent(all);
        all.addAssertion(getAddressingAssertion());
        final SecureConversationToken secureConversationToken = new SecureConversationToken(SPConstants.SPVersion.SP12, SPConstants.IncludeTokenType.INCLUDE_TOKEN_ALWAYS_TO_RECIPIENT, null, null, null, null);
        secureConversationToken.setOptional(true);
        class InternalProtectionToken extends ProtectionToken {

            InternalProtectionToken(SPVersion version, Policy nestedPolicy) {
                super(version, nestedPolicy);
                super.setToken(secureConversationToken);
            }
        }
        DefaultSymmetricBinding binding = new DefaultSymmetricBinding(SPConstants.SPVersion.SP12, new Policy());
        all.addAssertion(binding);
        all.addAssertion(getAddressingAssertion());
        binding.setProtectionToken(new InternalProtectionToken(SPConstants.SPVersion.SP12, new Policy()));
        binding.setIncludeTimestamp(true);
        binding.setOnlySignEntireHeadersAndBody(true);
        binding.setProtectTokens(false);
        String addrNamespace = addressingNamespace;
        if (addrNamespace == null) {
            addrNamespace = "http://www.w3.org/2005/08/addressing";
        }
        List<Header> headers = new ArrayList<>();
        headers.add(new Header("To", addrNamespace));
        headers.add(new Header("From", addrNamespace));
        headers.add(new Header("FaultTo", addrNamespace));
        headers.add(new Header("ReplyTo", addrNamespace));
        headers.add(new Header("Action", addrNamespace));
        headers.add(new Header("MessageID", addrNamespace));
        headers.add(new Header("RelatesTo", addrNamespace));
        SignedParts parts = new SignedParts(SPConstants.SPVersion.SP12, true, null, headers, false);
        parts.setOptional(true);
        all.addPolicyComponent(parts);
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, cancelPolicy);
    }
    if (isSecureConv) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/SCT/Cancel");
    } else {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/Cancel");
    }
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Cancel");
    writer.writeEndElement();
    writer.writeStartElement("wst", "CancelTarget", namespace);
    Element el = null;
    if (attachTokenDirectly) {
        el = token.getToken();
    } else {
        el = token.getUnattachedReference();
        if (el == null) {
            el = token.getAttachedReference();
        }
    }
    StaxUtils.copy(el, writer);
    writer.writeEndElement();
    writer.writeEndElement();
    Object[] obj = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    return new STSResponse((DOMSource) obj[0], null);
}
Also used : Policy(org.apache.neethi.Policy) EffectivePolicy(org.apache.cxf.ws.policy.EffectivePolicy) All(org.apache.neethi.All) SPVersion(org.apache.wss4j.policy.SPConstants.SPVersion) W3CDOMStreamWriter(org.apache.cxf.staxutils.W3CDOMStreamWriter) BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) DOMSource(javax.xml.transform.dom.DOMSource) ExtensibilityElement(javax.wsdl.extensions.ExtensibilityElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) ModCountCopyOnWriteArrayList(org.apache.cxf.common.util.ModCountCopyOnWriteArrayList) ExactlyOne(org.apache.neethi.ExactlyOne) SecureConversationToken(org.apache.wss4j.policy.model.SecureConversationToken) Header(org.apache.wss4j.policy.model.Header) SignedParts(org.apache.wss4j.policy.model.SignedParts) ProtectionToken(org.apache.wss4j.policy.model.ProtectionToken)

Example 10 with ExactlyOne

use of org.apache.neethi.ExactlyOne in project cxf by apache.

the class EndpointPolicyImplTest method testUpdatePolicyWithEmptyExactlyOneAndAll.

@Test
public void testUpdatePolicyWithEmptyExactlyOneAndAll() {
    Policy emptyPolicy = new Policy();
    PolicyOperator exactlyOne = new ExactlyOne();
    exactlyOne.addPolicyComponent(new All());
    exactlyOne.addPolicyComponent(new All());
    emptyPolicy.addPolicyComponent(exactlyOne);
    emptyPolicy.addPolicyComponent(new All());
    emptyPolicy.addPolicyComponent(new All());
    doTestUpdateWithEmptyPolicy(emptyPolicy);
}
Also used : Policy(org.apache.neethi.Policy) All(org.apache.neethi.All) PolicyOperator(org.apache.neethi.PolicyOperator) ExactlyOne(org.apache.neethi.ExactlyOne) Test(org.junit.Test)

Aggregations

ExactlyOne (org.apache.neethi.ExactlyOne)19 All (org.apache.neethi.All)18 Policy (org.apache.neethi.Policy)18 Test (org.junit.Test)9 Assertion (org.apache.neethi.Assertion)7 QName (javax.xml.namespace.QName)6 PrimitiveAssertion (org.apache.cxf.ws.policy.builder.primitive.PrimitiveAssertion)6 Message (org.apache.cxf.message.Message)3 MessageImpl (org.apache.cxf.message.MessageImpl)3 AlternativeSelector (org.apache.cxf.ws.policy.AlternativeSelector)3 Assertor (org.apache.cxf.ws.policy.Assertor)3 PolicyAssertion (org.apache.cxf.ws.policy.PolicyAssertion)3 PolicyEngine (org.apache.cxf.ws.policy.PolicyEngine)3 TestAssertion (org.apache.cxf.ws.policy.TestAssertion)3 AlgorithmSuite (org.apache.wss4j.policy.model.AlgorithmSuite)3 ProtectionToken (org.apache.wss4j.policy.model.ProtectionToken)3 SignedParts (org.apache.wss4j.policy.model.SignedParts)3 ArrayList (java.util.ArrayList)2 ExtensibilityElement (javax.wsdl.extensions.ExtensibilityElement)2 DOMSource (javax.xml.transform.dom.DOMSource)2