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;
}
}
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;
}
}
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());
}
}
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);
}
}
}
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);
}
}
}
Aggregations