use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.
the class PaloAltoResource method configure.
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
try {
_name = (String) params.get("name");
if (_name == null) {
throw new ConfigurationException("Unable to find name");
}
_zoneId = (String) params.get("zoneId");
if (_zoneId == null) {
throw new ConfigurationException("Unable to find zone");
}
_ip = (String) params.get("ip");
if (_ip == null) {
throw new ConfigurationException("Unable to find IP");
}
_username = (String) params.get("username");
if (_username == null) {
throw new ConfigurationException("Unable to find username");
}
_password = (String) params.get("password");
if (_password == null) {
throw new ConfigurationException("Unable to find password");
}
_publicInterface = (String) params.get("publicinterface");
if (_publicInterface == null) {
throw new ConfigurationException("Unable to find public interface.");
}
_privateInterface = (String) params.get("privateinterface");
if (_privateInterface == null) {
throw new ConfigurationException("Unable to find private interface.");
}
_publicZone = (String) params.get("publicnetwork");
if (_publicZone == null) {
throw new ConfigurationException("Unable to find public zone");
}
_privateZone = (String) params.get("privatenetwork");
if (_privateZone == null) {
throw new ConfigurationException("Unable to find private zone");
}
_virtualRouter = (String) params.get("pavr");
if (_virtualRouter == null) {
throw new ConfigurationException("Unable to find virtual router");
}
_threatProfile = (String) params.get("patp");
_logProfile = (String) params.get("palp");
_guid = (String) params.get("guid");
if (_guid == null) {
throw new ConfigurationException("Unable to find the guid");
}
_numRetries = NumbersUtil.parseInt((String) params.get("numretries"), 1);
_timeoutInSeconds = NumbersUtil.parseInt((String) params.get("timeout"), 300);
// Open a socket and login
if (!refreshPaloAltoConnection()) {
throw new ConfigurationException("Unable to open a connection to the Palo Alto.");
}
// check that the threat profile exists if one was specified
if (_threatProfile != null) {
try {
boolean has_profile = getThreatProfile(_threatProfile);
if (!has_profile) {
throw new ConfigurationException("The specified threat profile group does not exist.");
}
} catch (ExecutionException e) {
throw new ConfigurationException(e.getMessage());
}
}
// check that the log profile exists if one was specified
if (_logProfile != null) {
try {
boolean has_profile = getLogProfile(_logProfile);
if (!has_profile) {
throw new ConfigurationException("The specified log profile does not exist.");
}
} catch (ExecutionException e) {
throw new ConfigurationException(e.getMessage());
}
}
// get public interface type
try {
_publicInterfaceType = getInterfaceType(_publicInterface);
if (_publicInterfaceType.equals("")) {
throw new ConfigurationException("The specified public interface is not configured on the Palo Alto.");
}
} catch (ExecutionException e) {
throw new ConfigurationException(e.getMessage());
}
// get private interface type
try {
_privateInterfaceType = getInterfaceType(_privateInterface);
if (_privateInterfaceType.equals("")) {
throw new ConfigurationException("The specified private interface is not configured on the Palo Alto.");
}
} catch (ExecutionException e) {
throw new ConfigurationException(e.getMessage());
}
_pingManagementProfile = "Ping";
try {
ArrayList<IPaloAltoCommand> cmdList = new ArrayList<IPaloAltoCommand>();
managePingProfile(cmdList, PaloAltoPrimative.ADD);
boolean status = requestWithCommit(cmdList);
} catch (ExecutionException e) {
throw new ConfigurationException(e.getMessage());
}
return true;
} catch (Exception e) {
throw new ConfigurationException(e.getMessage());
}
}
use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.
the class PaloAltoResource method requestWithPolling.
/* Used for requests that require polling to get a result (eg: commit) */
private String requestWithPolling(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
String job_id;
String job_response = request(method, params);
Document doc = getDocument(job_response);
XPath xpath = XPathFactory.newInstance().newXPath();
try {
XPathExpression expr = xpath.compile("/response[@status='success']/result/job/text()");
job_id = (String) expr.evaluate(doc, XPathConstants.STRING);
} catch (XPathExpressionException e) {
throw new ExecutionException(e.getCause().getMessage());
}
if (job_id.length() > 0) {
boolean finished = false;
Map<String, String> job_params = new HashMap<String, String>();
job_params.put("type", "op");
job_params.put("cmd", "<show><jobs><id>" + job_id + "</id></jobs></show>");
while (!finished) {
String job_status;
String response = request(PaloAltoMethod.GET, job_params);
Document job_doc = getDocument(response);
XPath job_xpath = XPathFactory.newInstance().newXPath();
try {
XPathExpression expr = job_xpath.compile("/response[@status='success']/result/job/status/text()");
job_status = (String) expr.evaluate(job_doc, XPathConstants.STRING);
} catch (XPathExpressionException e) {
throw new ExecutionException(e.getCause().getMessage());
}
if (job_status.equals("FIN")) {
finished = true;
String job_result;
try {
XPathExpression expr = job_xpath.compile("/response[@status='success']/result/job/result/text()");
job_result = (String) expr.evaluate(job_doc, XPathConstants.STRING);
} catch (XPathExpressionException e) {
throw new ExecutionException(e.getCause().getMessage());
}
if (!job_result.equals("OK")) {
NodeList job_details;
try {
XPathExpression expr = job_xpath.compile("/response[@status='success']/result/job/details/line");
job_details = (NodeList) expr.evaluate(job_doc, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new ExecutionException(e.getCause().getMessage());
}
String error = "";
for (int i = 0; i < job_details.getLength(); i++) {
error = error + job_details.item(i).getTextContent() + "\n";
}
throw new ExecutionException(error);
}
return response;
} else {
try {
// poll periodically for the status of the async job...
Thread.sleep(2000);
} catch (InterruptedException e) {
/* do nothing */
}
}
}
} else {
return job_response;
}
return null;
}
use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.
the class PaloAltoResource method request.
/*
* XML API commands
*/
/* Function to make calls to the Palo Alto API. */
/* All API calls will end up going through this function. */
protected String request(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
if (method != PaloAltoMethod.GET && method != PaloAltoMethod.POST) {
throw new ExecutionException("Invalid http method used to access the Palo Alto API.");
}
String responseBody = "";
String debug_msg = "Palo Alto Request\n";
// a GET method...
if (method == PaloAltoMethod.GET) {
String queryString = "?";
for (String key : params.keySet()) {
if (!queryString.equals("?")) {
queryString = queryString + "&";
}
try {
queryString = queryString + key + "=" + URLEncoder.encode(params.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ExecutionException(e.getMessage());
}
}
if (_key != null) {
queryString = queryString + "&key=" + _key;
}
try {
debug_msg = debug_msg + "GET request: https://" + _ip + s_apiUri + URLDecoder.decode(queryString, "UTF-8") + "\n";
} catch (UnsupportedEncodingException e) {
debug_msg = debug_msg + "GET request: https://" + _ip + s_apiUri + queryString + "\n";
}
HttpGet get_request = new HttpGet("https://" + _ip + s_apiUri + queryString);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
responseBody = s_httpclient.execute(get_request, responseHandler);
} catch (IOException e) {
throw new ExecutionException(e.getMessage());
}
}
// a POST method...
if (method == PaloAltoMethod.POST) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
if (_key != null) {
nvps.add(new BasicNameValuePair("key", _key));
}
debug_msg = debug_msg + "POST request: https://" + _ip + s_apiUri + "\n";
for (NameValuePair nvp : nvps) {
debug_msg = debug_msg + "param: " + nvp.getName() + ", " + nvp.getValue() + "\n";
}
HttpPost post_request = new HttpPost("https://" + _ip + s_apiUri);
try {
post_request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
throw new ExecutionException(e.getMessage());
}
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
responseBody = s_httpclient.execute(post_request, responseHandler);
} catch (IOException e) {
throw new ExecutionException(e.getMessage());
}
}
debug_msg = debug_msg + prettyFormat(responseBody);
// test cases
debug_msg = debug_msg + "\n" + responseBody.replace("\"", "\\\"") + "\n\n";
return responseBody;
}
use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.
the class PaloAltoResource method execute.
private Answer execute(SetPortForwardingRulesCommand cmd, int numRetries) {
PortForwardingRuleTO[] rules = cmd.getRules();
try {
ArrayList<IPaloAltoCommand> commandList = new ArrayList<IPaloAltoCommand>();
for (PortForwardingRuleTO rule : rules) {
if (!rule.revoked()) {
manageDstNatRule(commandList, PaloAltoPrimative.ADD, rule);
} else {
manageDstNatRule(commandList, PaloAltoPrimative.DELETE, rule);
}
}
boolean status = requestWithCommit(commandList);
return new Answer(cmd);
} catch (ExecutionException e) {
s_logger.error(e);
if (numRetries > 0 && refreshPaloAltoConnection()) {
int numRetriesRemaining = numRetries - 1;
s_logger.debug("Retrying SetPortForwardingRulesCommand. 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 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;
}
}
Aggregations