org.wso2.balana.XACMLConstants Java Examples

The following examples show how to use org.wso2.balana.XACMLConstants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PolicyAttributeBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * This extract policy meta data from condition element in the policy
 *
 * @param omElement     condition element as an OMElement
 * @param attributeDTOs list of AttributeDTO object which holds the policy meta data
 *                      in String format
 * @return list of AttributeDTO object which holds the policy meta data in String format
 */
public List<AttributeDTO> createMetaDataFromConditionElement(OMElement omElement,
                                                             List<AttributeDTO> attributeDTOs) {

    Iterator iterator = omElement.getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT);
    if (iterator.hasNext()) {
        if (version == XACMLConstants.XACML_VERSION_3_0) {
            createMetaDataFromXACML3ApplyElement(omElement, attributeDTOs);
        } else {
            createMetaDataFromApplyElement(omElement, attributeDTOs);
        }
    } else {
        AttributeDTO attributeDTO = new AttributeDTO();
        attributeDTO.setCategory(PDPConstants.UNKNOWN);
        attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE4);
    }

    // TODO currently only search meta data on Apply Element, support for other elements 
    return attributeDTOs;
}
 
Example #2
Source File: RequestCtxFactory.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 *  Returns instance of <code>AbstractRequestCtx</code> based one the XACML version.
 *
 * @param request  the String to parse for the <code>AbstractRequestCtx</code>
 * @return <code>AbstractRequestCtx</code> object
 * @throws ParsingException  if the request is invalid
 */
public AbstractRequestCtx getRequestCtx(String request) throws ParsingException {

    Node root = getXacmlRequest(request);
    String requestCtxNs = root.getNamespaceURI();

    if(requestCtxNs != null){
        if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(requestCtxNs.trim())){
            return RequestCtx.getInstance(root);
        } else if(XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(requestCtxNs.trim()) ||
                XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(requestCtxNs.trim())) {
            return org.wso2.balana.ctx.xacml2.RequestCtx.getInstance(root);
        } else {
            throw new ParsingException("Invalid namespace in XACML request");
        }
    } else {
        log.warn("No Namespace defined in XACML request and Assume as XACML 3.0");
        return RequestCtx.getInstance(root);
    }
}
 
Example #3
Source File: RequestCtxFactory.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 *  Returns instance of <code>AbstractRequestCtx</code> based one the XACML version.
 *
 * @param root  the node to parse for the <code>AbstractRequestCtx</code>
 * @return <code>AbstractRequestCtx</code> object
 * @throws org.wso2.balana.ParsingException  if the DOM node is invalid
 */
public AbstractRequestCtx getRequestCtx(Node root) throws ParsingException {

    String requestCtxNs = root.getNamespaceURI();

    if(requestCtxNs != null){
        if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(requestCtxNs.trim())){
            return RequestCtx.getInstance(root);
        } else if(XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(requestCtxNs.trim()) ||
                XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(requestCtxNs.trim())) {
            return org.wso2.balana.ctx.xacml2.RequestCtx.getInstance(root);
        } else {
            throw new ParsingException("Invalid namespace in XACML request");
        }
    } else {
        log.warn("No Namespace defined in XACML request and Assume as XACML 3.0");
        return RequestCtx.getInstance(root);
    }
}
 
Example #4
Source File: RequestCtxFactory.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 *  Returns instance of <code>AbstractRequestCtx</code> based one the XACML version.
 *
 * Creates a new <code>RequestCtx</code> by parsing XML from an input stream. Note that this a
 * convenience method, and it will not do schema validation by default. You should be parsing
 * the data yourself, and then providing the root node to the other <code>getInstance</code>
 * method. If you use this convenience method, you probably want to turn on validation by
 * setting the context schema file (see the programmer guide for more information on this).
 *
 * @param input input a stream providing the XML data
 * @return <code>AbstractRequestCtx</code> object
 * @throws ParsingException  if the DOM node is invalid
 */
public AbstractRequestCtx getRequestCtx(InputStream input) throws ParsingException {

    Node root  = InputParser.parseInput(input, "Request");
    String requestCtxNs = root.getNamespaceURI();

    if(requestCtxNs != null){
        if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(requestCtxNs.trim())){
            return RequestCtx.getInstance(root);
        } else if(XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(requestCtxNs.trim()) ||
                XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(requestCtxNs.trim())) {
            return org.wso2.balana.ctx.xacml2.RequestCtx.getInstance(root);
        } else {
            throw new ParsingException("Invalid namespace in XACML request");
        }
    } else {
        log.warn("No Namespace defined in XACML request and Assume as XACML 3.0");
        return RequestCtx.getInstance(root);
    }
}
 
Example #5
Source File: CurrentEnvModule.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Used to get the current time, date, or dateTime. If one of those values isn't being asked
 * for, or if the types are wrong, then an empty bag is returned.
 * 
 * @param attributeType the datatype of the attributes to find, which must be time, date, or
 *            dateTime for this module to resolve a value
 * @param attributeId the identifier of the attributes to find, which must be one of the three
 *            ENVIRONMENT_* fields for this module to resolve a value
 * @param issuer the issuer of the attributes, or null if unspecified
 * @param category the category of the attribute 
 * @param context the representation of the request data
 * 
 * @return the result of attribute retrieval, which will be a bag with a single attribute, an
 *         empty bag, or an error
 */
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer,
        URI category, EvaluationCtx context) {
    // we only know about environment attributes
    if (!XACMLConstants.ENT_CATEGORY.equals(category.toString())){
        return new EvaluationResult(BagAttribute.createEmptyBag(attributeType));
    }
    // figure out which attribute we're looking for
    String attrName = attributeId.toString();

    if (attrName.equals(ENVIRONMENT_CURRENT_TIME)) {
        return handleTime(attributeType, issuer, context);
    } else if (attrName.equals(ENVIRONMENT_CURRENT_DATE)) {
        return handleDate(attributeType, issuer, context);
    } else if (attrName.equals(ENVIRONMENT_CURRENT_DATETIME)) {
        return handleDateTime(attributeType, issuer, context);
    }

    // if we got here, then it's an attribute that we don't know
    return new EvaluationResult(BagAttribute.createEmptyBag(attributeType));
}
 
Example #6
Source File: EqualFunction.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate the function, using the specified parameters.
 * 
 * @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
 *            arguments passed to the function
 * @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
 *            be evaluated
 * @return an <code>EvaluationResult</code> representing the function's result
 */
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {

    // Evaluate the arguments
    AttributeValue[] argValues = new AttributeValue[inputs.size()];
    EvaluationResult result = evalArgs(inputs, context, argValues);
    if (result != null)
        return result;

    if (argValues[1] instanceof StringAttribute
            && XACMLConstants.ANY.equals(((StringAttribute) argValues[1]).getValue())) {
        return EvaluationResult.getInstance(true);
    }

    // Now that we have real values, perform the equals operation
    if(getFunctionId() == ID_EQUAL_CASE_IGNORE){
        return EvaluationResult.getInstance(argValues[0].encode().toLowerCase().
                equals(argValues[1].encode().toLowerCase()));            
    }  else {
        return EvaluationResult.getInstance(argValues[0].equals(argValues[1]));
    }
}
 
Example #7
Source File: EntitlementUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static String getPolicyVersion(String policy) {

        try {
            //build XML document
            DocumentBuilder documentBuilder = getSecuredDocumentBuilder(false);
            InputStream stream = new ByteArrayInputStream(policy.getBytes());
            Document doc = documentBuilder.parse(stream);


            //get policy version
            Element policyElement = doc.getDocumentElement();
            return policyElement.getNamespaceURI();
        } catch (Exception e) {
            log.debug(e);
            // ignore exception as default value is used
            log.warn("Policy version can not be identified. Default XACML 3.0 version is used");
            return XACMLConstants.XACML_3_0_IDENTIFIER;
        }
    }
 
Example #8
Source File: EntitlementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static String getPolicyVersion(String policy) {

        try {
            //build XML document
            DocumentBuilder documentBuilder = getSecuredDocumentBuilder(false);
            InputStream stream = new ByteArrayInputStream(policy.getBytes());
            Document doc = documentBuilder.parse(stream);


            //get policy version
            Element policyElement = doc.getDocumentElement();
            return policyElement.getNamespaceURI();
        } catch (Exception e) {
            log.debug(e);
            // ignore exception as default value is used
            log.warn("Policy version can not be identified. Default XACML 3.0 version is used");
            return XACMLConstants.XACML_3_0_IDENTIFIER;
        }
    }
 
Example #9
Source File: PolicyAttributeBuilder.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * This extract policy meta data from condition element in the policy
 *
 * @param omElement     condition element as an OMElement
 * @param attributeDTOs list of AttributeDTO object which holds the policy meta data
 *                      in String format
 * @return list of AttributeDTO object which holds the policy meta data in String format
 */
public List<AttributeDTO> createMetaDataFromConditionElement(OMElement omElement,
                                                             List<AttributeDTO> attributeDTOs) {

    Iterator iterator = omElement.getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT);
    if (iterator.hasNext()) {
        if (version == XACMLConstants.XACML_VERSION_3_0) {
            createMetaDataFromXACML3ApplyElement(omElement, attributeDTOs);
        } else {
            createMetaDataFromApplyElement(omElement, attributeDTOs);
        }
    } else {
        AttributeDTO attributeDTO = new AttributeDTO();
        attributeDTO.setCategory(PDPConstants.UNKNOWN);
        attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE4);
    }

    // TODO currently only search meta data on Apply Element, support for other elements 
    return attributeDTOs;
}
 
Example #10
Source File: PolicyAttributeBuilder.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @param policy policy as a String
 */
public PolicyAttributeBuilder(String policy) {
    this.policy = policy;
    String version = EntitlementUtil.getPolicyVersion(policy);
    if (XACMLConstants.XACML_1_0_IDENTIFIER.equals(version)) {
        this.version = XACMLConstants.XACML_VERSION_1_0;
    } else if (XACMLConstants.XACML_2_0_IDENTIFIER.equals(version)) {
        this.version = XACMLConstants.XACML_VERSION_2_0;
    } else {
        this.version = XACMLConstants.XACML_VERSION_3_0;
    }
}
 
Example #11
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
private static Set<Attribute> parseAttributes(Node root) throws ParsingException {
    Set<Attribute> set = new HashSet<Attribute>();

    // the Environment section is just a list of Attributes
    NodeList nodes = root.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (DOMHelper.getLocalName(node).equals("Attribute"))
            set.add(Attribute.getInstance(node, XACMLConstants.XACML_VERSION_2_0));
    }

    return set;
}
 
Example #12
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes this  <code>AbstractRequestCtx</code>  into its XML representation and writes this encoding to the given
 * <code>OutputStream</code> with indentation.
 *
 * @param output a stream into which the XML-encoded data is written
 * @param indenter an object that creates indentation strings
 */
public void encode(OutputStream output, Indenter indenter) {

    String indent = indenter.makeString();
    PrintStream out = new PrintStream(output);

    out.println(indent + "<Request xmlns=\"" + XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER +
            "\" ReturnPolicyIdList=\"" + returnPolicyIdList + "\" CombinedDecision=\"" + 
            combinedDecision +   "\" >");

    indenter.in();

    for(Attributes attributes : attributesSet){
        out.println(attributes.encode());
    }

    if(defaults != null){
        defaults.encode(output, indenter);
    }

    if(multiRequests != null){
       // multiRequests 
    }

    indenter.out();

    out.println(indent + "</Request>");
}
 
Example #13
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 * @param documentRoot       the root node of the DOM tree for this request
 * @param attributesSet      a <code>Set</code> of <code>Attributes</code>s
 * @param returnPolicyIdList a <code>boolean</code> value whether to send back policy list of not
 * @param combinedDecision   a <code>boolean</code> value whether to combine decisions or not
 * @param multiRequests      a <code>MultiRequests</code> for the  MultiRequests element in request
 * @param defaults           a <code>RequestDefaults</code>  for the  RequestDefaults element in request
 * @throws IllegalArgumentException if the inputs are not well formed
 */
public RequestCtx(Node documentRoot, Set<Attributes> attributesSet, boolean returnPolicyIdList,
                  boolean combinedDecision, MultiRequests multiRequests,
                  RequestDefaults defaults) throws IllegalArgumentException {


    this.xacmlVersion = XACMLConstants.XACML_VERSION_3_0;
    this.documentRoot = documentRoot;
    this.attributesSet = attributesSet;
    this.returnPolicyIdList = returnPolicyIdList;
    this.combinedDecision = combinedDecision;
    this.multiRequests = multiRequests;
    this.defaults = defaults;
}
 
Example #14
Source File: EntitlementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static Attributes getAttributes(AttributeDTO attributeDataDTO) {

        try {
            AttributeValue value = Balana.getInstance().getAttributeFactory().
                    createValue(new URI(attributeDataDTO.getAttributeDataType()),
                            attributeDataDTO.getAttributeValue());
            Attribute attribute = new Attribute(new URI(attributeDataDTO.getAttributeId()),
                    null, null, value, XACMLConstants.XACML_VERSION_3_0);
            Set<Attribute> set = new HashSet<Attribute>();
            set.add(attribute);
            String category = attributeDataDTO.getCategory();
            // We are only creating XACML 3.0 requests Therefore covert order XACML categories to new uris
            if (PDPConstants.SUBJECT_ELEMENT.equals(category)) {
                category = PDPConstants.SUBJECT_CATEGORY_URI;
            } else if (PDPConstants.RESOURCE_ELEMENT.equals(category)) {
                category = PDPConstants.RESOURCE_CATEGORY_URI;
            } else if (PDPConstants.ACTION_ELEMENT.equals(category)) {
                category = PDPConstants.ACTION_CATEGORY_URI;
            } else if (PDPConstants.ENVIRONMENT_ELEMENT.equals(category)) {
                category = PDPConstants.ENVIRONMENT_CATEGORY_URI;
            }
            return new Attributes(new URI(category), set);
        } catch (Exception e) {
            log.debug(e);
            //ignore and return null;
        }

        return null;
    }
 
Example #15
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 * @param attributesSet
 * @param documentRoot the root node of the DOM tree for this request
 * @param resourceContent a text-encoded version of the content, suitable for including in the
 *            RequestType, including the root <code>RequestContent</code> node
 *
 * @throws IllegalArgumentException if the inputs are not well formed
 */
public RequestCtx(Set<Attributes> attributesSet, Node documentRoot, Set<Subject> subjects,
                  Set<Attribute> resource, Set<Attribute> action,  Set<Attribute> environment,
                  String resourceContent) throws IllegalArgumentException {

    this.attributesSet = attributesSet;
    this.documentRoot = documentRoot;
    this.subjects = subjects;
    this.resource = resource;
    this.action = action;
    this.environment = environment;
    this.resourceContent = resourceContent;
    this.xacmlVersion = XACMLConstants.XACML_VERSION_2_0;
}
 
Example #16
Source File: ResultFactory.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Returns instance of <code>AbstractResult</code> based one the XACML version.
 * Constructs a <code>AbstractResult</code> object with decision and evaluation ctx
 *
 * @param decision decision the decision effect to include in this result.
 * @param obligationResults a list of <code>ObligationResult</code> objects
 * @param advices a list of <code>Advice</code> objects
 * @param evaluationCtx context of a single policy evaluation
 * @return <code>AbstractResult</code> object
 */
public AbstractResult getResult(int decision, List<ObligationResult> obligationResults,
                                        List<Advice> advices,  EvaluationCtx evaluationCtx) {

    if(evaluationCtx.getXacmlVersion() == XACMLConstants.XACML_VERSION_3_0){
        return new Result(decision, null, obligationResults,
                                                                        advices, evaluationCtx);
    } else {
        return new org.wso2.balana.ctx.xacml2.Result(decision, null, obligationResults);
    }
}
 
Example #17
Source File: AttributeDesignatorFactory.java    From balana with Apache License 2.0 5 votes vote down vote up
public AbstractDesignator getAbstractDesignator(Node root, PolicyMetaData metaData)
                                                                    throws ParsingException {

    if(metaData.getXACMLVersion() == XACMLConstants.XACML_VERSION_3_0){
        return AttributeDesignator.getInstance(root);
    } else {
        return org.wso2.balana.attr.AttributeDesignator.getInstance(root);
    }
}
 
Example #18
Source File: EvaluationCtxFactory.java    From balana with Apache License 2.0 5 votes vote down vote up
public EvaluationCtx getEvaluationCtx(AbstractRequestCtx requestCtx, PDPConfig pdpConfig)
                                                                    throws ParsingException {

    if(XACMLConstants.XACML_VERSION_3_0 == requestCtx.getXacmlVersion()){
        return new XACML3EvaluationCtx((RequestCtx)requestCtx, pdpConfig);
    } else {
        return new XACML2EvaluationCtx((org.wso2.balana.ctx.xacml2.RequestCtx) requestCtx, pdpConfig);
    }
}
 
Example #19
Source File: AttributeSelectorFactory.java    From balana with Apache License 2.0 5 votes vote down vote up
public AbstractAttributeSelector getAbstractSelector(Node root, PolicyMetaData metaData)
                                                                    throws ParsingException {

    if(metaData.getXACMLVersion() == XACMLConstants.XACML_VERSION_3_0){
        return org.wso2.balana.attr.xacml3.AttributeSelector.getInstance(root, metaData);
    } else {
        return org.wso2.balana.attr.AttributeSelector.getInstance(root, metaData);
    }
}
 
Example #20
Source File: XPathFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Gets Xpath results
 *
 * @param contextNode
 * @param xpathValue
 * @return
 * @throws XPathExpressionException
 */
private NodeList getXPathResults(Node contextNode, String xpathValue)
                                                            throws XPathExpressionException {

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    //see if the request root is in a namespace
    String namespace = contextNode.getNamespaceURI();
    // name spaces are used, so we need to lookup the correct
    // prefix to use in the search string
    NamedNodeMap namedNodeMap = contextNode.getAttributes();

    Map<String, String> nsMap = new HashMap<String, String>();

    for (int i = 0; i < namedNodeMap.getLength(); i++) {
        Node n = namedNodeMap.item(i);
        // we found the matching namespace, so get the prefix
        // and then break out
        String prefix = DOMHelper.getLocalName(n);
        String nodeValue= n.getNodeValue();
        nsMap.put(prefix, nodeValue);
    }

    // if there is not any namespace is defined for content element, default XACML request
    //  name space would be there.
    if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace) ||
            XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace) ||
            XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)){
        nsMap.put("xacml", namespace);
    }

    NamespaceContext namespaceContext = new DefaultNamespaceContext(nsMap);
    xpath.setNamespaceContext(namespaceContext);

    XPathExpression expression = xpath.compile(xpathValue);
    return (NodeList) expression.evaluate(contextNode, XPathConstants.NODESET);
}
 
Example #21
Source File: PolicyAttributeBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This extract policy meta data from each rule element in the policy
 *
 * @param omElement     rule element as an OMElement
 * @param attributeDTOs list of AttributeDTO object which holds the policy meta data
 *                      in String format
 * @return list of AttributeDTO object which holds the policy meta data in String format
 */
public List<AttributeDTO> createMetaDataFromRuleElement(OMElement omElement,
                                                        List<AttributeDTO> attributeDTOs) {

    if (omElement != null) {

        Iterator iterator1 = omElement.getChildrenWithLocalName(PDPConstants.
                TARGET_ELEMENT);
        while (iterator1.hasNext()) {
            OMElement targetElement = (OMElement) iterator1.next();
            if (version == XACMLConstants.XACML_VERSION_3_0) {
                createMetaDataFromXACML3TargetElement(targetElement, attributeDTOs);
            } else {
                createMetaDataFromTargetElement(targetElement, attributeDTOs);
            }
        }

        Iterator iterator2 = omElement.getChildrenWithLocalName(PDPConstants.
                CONDITION_ELEMENT);
        while (iterator2.hasNext()) {
            OMElement conditionElement = (OMElement) iterator2.next();
            createMetaDataFromConditionElement(conditionElement, attributeDTOs);
        }
    }

    return attributeDTOs;
}
 
Example #22
Source File: PolicyAttributeBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This searches through  attribute values in the attribute elements to extract the policy meta data
 *
 * @param omElement         apply element as an OMElement
 * @param values            set of String objects
 * @param searchDesignators states where,  to find designators which are involved in creating
 *                          attribute values
 * @return AttributeValueDTO object which holds the policy meta data in String format
 */
public List<String> searchAttributeValues(OMElement omElement, List<String> values,
                                          boolean searchDesignators) {

    if (values != null) {
        Iterator iterator = omElement.
                getChildrenWithLocalName(PDPConstants.ATTRIBUTE_VALUE);
        while (iterator.hasNext()) {
            OMElement attributeElement = (OMElement) iterator.next();
            if (attributeElement != null) {
                String dataType = attributeElement.
                        getAttributeValue(new QName(PDPConstants.DATA_TYPE));   // TODO
                values.add(attributeElement.getText());
            }
        }
    }

    Iterator iterator1 = omElement.getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT);
    while (iterator1.hasNext()) {
        OMElement applyElement = (OMElement) iterator1.next();
        searchAttributeValues(applyElement, values, searchDesignators);

        AttributeDTO attributeDTO = new AttributeDTO();
        if (searchDesignators) {
            if (version == XACMLConstants.XACML_VERSION_3_0) {
                searchXACML3Designator(applyElement, attributeDTO);
            } else {
                searchDesignatorOrSelector(applyElement, attributeDTO);
            }
        }
        if (attributeDTO.getCategory() != null || attributeDTO.getAttributeId() != null ||
                attributeDTO.getAttributeDataType() != null) {
            values = null;
        }
    }

    return values;
}
 
Example #23
Source File: PolicyAttributeBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param policy policy as a String
 */
public PolicyAttributeBuilder(String policy) {
    this.policy = policy;
    String version = EntitlementUtil.getPolicyVersion(policy);
    if (XACMLConstants.XACML_1_0_IDENTIFIER.equals(version)) {
        this.version = XACMLConstants.XACML_VERSION_1_0;
    } else if (XACMLConstants.XACML_2_0_IDENTIFIER.equals(version)) {
        this.version = XACMLConstants.XACML_VERSION_2_0;
    } else {
        this.version = XACMLConstants.XACML_VERSION_3_0;
    }
}
 
Example #24
Source File: ResultFactory.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Returns instance of <code>AbstractResult</code> based one the XACML version. 
 * Constructs a <code>AbstractResult</code> object with decision and evaluation ctx
 * 
 * @param decision decision the decision effect to include in this result.
 * @param evaluationCtx context of a single policy evaluation
 * @return <code>AbstractResult</code> object
 */
public AbstractResult getResult(int decision, EvaluationCtx evaluationCtx) {

    if(evaluationCtx.getXacmlVersion() == XACMLConstants.XACML_VERSION_3_0){
        return new Result(decision, null, null, null,evaluationCtx);
    } else {
        return new org.wso2.balana.ctx.xacml2.Result(decision, null);
    }
}
 
Example #25
Source File: EntitlementUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static Attributes getAttributes(AttributeDTO attributeDataDTO) {

        try {
            AttributeValue value = Balana.getInstance().getAttributeFactory().
                    createValue(new URI(attributeDataDTO.getAttributeDataType()),
                            attributeDataDTO.getAttributeValue());
            Attribute attribute = new Attribute(new URI(attributeDataDTO.getAttributeId()),
                    null, null, value, XACMLConstants.XACML_VERSION_3_0);
            Set<Attribute> set = new HashSet<Attribute>();
            set.add(attribute);
            String category = attributeDataDTO.getCategory();
            // We are only creating XACML 3.0 requests Therefore covert order XACML categories to new uris
            if (PDPConstants.SUBJECT_ELEMENT.equals(category)) {
                category = PDPConstants.SUBJECT_CATEGORY_URI;
            } else if (PDPConstants.RESOURCE_ELEMENT.equals(category)) {
                category = PDPConstants.RESOURCE_CATEGORY_URI;
            } else if (PDPConstants.ACTION_ELEMENT.equals(category)) {
                category = PDPConstants.ACTION_CATEGORY_URI;
            } else if (PDPConstants.ENVIRONMENT_ELEMENT.equals(category)) {
                category = PDPConstants.ENVIRONMENT_CATEGORY_URI;
            }
            return new Attributes(new URI(category), set);
        } catch (Exception e) {
            log.debug(e);
            //ignore and return null;
        }

        return null;
    }
 
Example #26
Source File: PolicyAttributeBuilder.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * This searches through  attribute values in the attribute elements to extract the policy meta data
 *
 * @param omElement         apply element as an OMElement
 * @param values            set of String objects
 * @param searchDesignators states where,  to find designators which are involved in creating
 *                          attribute values
 * @return AttributeValueDTO object which holds the policy meta data in String format
 */
public List<String> searchAttributeValues(OMElement omElement, List<String> values,
                                          boolean searchDesignators) {

    if (values != null) {
        Iterator iterator = omElement.
                getChildrenWithLocalName(PDPConstants.ATTRIBUTE_VALUE);
        while (iterator.hasNext()) {
            OMElement attributeElement = (OMElement) iterator.next();
            if (attributeElement != null) {
                String dataType = attributeElement.
                        getAttributeValue(new QName(PDPConstants.DATA_TYPE));   // TODO
                values.add(attributeElement.getText());
            }
        }
    }

    Iterator iterator1 = omElement.getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT);
    while (iterator1.hasNext()) {
        OMElement applyElement = (OMElement) iterator1.next();
        searchAttributeValues(applyElement, values, searchDesignators);

        AttributeDTO attributeDTO = new AttributeDTO();
        if (searchDesignators) {
            if (version == XACMLConstants.XACML_VERSION_3_0) {
                searchXACML3Designator(applyElement, attributeDTO);
            } else {
                searchDesignatorOrSelector(applyElement, attributeDTO);
            }
        }
        if (attributeDTO.getCategory() != null || attributeDTO.getAttributeId() != null ||
                attributeDTO.getAttributeDataType() != null) {
            values = null;
        }
    }

    return values;
}
 
Example #27
Source File: PolicyAttributeBuilder.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * This extract policy meta data from each rule element in the policy
 *
 * @param omElement     rule element as an OMElement
 * @param attributeDTOs list of AttributeDTO object which holds the policy meta data
 *                      in String format
 * @return list of AttributeDTO object which holds the policy meta data in String format
 */
public List<AttributeDTO> createMetaDataFromRuleElement(OMElement omElement,
                                                        List<AttributeDTO> attributeDTOs) {

    if (omElement != null) {

        Iterator iterator1 = omElement.getChildrenWithLocalName(PDPConstants.
                TARGET_ELEMENT);
        while (iterator1.hasNext()) {
            OMElement targetElement = (OMElement) iterator1.next();
            if (version == XACMLConstants.XACML_VERSION_3_0) {
                createMetaDataFromXACML3TargetElement(targetElement, attributeDTOs);
            } else {
                createMetaDataFromTargetElement(targetElement, attributeDTOs);
            }
        }

        Iterator iterator2 = omElement.getChildrenWithLocalName(PDPConstants.
                CONDITION_ELEMENT);
        while (iterator2.hasNext()) {
            OMElement conditionElement = (OMElement) iterator2.next();
            createMetaDataFromConditionElement(conditionElement, attributeDTOs);
        }
    }

    return attributeDTOs;
}
 
Example #28
Source File: RequestCtx.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Encodes this  <code>AbstractRequestCtx</code>  into its XML representation and writes this encoding to the given
 * <code>OutputStream</code> with indentation.
 * 
 * @param output a stream into which the XML-encoded data is written
 * @param indenter an object that creates indentation strings
 */
public void encode(OutputStream output, Indenter indenter) {

    // Make a PrintStream for a nicer printing interface
    PrintStream out = new PrintStream(output);

    // Prepare the indentation string
    String topIndent = indenter.makeString();
    out.println(topIndent + "<Request xmlns=\"" + XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER + "\" >");

    // go in one more for next-level elements...
    indenter.in();
    String indent = indenter.makeString();

    // ...and go in again for everything else
    indenter.in();

    // first off, go through all subjects
    Iterator it = subjects.iterator();
    while (it.hasNext()) {
        Subject subject = (Subject) (it.next());

        out.print(indent + "<Subject SubjectCategory=\"" + subject.getCategory().toString()
                + "\"");

        Set subjectAttrs = subject.getAttributes();

        if (subjectAttrs.size() == 0) {
            // there's nothing in this Subject, so just close the tag
            out.println("/>");
        } else {
            // there's content, so fill it in
            out.println(">");

            encodeAttributes(subjectAttrs, out, indenter);

            out.println(indent + "</Subject>");
        }
    }

    // next do the resource
    if ((resource.size() != 0) || (resourceContent != null)) {
        out.println(indent + "<Resource>");
        if (resourceContent != null)
            out.println(indenter.makeString() + "<ResourceContent>" + resourceContent
                    + "</ResourceContent>");
        encodeAttributes(resource, out, indenter);
        out.println(indent + "</Resource>");
    } else {
        out.println(indent + "<Resource/>");
    }

    // now the action
    if (action.size() != 0) {
        out.println(indent + "<Action>");
        encodeAttributes(action, out, indenter);
        out.println(indent + "</Action>");
    } else {
        out.println(indent + "<Action/>");
    }

    // finally the environment, if there are any attrs
    if (environment.size() != 0) {
        out.println(indent + "<Environment>");
        encodeAttributes(environment, out, indenter);
        out.println(indent + "</Environment>");
    }

    // we're back to the top
    indenter.out();
    indenter.out();

    out.println(topIndent + "</Request>");
}
 
Example #29
Source File: JSONRequestParser.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Static method that will convert a XACML JSON Request to a <code>{@link RequestCtx}</code> instance
 *
 * @param jsonRequest <code>String</code> with JSON request
 * @return <code>{@link RequestCtx}</code> instance that can be used to evaluate on Balana
 * @throws JsonParseException         <code>{@link JsonParseException}</code>
 * @throws RequestParseException      <code>{@link RequestParseException}</code>
 * @throws UnknownIdentifierException <code>{@link UnknownIdentifierException}</code>
 */
public static RequestCtx parse(String jsonRequest) throws JsonParseException, RequestParseException,
        UnknownIdentifierException {
    JsonObject requestObject = null;
    Set<Attributes> categories = new HashSet<>();
    boolean returnPolicyIdList = false;
    boolean combinedDecision = false;
    MultiRequests multiRequests = null;
    RequestDefaults requestDefaults = null;

    try {
        requestObject = gson.fromJson(jsonRequest, JsonObject.class);
        requestObject = requestObject.get("Request").getAsJsonObject();
    } catch (Exception e) {
        throw new JsonParseException("Error in JSON Request String");
    }

    Set<Map.Entry<String, JsonElement>> jsonAttributes = requestObject.entrySet();

    for (Map.Entry<String, JsonElement> jsonAttribute : jsonAttributes) {
        if (jsonAttribute.getValue().isJsonPrimitive()) {
            switch (jsonAttribute.getKey()) {
                case XACMLConstants.RETURN_POLICY_LIST:
                    if (jsonAttribute.getValue().getAsBoolean() == true) {
                        returnPolicyIdList = true;
                    }
                    break;

                case XACMLConstants.COMBINE_DECISION:
                    if (jsonAttribute.getValue().getAsBoolean() == true) {
                        combinedDecision = true;
                    }
                    break;

                case EntitlementEndpointConstants.XPATH_VERSION:
                    String xPathVersion = jsonAttribute.getValue().getAsString();
                    requestDefaults = new RequestDefaults(xPathVersion);
                    break;
            }
        } else if (!jsonAttribute.getValue().isJsonNull()) {
            JsonObject jsonCategory = null;
            if (jsonAttribute.getValue().isJsonObject()) {
                jsonCategory = jsonAttribute.getValue().getAsJsonObject();
                jsonAttributeSeperator(jsonAttribute, jsonCategory, categories);

            } else if (jsonAttribute.getValue().isJsonArray()) {
                for (JsonElement jsonElement : jsonAttribute.getValue().getAsJsonArray()) {
                    jsonCategory = jsonElement.getAsJsonObject();
                    jsonAttributeSeperator(jsonAttribute, jsonCategory, categories);
                }
            } else if (EntitlementEndpointConstants.MULTI_REQUESTS.equals(jsonAttribute.getKey())) {
                Set<Map.Entry<String, JsonElement>> jsonRequestReferences = jsonCategory.entrySet();
                Set<RequestReference> requestReferences = new HashSet<>();

                if (jsonRequestReferences.isEmpty()) {
                    throw new RequestParseException("MultiRequest should contain at least one Reference Request");
                }
                for (Map.Entry<String, JsonElement> jsonRequstReference : jsonRequestReferences) {
                    requestReferences.add(jsonObjectToRequestReference(jsonRequstReference.getValue()
                            .getAsJsonObject()));
                }
                multiRequests = new MultiRequests(requestReferences);
            }
        }

    }

    return new RequestCtx(null,
            categories, returnPolicyIdList, combinedDecision, multiRequests, requestDefaults);

}
 
Example #30
Source File: AbstractPIPResourceFinder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public Set<String> findDescendantResources(String parentResourceId, EvaluationCtx context)
        throws Exception {

    EvaluationResult environment;
    String environmentId = null;
    Set<String> resourceNames = null;

    NodeList children = context.getRequestRoot().getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child != null) {
            if (PDPConstants.ENVIRONMENT_ELEMENT.equals(child.getLocalName())) {
                if (child.getChildNodes() != null && child.getChildNodes().getLength() > 0) {
                    environment = context.getAttribute(new URI(StringAttribute.identifier),
                            new URI(PDPConstants.ENVIRONMENT_ID_DEFAULT), null,
                            new URI(XACMLConstants.ENT_CATEGORY));
                    if (environment != null && environment.getAttributeValue() != null &&
                            environment.getAttributeValue().isBag()) {
                        BagAttribute attr = (BagAttribute) environment.getAttributeValue();
                        environmentId = ((AttributeValue) attr.iterator().next()).encode();
                    }
                }
            }
        }
    }

    if (isAbstractResourceCacheEnabled) {
        IdentityCacheKey cacheKey;
        String key = PDPConstants.RESOURCE_DESCENDANTS + parentResourceId +
                (environmentId != null ? environmentId : "");
        tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        cacheKey = new IdentityCacheKey(tenantId, key);
        IdentityCacheEntry cacheEntry = (IdentityCacheEntry) abstractResourceCache.getValueFromCache(cacheKey);
        if (cacheEntry != null) {
            String[] values = cacheEntry.getCacheEntryArray();
            resourceNames = new HashSet<String>(Arrays.asList(values));
            if (log.isDebugEnabled()) {
                log.debug("Carbon Resource Cache Hit");
            }
        }

        if (resourceNames != null) {
            resourceNames = findDescendantResources(parentResourceId, environmentId);
            if (log.isDebugEnabled()) {
                log.debug("Carbon Resource Cache Miss");
            }
            if (resourceNames != null && !resourceNames.isEmpty()) {
                cacheEntry = new IdentityCacheEntry(resourceNames.toArray(new String[resourceNames.size()]));
                abstractResourceCache.addToCache(cacheKey, cacheEntry);
            }
        }
    } else {
        resourceNames = findDescendantResources(parentResourceId, environmentId);
    }

    return resourceNames;
}