Search in sources :

Example 76 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class JuniperSrxResource method manageSecurityPolicy.

private boolean manageSecurityPolicy(SecurityPolicyType type, SrxCommand command, Long accountId, String username, String privateIp, List<String> applicationNames, List<String> cidrs, String ipsecVpnName, boolean defaultEgressAction) throws ExecutionException {
    String fromZone = _publicZone;
    String toZone = _privateZone;
    String securityPolicyName;
    String addressBookEntryName = null;
    if (type.equals(SecurityPolicyType.VPN) && ipsecVpnName != null) {
        securityPolicyName = ipsecVpnName;
        addressBookEntryName = ipsecVpnName;
    } else if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) {
        fromZone = _privateZone;
        toZone = _publicZone;
        securityPolicyName = genSecurityPolicyName(type, accountId, username, fromZone, toZone, privateIp);
    } else {
        securityPolicyName = genSecurityPolicyName(type, accountId, username, fromZone, toZone, privateIp);
        addressBookEntryName = genAddressBookEntryName(privateIp);
    }
    String xml;
    switch(command) {
        case CHECK_IF_EXISTS:
            xml = SrxXml.SECURITY_POLICY_GETONE.getXml();
            xml = setDelete(xml, false);
            xml = replaceXmlValue(xml, "from-zone", fromZone);
            xml = replaceXmlValue(xml, "to-zone", toZone);
            xml = replaceXmlValue(xml, "policy-name", securityPolicyName);
            return sendRequestAndCheckResponse(command, xml, "name", securityPolicyName);
        case CHECK_IF_IN_USE:
            List<String[]> rulesToCheck = null;
            if (type.equals(SecurityPolicyType.STATIC_NAT)) {
                // Check if any static NAT rules rely on this security policy
                rulesToCheck = getStaticNatRules(RuleMatchCondition.ALL, null, null);
            } else if (type.equals(SecurityPolicyType.DESTINATION_NAT)) {
                // Check if any destination NAT rules rely on this security policy
                rulesToCheck = getDestNatRules(RuleMatchCondition.ALL, null, null, null, null);
            } else {
                return false;
            }
            for (String[] rule : rulesToCheck) {
                String rulePrivateIp = rule[1];
                if (privateIp.equals(rulePrivateIp)) {
                    return true;
                }
            }
            return false;
        case ADD:
            if (!(type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT))) {
                if (!manageAddressBookEntry(SrxCommand.CHECK_IF_EXISTS, toZone, privateIp, addressBookEntryName)) {
                    throw new ExecutionException("No address book entry for policy: " + securityPolicyName);
                }
            }
            String srcAddrs = "";
            String dstAddrs = "";
            String action = "";
            xml = SrxXml.SECURITY_POLICY_ADD.getXml();
            xml = replaceXmlValue(xml, "policy-name", securityPolicyName);
            if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) {
                xml = replaceXmlValue(xml, "from-zone", _privateZone);
                xml = replaceXmlValue(xml, "to-zone", _publicZone);
                if (cidrs == null || cidrs.size() == 0) {
                    srcAddrs = "<source-address>any</source-address>";
                } else {
                    for (String cidr : cidrs) {
                        srcAddrs += "<source-address>" + genAddressBookEntryName(cidr) + "</source-address>";
                    }
                }
                xml = replaceXmlValue(xml, "src-address", srcAddrs);
                dstAddrs = "<destination-address>any</destination-address>";
                xml = replaceXmlValue(xml, "dst-address", dstAddrs);
                if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) {
                    if (defaultEgressAction == false) {
                        //for default policy is false add default deny rules
                        action = "<deny></deny>";
                    } else {
                        action = "<permit></permit>";
                    }
                } else {
                    if (defaultEgressAction == true) {
                        //configure egress rules to deny the traffic when default egress is allow
                        action = "<deny></deny>";
                    } else {
                        action = "<permit></permit>";
                    }
                    xml = replaceXmlValue(xml, "action", action);
                }
            } else {
                xml = replaceXmlValue(xml, "from-zone", fromZone);
                xml = replaceXmlValue(xml, "to-zone", toZone);
                srcAddrs = "<source-address>any</source-address>";
                xml = replaceXmlValue(xml, "src-address", srcAddrs);
                dstAddrs = "<destination-address>" + addressBookEntryName + "</destination-address>";
                xml = replaceXmlValue(xml, "dst-address", dstAddrs);
            }
            if (type.equals(SecurityPolicyType.VPN) && ipsecVpnName != null) {
                xml = replaceXmlValue(xml, "tunnel", "<permit><tunnel><ipsec-vpn>" + ipsecVpnName + "</ipsec-vpn></tunnel></permit>");
            } else {
                xml = replaceXmlValue(xml, "tunnel", "");
                if (!(type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS))) {
                    action = "<permit></permit>";
                    xml = replaceXmlValue(xml, "action", action);
                }
            }
            String applications;
            if (applicationNames == null || applicationNames.size() == 0) {
                applications = "<application>any</application>";
            } else {
                applications = "";
                for (String applicationName : applicationNames) {
                    applications += "<application>" + applicationName + "</application>";
                }
            }
            xml = replaceXmlValue(xml, "applications", applications);
            if (!sendRequestAndCheckResponse(command, xml)) {
                throw new ExecutionException("Failed to add security policy for privateIp " + privateIp + " and applications " + applicationNames);
            } else {
                return true;
            }
        case DELETE:
            if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, privateIp, applicationNames, cidrs, ipsecVpnName, defaultEgressAction)) {
                return true;
            }
            if (manageSecurityPolicy(type, SrxCommand.CHECK_IF_IN_USE, null, null, privateIp, applicationNames, cidrs, ipsecVpnName, defaultEgressAction)) {
                return true;
            }
            xml = SrxXml.SECURITY_POLICY_GETONE.getXml();
            xml = setDelete(xml, true);
            xml = replaceXmlValue(xml, "from-zone", fromZone);
            xml = replaceXmlValue(xml, "to-zone", toZone);
            xml = replaceXmlValue(xml, "policy-name", securityPolicyName);
            boolean success = sendRequestAndCheckResponse(command, xml);
            if (success) {
                xml = SrxXml.SECURITY_POLICY_GETALL.getXml();
                xml = replaceXmlValue(xml, "from-zone", fromZone);
                xml = replaceXmlValue(xml, "to-zone", toZone);
                String getAllResponseXml = sendRequest(xml);
                if (getAllResponseXml == null) {
                    throw new ExecutionException("Deleted security policy, but failed to delete security policy group.");
                }
                if (!getAllResponseXml.contains(fromZone) || !getAllResponseXml.contains(toZone)) {
                    return true;
                } else if (!getAllResponseXml.contains("match") && !getAllResponseXml.contains("then")) {
                    xml = SrxXml.SECURITY_POLICY_GROUP.getXml();
                    xml = replaceXmlValue(xml, "from-zone", fromZone);
                    xml = replaceXmlValue(xml, "to-zone", toZone);
                    xml = setDelete(xml, true);
                    if (!sendRequestAndCheckResponse(command, xml)) {
                        throw new ExecutionException("Deleted security policy, but failed to delete security policy group.");
                    } else {
                        return true;
                    }
                } else {
                    return true;
                }
            } else {
                throw new ExecutionException("Failed to delete security policy for privateIp " + privateIp + " and applications " + applicationNames);
            }
        default:
            s_logger.debug("Unrecognized command.");
            return false;
    }
}
Also used : ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 77 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class JuniperSrxResource method getDocument.

private Document getDocument(String xml) throws ExecutionException {
    StringReader srcNatRuleReader = new StringReader(xml);
    InputSource srcNatRuleSource = new InputSource(srcNatRuleReader);
    Document doc = null;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(srcNatRuleSource);
    } catch (Exception e) {
        s_logger.error(e);
        throw new ExecutionException(e.getMessage());
    }
    if (doc == null) {
        throw new ExecutionException("Failed to parse xml " + xml);
    } else {
        return doc;
    }
}
Also used : InputSource(org.xml.sax.InputSource) StringReader(java.io.StringReader) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException) ExecutionException(com.cloud.utils.exception.ExecutionException) ConfigurationException(javax.naming.ConfigurationException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Example 78 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class JuniperSrxResource method getUsageAnswer.

/*
     * Usage
     */
private ExternalNetworkResourceUsageAnswer getUsageAnswer(ExternalNetworkResourceUsageCommand cmd) throws ExecutionException {
    try {
        String socOpenException = "Failed to open a connection for Usage data.";
        String socCloseException = "Unable to close connection for Usage data.";
        if (!openUsageSocket()) {
            throw new ExecutionException(socOpenException);
        }
        ExternalNetworkResourceUsageAnswer answer = new ExternalNetworkResourceUsageAnswer(cmd);
        String xml = SrxXml.FIREWALL_FILTER_BYTES_GETALL.getXml();
        String rawUsageData = sendUsageRequest(xml);
        Document doc = getDocument(rawUsageData);
        NodeList counters = doc.getElementsByTagName("counter");
        for (int i = 0; i < counters.getLength(); i++) {
            Node n = counters.item(i);
            if (n.getNodeName().equals("counter")) {
                NodeList counterInfoList = n.getChildNodes();
                String counterName = null;
                long byteCount = 0;
                for (int j = 0; j < counterInfoList.getLength(); j++) {
                    Node counterInfo = counterInfoList.item(j);
                    if (counterInfo.getNodeName().equals("counter-name")) {
                        counterName = counterInfo.getFirstChild().getNodeValue();
                    } else if (counterInfo.getNodeName().equals("byte-count")) {
                        try {
                            byteCount = Long.parseLong(counterInfo.getFirstChild().getNodeValue());
                        } catch (Exception e) {
                            s_logger.debug(e);
                            byteCount = 0;
                        }
                    }
                }
                if (byteCount >= 0) {
                    updateUsageAnswer(answer, counterName, byteCount);
                }
            }
        }
        if (!closeUsageSocket()) {
            throw new ExecutionException(socCloseException);
        }
        return answer;
    } catch (Exception e) {
        closeUsageSocket();
        throw new ExecutionException(e.getMessage());
    }
}
Also used : ExternalNetworkResourceUsageAnswer(com.cloud.agent.api.ExternalNetworkResourceUsageAnswer) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ExecutionException(com.cloud.utils.exception.ExecutionException) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException) ConfigurationException(javax.naming.ConfigurationException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Example 79 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class JuniperSrxResource method execute.

private Answer execute(SetFirewallRulesCommand cmd, int numRetries) {
    FirewallRuleTO[] rules = cmd.getRules();
    try {
        openConfiguration();
        if (rules[0].getTrafficType() == FirewallRule.TrafficType.Egress) {
            Map<String, ArrayList<FirewallRuleTO>> activeRules = getActiveFirewallEgressRules(rules);
            Set<String> guestVlans = activeRules.keySet();
            // List<String> cidrs = new ArrayList();
            boolean defaultEgressPolicy = rules[0].isDefaultEgressPolicy();
            FirewallRule.FirewallRuleType type = rules[0].getType();
            //getting
            String guestCidr = rules[0].getGuestCidr();
            List<String> cidrs = new ArrayList<String>();
            cidrs.add(guestCidr);
            List<Object[]> applications = new ArrayList<Object[]>();
            Object[] application = new Object[3];
            application[0] = Protocol.all;
            application[1] = NetUtils.PORT_RANGE_MIN;
            application[2] = NetUtils.PORT_RANGE_MAX;
            applications.add(application);
            for (String guestVlan : guestVlans) {
                List<FirewallRuleTO> activeRulesForGuestNw = activeRules.get(guestVlan);
                removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS, guestVlan, extractCidrs(activeRulesForGuestNw), defaultEgressPolicy);
                if (activeRulesForGuestNw.size() > 0 && type == FirewallRule.FirewallRuleType.User) {
                    addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS, guestVlan, extractApplications(activeRulesForGuestNw), extractCidrs(activeRulesForGuestNw), defaultEgressPolicy);
                    /* Adding default policy rules are required because the order of rules is important.
                         * Depending on the rules order the traffic accept/drop is performed
                         */
                    removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, cidrs, defaultEgressPolicy);
                    addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, applications, cidrs, defaultEgressPolicy);
                }
                //remove required with out comparing default policy  because in upgrade network offering we may required to delete
                // the previously added rule
                removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, cidrs, false);
                if (defaultEgressPolicy == true && type == FirewallRule.FirewallRuleType.System) {
                    removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, cidrs, defaultEgressPolicy);
                    if (activeRulesForGuestNw.size() > 0) {
                        //add default egress security policy
                        addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, applications, cidrs, defaultEgressPolicy);
                    }
                }
            }
            commitConfiguration();
        } else {
            for (FirewallRuleTO rule : rules) {
                int startPort = NetUtils.PORT_RANGE_MIN, endPort = NetUtils.PORT_RANGE_MAX;
                if (rule.getSrcPortRange() != null) {
                    startPort = rule.getSrcPortRange()[0];
                    endPort = rule.getSrcPortRange()[1];
                }
                FirewallFilterTerm term = new FirewallFilterTerm(genIpIdentifier(rule.getSrcIp()) + "-" + String.valueOf(rule.getId()), rule.getSourceCidrList(), rule.getSrcIp(), rule.getProtocol(), startPort, endPort, rule.getIcmpType(), rule.getIcmpCode(), genIpIdentifier(rule.getSrcIp()) + _usageFilterIPInput.getCounterIdentifier());
                if (!rule.revoked()) {
                    manageProxyArp(SrxCommand.ADD, getVlanTag(rule.getSrcVlanTag()), rule.getSrcIp());
                    manageFirewallFilter(SrxCommand.ADD, term, _publicZoneInputFilterName);
                } else {
                    manageFirewallFilter(SrxCommand.DELETE, term, _publicZoneInputFilterName);
                    manageProxyArp(SrxCommand.DELETE, getVlanTag(rule.getSrcVlanTag()), rule.getSrcIp());
                }
            }
            commitConfiguration();
        }
        return new Answer(cmd);
    } catch (ExecutionException e) {
        s_logger.error(e);
        closeConfiguration();
        if (numRetries > 0 && refreshSrxConnection()) {
            int numRetriesRemaining = numRetries - 1;
            s_logger.debug("Retrying SetFirewallRulesCommand. Number of retries remaining: " + numRetriesRemaining);
            return execute(cmd, numRetriesRemaining);
        } else {
            return new Answer(cmd, e);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) FirewallRuleTO(com.cloud.agent.api.to.FirewallRuleTO) Answer(com.cloud.agent.api.Answer) MaintainAnswer(com.cloud.agent.api.MaintainAnswer) IpAssocAnswer(com.cloud.agent.api.routing.IpAssocAnswer) ReadyAnswer(com.cloud.agent.api.ReadyAnswer) ExternalNetworkResourceUsageAnswer(com.cloud.agent.api.ExternalNetworkResourceUsageAnswer) ExecutionException(com.cloud.utils.exception.ExecutionException) FirewallRule(com.cloud.network.rules.FirewallRule)

Example 80 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class JuniperSrxResource method execute.

private Answer execute(VpnUsersCfgCommand cmd, int numRetries) {
    long accountId = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.ACCOUNT_ID));
    String guestNetworkCidr = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR);
    String ikePolicyName = genIkePolicyName(accountId);
    UsernamePassword[] users = cmd.getUserpwds();
    try {
        openConfiguration();
        for (UsernamePassword user : users) {
            SrxCommand srxCmd = user.isAdd() ? SrxCommand.ADD : SrxCommand.DELETE;
            String ipsecVpnName = genIpsecVpnName(accountId, user.getUsername());
            // IKE gateway
            manageIkeGateway(srxCmd, null, accountId, ikePolicyName, _ikeGatewayHostname, user.getUsername());
            // IPSec VPN
            manageIpsecVpn(srxCmd, null, accountId, guestNetworkCidr, user.getUsername(), _ipsecPolicyName);
            // Dynamic VPN client
            manageDynamicVpnClient(srxCmd, null, accountId, guestNetworkCidr, ipsecVpnName, user.getUsername());
            // Access profile
            manageAccessProfile(srxCmd, null, accountId, user.getUsername(), user.getPassword(), genAddressPoolName(accountId));
            // Address book entry
            manageAddressBookEntry(srxCmd, _privateZone, guestNetworkCidr, ipsecVpnName);
            // Security policy
            manageSecurityPolicy(SecurityPolicyType.VPN, srxCmd, null, null, guestNetworkCidr, null, null, ipsecVpnName, false);
        }
        commitConfiguration();
        return new Answer(cmd);
    } catch (ExecutionException e) {
        s_logger.error(e);
        closeConfiguration();
        if (numRetries > 0 && refreshSrxConnection()) {
            int numRetriesRemaining = numRetries - 1;
            s_logger.debug("Retrying RemoteAccessVpnCfgCommand. Number of retries remaining: " + numRetriesRemaining);
            return execute(cmd, numRetriesRemaining);
        } else {
            return new Answer(cmd, e);
        }
    }
}
Also used : Answer(com.cloud.agent.api.Answer) MaintainAnswer(com.cloud.agent.api.MaintainAnswer) IpAssocAnswer(com.cloud.agent.api.routing.IpAssocAnswer) ReadyAnswer(com.cloud.agent.api.ReadyAnswer) ExternalNetworkResourceUsageAnswer(com.cloud.agent.api.ExternalNetworkResourceUsageAnswer) ExecutionException(com.cloud.utils.exception.ExecutionException) UsernamePassword(com.cloud.agent.api.routing.VpnUsersCfgCommand.UsernamePassword)

Aggregations

ExecutionException (com.cloud.utils.exception.ExecutionException)83 ConfigurationException (javax.naming.ConfigurationException)31 IOException (java.io.IOException)30 ArrayList (java.util.ArrayList)23 IpAssocAnswer (com.cloud.agent.api.routing.IpAssocAnswer)20 RemoteException (java.rmi.RemoteException)20 ExternalNetworkResourceUsageAnswer (com.cloud.agent.api.ExternalNetworkResourceUsageAnswer)19 Answer (com.cloud.agent.api.Answer)17 MaintainAnswer (com.cloud.agent.api.MaintainAnswer)16 ReadyAnswer (com.cloud.agent.api.ReadyAnswer)16 com.citrix.netscaler.nitro.exception.nitro_exception (com.citrix.netscaler.nitro.exception.nitro_exception)13 Document (org.w3c.dom.Document)12 XPathExpressionException (javax.xml.xpath.XPathExpressionException)11 HashMap (java.util.HashMap)10 XPath (javax.xml.xpath.XPath)8 XPathExpression (javax.xml.xpath.XPathExpression)8 NodeList (org.w3c.dom.NodeList)7 com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver (com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver)5 com.citrix.netscaler.nitro.resource.config.lb.lbvserver (com.citrix.netscaler.nitro.resource.config.lb.lbvserver)5 com.citrix.netscaler.nitro.resource.config.ns.nsconfig (com.citrix.netscaler.nitro.resource.config.ns.nsconfig)5