Search in sources :

Example 91 with XPathExpression

use of javax.xml.xpath.XPathExpression in project cloudstack by apache.

the class PaloAltoResource method manageFirewallRule.

public boolean manageFirewallRule(ArrayList<IPaloAltoCommand> cmdList, PaloAltoPrimative prim, FirewallRuleTO rule) throws ExecutionException {
    String ruleName;
    if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
        ruleName = genFirewallRuleName(rule.getId(), rule.getSrcVlanTag());
    } else {
        ruleName = genFirewallRuleName(rule.getId());
    }
    switch(prim) {
        case CHECK_IF_EXISTS:
            // check if one exists already
            Map<String, String> params = new HashMap<String, String>();
            params.put("type", "config");
            params.put("action", "get");
            params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='" + ruleName + "']");
            String response = request(PaloAltoMethod.GET, params);
            boolean result = (validResponse(response) && responseNotEmpty(response));
            s_logger.debug("Firewall policy exists: " + ruleName + ", " + result);
            return result;
        case ADD:
            if (manageFirewallRule(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, rule)) {
                return true;
            }
            String srcZone;
            String dstZone;
            String dstAddressXML;
            String appXML;
            String serviceXML;
            String protocol = rule.getProtocol();
            String action = "allow";
            // Only ICMP will use an Application, so others will be any.
            if (protocol.equals(Protocol.ICMP.toString())) {
                // use the default icmp applications...
                appXML = "<member>icmp</member><member>ping</member><member>traceroute</member>";
            } else {
                appXML = "<member>any</member>";
            }
            // Only TCP and UDP will use a Service, others will use any.
            if (protocol.equals(Protocol.TCP.toString()) || protocol.equals(Protocol.UDP.toString())) {
                String portRange;
                if (rule.getSrcPortRange() != null) {
                    int startPort = rule.getSrcPortRange()[0];
                    int endPort = rule.getSrcPortRange()[1];
                    if (startPort == endPort) {
                        portRange = String.valueOf(startPort);
                    } else {
                        portRange = String.valueOf(startPort) + "-" + String.valueOf(endPort);
                    }
                    manageService(cmdList, PaloAltoPrimative.ADD, protocol, portRange, null);
                    serviceXML = "<member>" + genServiceName(protocol, portRange, null) + "</member>";
                } else {
                    // no equivalent config in PA, so allow all traffic...
                    serviceXML = "<member>any</member>";
                }
            } else {
                serviceXML = "<member>any</member>";
            }
            // handle different types of fire wall rules (egress | ingress)
            if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                // Egress Rule
                srcZone = _privateZone;
                dstZone = _publicZone;
                dstAddressXML = "<member>any</member>";
                // defaults to 'allow', the deny rules are as follows
                if (rule.getType() == FirewallRule.FirewallRuleType.System) {
                    if (!rule.isDefaultEgressPolicy()) {
                        // default of deny && system rule, so deny
                        action = "deny";
                    }
                } else {
                    if (rule.isDefaultEgressPolicy()) {
                        // default is allow && user rule, so deny
                        action = "deny";
                    }
                }
            } else {
                // Ingress Rule
                srcZone = _publicZone;
                dstZone = _privateZone;
                dstAddressXML = "<member>" + rule.getSrcIp() + "</member>";
            }
            // build the source cidr xml
            String srcCidrXML = "";
            List<String> ruleSrcCidrList = rule.getSourceCidrList();
            if (ruleSrcCidrList.size() > 0) {
                // a cidr was entered, modify as needed...
                for (int i = 0; i < ruleSrcCidrList.size(); i++) {
                    if (ruleSrcCidrList.get(i).trim().equals("0.0.0.0/0")) {
                        // allow any
                        if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                            srcCidrXML += "<member>" + getPrivateSubnet(rule.getSrcVlanTag()) + "</member>";
                        } else {
                            srcCidrXML += "<member>any</member>";
                        }
                    } else {
                        srcCidrXML += "<member>" + ruleSrcCidrList.get(i).trim() + "</member>";
                    }
                }
            } else {
                // no cidr was entered, so allow ALL according to firewall rule type
                if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                    srcCidrXML = "<member>" + getPrivateSubnet(rule.getSrcVlanTag()) + "</member>";
                } else {
                    srcCidrXML = "<member>any</member>";
                }
            }
            // build new rule xml
            String xml = "";
            xml += "<from><member>" + srcZone + "</member></from>";
            xml += "<to><member>" + dstZone + "</member></to>";
            xml += "<source>" + srcCidrXML + "</source>";
            xml += "<destination>" + dstAddressXML + "</destination>";
            xml += "<application>" + appXML + "</application>";
            xml += "<service>" + serviceXML + "</service>";
            xml += "<action>" + action + "</action>";
            xml += "<negate-source>no</negate-source>";
            xml += "<negate-destination>no</negate-destination>";
            if (_threatProfile != null && action.equals("allow")) {
                // add the threat profile if it exists
                xml += "<profile-setting><group><member>" + _threatProfile + "</member></group></profile-setting>";
            }
            if (_logProfile != null && action.equals("allow")) {
                // add the log profile if it exists
                xml += "<log-setting>" + _logProfile + "</log-setting>";
            }
            boolean has_default = false;
            String defaultEgressRule = "";
            if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                // check if a default egress rule exists because it always has to be after the other rules.
                Map<String, String> e_params = new HashMap<String, String>();
                e_params.put("type", "config");
                e_params.put("action", "get");
                e_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_" + rule.getSrcVlanTag() + "']");
                String e_response = request(PaloAltoMethod.GET, e_params);
                has_default = (validResponse(e_response) && responseNotEmpty(e_response));
                // there is an existing default rule, so we need to remove it and add it back after the new rule is added.
                if (has_default) {
                    s_logger.debug("Moving the default egress rule after the new rule: " + ruleName);
                    NodeList response_body;
                    Document doc = getDocument(e_response);
                    XPath xpath = XPathFactory.newInstance().newXPath();
                    try {
                        XPathExpression expr = xpath.compile("/response[@status='success']/result/entry/node()");
                        response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                    } catch (XPathExpressionException e) {
                        throw new ExecutionException(e.getCause().getMessage());
                    }
                    for (int i = 0; i < response_body.getLength(); i++) {
                        Node n = response_body.item(i);
                        defaultEgressRule += nodeToString(n);
                    }
                    Map<String, String> dd_params = new HashMap<String, String>();
                    dd_params.put("type", "config");
                    dd_params.put("action", "delete");
                    dd_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_" + rule.getSrcVlanTag() + "']");
                    cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, dd_params));
                }
            }
            // add the new rule...
            Map<String, String> a_params = new HashMap<String, String>();
            a_params.put("type", "config");
            a_params.put("action", "set");
            a_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='" + ruleName + "']");
            a_params.put("element", xml);
            cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, a_params));
            // add back the default rule
            if (rule.getTrafficType() == FirewallRule.TrafficType.Egress && has_default) {
                Map<String, String> da_params = new HashMap<String, String>();
                da_params.put("type", "config");
                da_params.put("action", "set");
                da_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_" + rule.getSrcVlanTag() + "']");
                da_params.put("element", defaultEgressRule);
                cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, da_params));
                s_logger.debug("Completed move of the default egress rule after rule: " + ruleName);
            }
            return true;
        case DELETE:
            if (!manageFirewallRule(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, rule)) {
                return true;
            }
            Map<String, String> d_params = new HashMap<String, String>();
            d_params.put("type", "config");
            d_params.put("action", "delete");
            d_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='" + ruleName + "']");
            cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, d_params));
            return true;
        default:
            s_logger.debug("Unrecognized command.");
            return false;
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 92 with XPathExpression

use of javax.xml.xpath.XPathExpression in project cloudstack by apache.

the class PaloAltoResource method validResponse.

/* A default response handler to validate that the request was successful. */
public boolean validResponse(String response) throws ExecutionException {
    NodeList response_body;
    Document doc = getDocument(response);
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        XPathExpression expr = xpath.compile("/response[@status='success']");
        response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new ExecutionException(e.getCause().getMessage());
    }
    if (response_body.getLength() > 0) {
        return true;
    } else {
        NodeList error_details;
        try {
            XPathExpression expr = xpath.compile("/response/msg/line/line");
            error_details = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            throw new ExecutionException(e.getCause().getMessage());
        }
        if (error_details.getLength() == 0) {
            try {
                XPathExpression expr = xpath.compile("/response/msg/line");
                error_details = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            } catch (XPathExpressionException e) {
                throw new ExecutionException(e.getCause().getMessage());
            }
            if (error_details.getLength() == 0) {
                try {
                    XPathExpression expr = xpath.compile("/response/result/msg");
                    error_details = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
            }
        }
        String error = "";
        for (int i = 0; i < error_details.getLength(); i++) {
            error = error + error_details.item(i).getTextContent() + "\n";
        }
        throw new ExecutionException(error);
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 93 with XPathExpression

use of javax.xml.xpath.XPathExpression in project cloudstack by apache.

the class OvmObject method xmlToMap.

/* was String, Object before */
public <E> Map<String, E> xmlToMap(String path, Document xmlDocument) throws Ovm3ResourceException {
    XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    try {
        XPathExpression xPathExpression = xPath.compile(path);
        NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDocument, XPathConstants.NODESET);
        Map<String, E> myMap = new HashMap<String, E>();
        for (int ind = 0; ind < nodeList.getLength(); ind++) {
            NodeList nodeListFor = nodeList.item(ind).getChildNodes();
            for (int index = 0; index < nodeListFor.getLength(); index++) {
                String rnode = nodeListFor.item(index).getNodeName();
                NodeList nodeListFor2 = nodeListFor.item(index).getChildNodes();
                if (nodeListFor2.getLength() > 1) {
                /* Do we need to figure out all the sub elements here and put them in a map? */
                } else {
                    String element = nodeListFor.item(index).getTextContent();
                    myMap.put(rnode, (E) element);
                }
            }
        }
        return myMap;
    } catch (XPathExpressionException e) {
        throw new Ovm3ResourceException("Problem parsing XML to Map:", e);
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) XPathFactory(javax.xml.xpath.XPathFactory) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList)

Example 94 with XPathExpression

use of javax.xml.xpath.XPathExpression in project cloudstack by apache.

the class OvmObject method xmlToString.

public String xmlToString(String path, Document xmlDocument) throws Ovm3ResourceException {
    XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    try {
        XPathExpression xPathExpression = xPath.compile(path);
        NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDocument, XPathConstants.NODESET);
        return nodeList.item(0).getTextContent();
    } catch (NullPointerException e) {
        LOGGER.info("Got no items back from parsing, returning null: " + e);
        return null;
    } catch (XPathExpressionException e) {
        throw new Ovm3ResourceException("Problem parsing XML to String: ", e);
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) XPathFactory(javax.xml.xpath.XPathFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList)

Example 95 with XPathExpression

use of javax.xml.xpath.XPathExpression in project sling by apache.

the class OsgiMetadataUtil method initMetadataDocumentCache.

/**
     * Reads all SCR metadata XML documents located at OSGI-INF/ and caches them with quick access by implementation class.
     * @return Cache map
     */
private static Map<String, Document> initMetadataDocumentCache() {
    Map<String, Document> cacheMap = new HashMap<>();
    XPath xpath = XPATH_FACTORY.newXPath();
    xpath.setNamespaceContext(NAMESPACE_CONTEXT);
    XPathExpression xpathExpression;
    try {
        xpathExpression = xpath.compile("//*[implementation/@class]");
    } catch (XPathExpressionException ex) {
        throw new RuntimeException("Compiling XPath expression failed.", ex);
    }
    Reflections reflections = new Reflections(METADATA_PATH, new ResourcesScanner());
    Set<String> paths = reflections.getResources(Pattern.compile("^.*\\.xml$"));
    for (String path : paths) {
        parseMetadataDocuments(cacheMap, path, xpathExpression);
    }
    return cacheMap;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ResourcesScanner(org.reflections.scanners.ResourcesScanner) Document(org.w3c.dom.Document) Reflections(org.reflections.Reflections)

Aggregations

XPathExpression (javax.xml.xpath.XPathExpression)98 XPath (javax.xml.xpath.XPath)69 NodeList (org.w3c.dom.NodeList)56 Document (org.w3c.dom.Document)48 XPathExpressionException (javax.xml.xpath.XPathExpressionException)40 XPathFactory (javax.xml.xpath.XPathFactory)40 Node (org.w3c.dom.Node)38 DocumentBuilder (javax.xml.parsers.DocumentBuilder)24 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)19 Test (org.junit.Test)15 ArrayList (java.util.ArrayList)13 HashMap (java.util.HashMap)13 Element (org.w3c.dom.Element)12 PBXNativeTarget (com.facebook.buck.apple.xcode.xcodeproj.PBXNativeTarget)11 PBXTarget (com.facebook.buck.apple.xcode.xcodeproj.PBXTarget)11 ImmutableMap (com.google.common.collect.ImmutableMap)11 IOException (java.io.IOException)11 Path (java.nio.file.Path)11 PBXFileReference (com.facebook.buck.apple.xcode.xcodeproj.PBXFileReference)10 InputSource (org.xml.sax.InputSource)9