2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.policy.pap.xacml.rest.components;
23 import java.io.BufferedWriter;
25 import java.io.FileWriter;
26 import java.io.IOException;
27 import java.io.StringReader;
29 import java.net.URISyntaxException;
30 import java.nio.charset.Charset;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.sql.Connection;
35 import java.sql.DriverManager;
36 import java.sql.ResultSet;
37 import java.sql.SQLException;
38 import java.sql.Statement;
39 import java.util.HashMap;
40 import java.util.List;
43 import javax.json.Json;
44 import javax.json.JsonArray;
45 import javax.json.JsonObject;
46 import javax.json.JsonReader;
47 import javax.persistence.EntityManager;
48 import javax.persistence.Query;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
64 import org.apache.commons.io.FilenameUtils;
65 import org.openecomp.policy.common.logging.eelf.MessageCodes;
66 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
67 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
68 import org.openecomp.policy.common.logging.flexlogger.Logger;
69 import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
70 import org.openecomp.policy.rest.XACMLRestProperties;
71 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
72 import org.openecomp.policy.rest.jpa.PolicyEntity;
74 import com.att.research.xacml.std.IdentifierImpl;
75 import com.att.research.xacml.util.XACMLProperties;
76 import com.fasterxml.jackson.databind.JsonNode;
77 import com.github.fge.jackson.JsonLoader;
78 import com.github.fge.jsonpatch.JsonPatch;
79 import com.github.fge.jsonpatch.diff.JsonDiff;
81 public class FirewallConfigPolicy extends Policy {
83 private static final Logger LOGGER = FlexLogger.getLogger(FirewallConfigPolicy.class);
86 * These are the parameters needed for DB access from the PAP
88 private static String papDbDriver = null;
89 private static String papDbUrl = null;
90 private static String papDbUser = null;
91 private static String papDbPassword = null;
93 public FirewallConfigPolicy() {
97 public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) {
98 this.policyAdapter = policyAdapter;
99 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
103 // Saving the Configurations file at server location for config policy.
104 protected void saveConfigurations(String policyName, String jsonBody) {
106 if(policyName.endsWith(".xml")){
107 policyName = policyName.replace(".xml", "");
109 FileWriter fw = new FileWriter(CONFIG_HOME + File.separator + policyName + ".json");
110 BufferedWriter bw = new BufferedWriter(fw);
113 if (LOGGER.isDebugEnabled()) {
114 LOGGER.debug("Configuration is succesfully saved");
116 } catch (IOException e) {
117 LOGGER.error("Exception Occured"+e);
121 //Utility to read json data from the existing file to a string
122 static String readFile(String path, Charset encoding) throws IOException {
124 byte[] encoded = Files.readAllBytes(Paths.get(path));
125 return new String(encoded, encoding);
129 // Validations for Config form
130 public boolean validateConfigForm() {
132 // Validating mandatory Fields.
139 public Map<String, String> savePolicies() throws Exception {
141 Map<String, String> successMap = new HashMap<String,String>();
142 if(isPolicyExists()){
143 successMap.put("EXISTS", "This Policy already exist on the PAP");
147 if(!isPreparedToSave()){
151 // Until here we prepared the data and here calling the method to create xml.
152 Path newPolicyPath = null;
153 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
154 Boolean dbIsUpdated = false;
155 if (policyAdapter.getApiflag() != null && policyAdapter.getApiflag().equalsIgnoreCase("admin")){
156 if (policyAdapter.isEditPolicy()) {
157 dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
159 dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
166 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
168 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
170 //remove the new json file
171 String jsonBody = policyAdapter.getPrevJsonBody();
173 saveConfigurations(policyName, jsonBody);
175 saveConfigurations(policyName, "");
177 successMap.put("fwdberror", "DB UPDATE");
183 //This is the method for preparing the policy for saving. We have broken it out
184 //separately because the fully configured policy is used for multiple things
186 public boolean prepareToSave() throws Exception{
188 if(isPreparedToSave()){
189 //we have already done this
194 String policyID = policyAdapter.getPolicyID();
195 version = policyAdapter.getHighestVersion();
197 // Create the Instance for pojo, PolicyType object is used in marshalling.
198 if (policyAdapter.getPolicyType().equals("Config")) {
199 PolicyType policyConfig = new PolicyType();
201 policyConfig.setVersion(Integer.toString(version));
202 policyConfig.setPolicyId(policyID);
203 policyConfig.setTarget(new TargetType());
204 policyAdapter.setData(policyConfig);
206 policyName = policyAdapter.getNewFileName();
208 //String oldPolicyName = policyName.replace(".xml", "");
209 String scope = policyName.substring(0, policyName.indexOf("."));
210 String dbPolicyName = policyName.substring(policyName.indexOf(".")+1).replace(".xml", "");
212 int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf(".")+1));
213 dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf(".")+1);
214 //String scope = oldPolicyName.substring(0, oldPolicyName.lastIndexOf("."));
215 //scope = scope.substring(0, scope.lastIndexOf("."));
217 oldversion = oldversion - 1;
218 dbPolicyName = dbPolicyName + oldversion + ".xml";
220 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
221 Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
222 createPolicyQuery.setParameter("scope", scope);
223 createPolicyQuery.setParameter("policyName", dbPolicyName);
224 List<?> createPolicyQueryList = createPolicyQuery.getResultList();
225 if(!createPolicyQueryList.isEmpty()){
226 PolicyEntity entitydata = (PolicyEntity) createPolicyQueryList.get(0);
227 policyAdapter.setPrevJsonBody(entitydata.getConfigurationData().getConfigBody());
230 if (policyAdapter.getData() != null) {
231 String jsonBody = policyAdapter.getJsonBody();
232 saveConfigurations(policyName, jsonBody);
234 // Make sure the filename ends with an extension
235 if (policyName.endsWith(".xml") == false) {
236 policyName = policyName + ".xml";
239 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
241 configPolicy.setDescription(policyAdapter.getPolicyDescription());
243 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
245 AllOfType allOfOne = new AllOfType();
246 String fileName = policyAdapter.getNewFileName();
247 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
248 if ((name == null) || (name.equals(""))) {
249 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
251 allOfOne.getMatch().add(createMatch("PolicyName", name));
252 AllOfType allOf = new AllOfType();
254 // Match for ConfigName
255 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
256 // Match for riskType
257 allOf.getMatch().add(
258 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
259 // Match for riskLevel
260 allOf.getMatch().add(
261 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
262 // Match for riskguard
263 allOf.getMatch().add(
264 createDynamicMatch("guard", policyAdapter.getGuard()));
266 allOf.getMatch().add(
267 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
268 AnyOfType anyOf = new AnyOfType();
269 anyOf.getAllOf().add(allOfOne);
270 anyOf.getAllOf().add(allOf);
272 TargetType target = new TargetType();
273 ((TargetType) target).getAnyOf().add(anyOf);
275 // Adding the target to the policy element
276 configPolicy.setTarget((TargetType) target);
278 RuleType rule = new RuleType();
279 rule.setRuleId(policyAdapter.getRuleID());
281 rule.setEffect(EffectType.PERMIT);
283 // Create Target in Rule
284 AllOfType allOfInRule = new AllOfType();
286 // Creating match for ACCESS in rule target
287 MatchType accessMatch = new MatchType();
288 AttributeValueType accessAttributeValue = new AttributeValueType();
289 accessAttributeValue.setDataType(STRING_DATATYPE);
290 accessAttributeValue.getContent().add("ACCESS");
291 accessMatch.setAttributeValue(accessAttributeValue);
292 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
293 URI accessURI = null;
295 accessURI = new URI(ACTION_ID);
296 } catch (URISyntaxException e) {
297 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
299 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
300 accessAttributeDesignator.setDataType(STRING_DATATYPE);
301 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
302 accessMatch.setAttributeDesignator(accessAttributeDesignator);
303 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
305 // Creating Config Match in rule Target
306 MatchType configMatch = new MatchType();
307 AttributeValueType configAttributeValue = new AttributeValueType();
308 configAttributeValue.setDataType(STRING_DATATYPE);
310 configAttributeValue.getContent().add("Config");
312 configMatch.setAttributeValue(configAttributeValue);
313 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
314 URI configURI = null;
316 configURI = new URI(RESOURCE_ID);
317 } catch (URISyntaxException e) {
318 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
321 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
322 configAttributeDesignator.setDataType(STRING_DATATYPE);
323 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
324 configMatch.setAttributeDesignator(configAttributeDesignator);
325 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
327 allOfInRule.getMatch().add(accessMatch);
328 allOfInRule.getMatch().add(configMatch);
330 AnyOfType anyOfInRule = new AnyOfType();
331 anyOfInRule.getAllOf().add(allOfInRule);
333 TargetType targetInRule = new TargetType();
334 targetInRule.getAnyOf().add(anyOfInRule);
336 rule.setTarget(targetInRule);
337 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
339 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
340 policyAdapter.setPolicyData(configPolicy);
343 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
345 setPreparedToSave(true);
349 // Data required for Advice part is setting here.
350 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
352 //Firewall Config ID Assignment
353 AdviceExpressionsType advices = new AdviceExpressionsType();
354 AdviceExpressionType advice = new AdviceExpressionType();
355 advice.setAdviceId("firewallConfigID");
356 advice.setAppliesTo(EffectType.PERMIT);
358 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
359 assignment1.setAttributeId("type");
360 assignment1.setCategory(CATEGORY_RESOURCE);
361 assignment1.setIssuer("");
362 AttributeValueType configNameAttributeValue = new AttributeValueType();
363 configNameAttributeValue.setDataType(STRING_DATATYPE);
364 configNameAttributeValue.getContent().add("Configuration");
365 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
366 advice.getAttributeAssignmentExpression().add(assignment1);
368 // For Config file Url if configurations are provided.
370 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
371 assignment2.setAttributeId("URLID");
372 assignment2.setCategory(CATEGORY_RESOURCE);
373 assignment2.setIssuer("");
374 AttributeValueType AttributeValue = new AttributeValueType();
375 AttributeValue.setDataType(URI_DATATYPE);
376 if (policyName.endsWith(".xml")) {
377 policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
379 String content = CONFIG_URL + "/Config/" + policyName + ".json";
381 AttributeValue.getContent().add(content);
382 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
383 advice.getAttributeAssignmentExpression().add(assignment2);
385 //Policy Name Assignment
386 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
387 assignment3.setAttributeId("PolicyName");
388 assignment3.setCategory(CATEGORY_RESOURCE);
389 assignment3.setIssuer("");
390 AttributeValueType attributeValue3 = new AttributeValueType();
391 attributeValue3.setDataType(STRING_DATATYPE);
392 fileName = FilenameUtils.removeExtension(fileName);
393 fileName = fileName + ".xml";
394 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
395 if ((name == null) || (name.equals(""))) {
396 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
398 attributeValue3.getContent().add(name);
399 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
400 advice.getAttributeAssignmentExpression().add(assignment3);
402 //Version Number Assignment
403 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
404 assignment4.setAttributeId("VersionNumber");
405 assignment4.setCategory(CATEGORY_RESOURCE);
406 assignment4.setIssuer("");
407 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
408 configNameAttributeValue4.setDataType(STRING_DATATYPE);
409 configNameAttributeValue4.getContent().add(Integer.toString(version));
410 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
411 advice.getAttributeAssignmentExpression().add(assignment4);
413 //Ecomp Name Assignment
414 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
415 assignment5.setAttributeId("matching:" + ECOMPID);
416 assignment5.setCategory(CATEGORY_RESOURCE);
417 assignment5.setIssuer("");
418 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
419 configNameAttributeValue5.setDataType(STRING_DATATYPE);
420 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
421 advice.getAttributeAssignmentExpression().add(assignment5);
423 //Config Name Assignment
424 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
425 assignment6.setAttributeId("matching:" + CONFIGID);
426 assignment6.setCategory(CATEGORY_RESOURCE);
427 assignment6.setIssuer("");
428 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
429 configNameAttributeValue6.setDataType(STRING_DATATYPE);
430 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
431 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
432 advice.getAttributeAssignmentExpression().add(assignment6);
435 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
436 assignment7.setAttributeId("RiskType");
437 assignment7.setCategory(CATEGORY_RESOURCE);
438 assignment7.setIssuer("");
440 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
441 configNameAttributeValue7.setDataType(STRING_DATATYPE);
442 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
443 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
445 advice.getAttributeAssignmentExpression().add(assignment7);
447 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
448 assignment8.setAttributeId("RiskLevel");
449 assignment8.setCategory(CATEGORY_RESOURCE);
450 assignment8.setIssuer("");
452 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
453 configNameAttributeValue8.setDataType(STRING_DATATYPE);
454 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
455 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
457 advice.getAttributeAssignmentExpression().add(assignment8);
459 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
460 assignment9.setAttributeId("guard");
461 assignment9.setCategory(CATEGORY_RESOURCE);
462 assignment9.setIssuer("");
464 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
465 configNameAttributeValue9.setDataType(STRING_DATATYPE);
466 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
467 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
469 advice.getAttributeAssignmentExpression().add(assignment9);
471 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
472 assignment10.setAttributeId("TTLDate");
473 assignment10.setCategory(CATEGORY_RESOURCE);
474 assignment10.setIssuer("");
476 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
477 configNameAttributeValue10.setDataType(STRING_DATATYPE);
478 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
479 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
481 advice.getAttributeAssignmentExpression().add(assignment10);
482 advices.getAdviceExpression().add(advice);
487 private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
490 JsonObject json = null;
491 if (jsonBody != null) {
493 //Read jsonBody to JsonObject
494 json = stringToJson(jsonBody);
496 JsonArray firewallRules = null;
497 JsonArray serviceGroup = null;
498 JsonArray addressGroup = null;
500 Connection con = null;
505 * Retrieve the property values for db access from the xacml.pap.properties
507 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
508 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
509 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
510 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
512 //insert data into tables
515 Class.forName(papDbDriver);
516 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
517 st = con.createStatement();
519 firewallRules = json.getJsonArray("firewallRuleList");
520 serviceGroup = json.getJsonArray("serviceGroups");
521 addressGroup = json.getJsonArray("addressGroups");
523 String insertQuery = null;
526 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
528 if (firewallRules != null) {
534 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;");
536 termID = rs.getInt("ID");
540 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;");
542 zoneID = rs.getInt("ID");
546 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;");
548 actionID = rs.getInt("ID");
551 for(int i = 0;i<firewallRules.size();i++) {
553 //increment ID Primary Keys
556 actionID = actionID + 1;
559 * Populate ArrayLists with values from the JSON
561 //create the JSON object from the JSON Array for each iteration through the for loop
562 JsonObject ruleListobj = firewallRules.getJsonObject(i);
564 //get values from JSON fields of firewallRulesList Array
565 String ruleName = ruleListobj.get("ruleName").toString();
566 String action = ruleListobj.get("action").toString();
567 String description = ruleListobj.get("description").toString();
569 rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";");
572 st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";");
576 //getting fromZone Array field from the firewallRulesList
577 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
578 String fromZoneString = null;
581 for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) {
582 String value = fromZoneArray.get(fromZoneIndex).toString();
583 value = value.replace("\"", "");
585 if (fromZoneString != null) {
586 fromZoneString = fromZoneString.concat(",").concat(value);
589 fromZoneString = value;
593 String fromZoneInsert = "'"+fromZoneString+"'";
595 //getting toZone Array field from the firewallRulesList
596 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
597 String toZoneString = null;
598 for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) {
599 String value = toZoneArray.get(toZoneIndex).toString();
600 value = value.replace("\"", "");
602 if (toZoneString != null) {
603 toZoneString = toZoneString.concat(",").concat(value);
606 toZoneString = value;
610 String toZoneInsert = "'"+toZoneString+"'";
612 //getting sourceList Array fields from the firewallRulesList
613 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
614 String srcListString = null;
615 for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) {
616 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
617 String type = srcListObj.get("type").toString().replace("\"", "");
620 if(type.equals("REFERENCE")||type.equals("GROUP")){
621 value = srcListObj.get("name").toString();
622 } else if (type.equalsIgnoreCase("ANY")){
625 value = srcListObj.get("value").toString();
629 value = value.replace("\"", "");
632 if (srcListString != null) {
633 srcListString = srcListString.concat(",").concat(value);
636 srcListString = value;
640 String srcListInsert = "'"+srcListString+"'";
642 //getting destinationList Array fields from the firewallRulesList
643 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
644 String destListString = null;
645 for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) {
646 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
647 String type = destListObj.get("type").toString().replace("\"", "");
650 if(type.equals("REFERENCE")||type.equals("GROUP")){
651 value = destListObj.get("name").toString();
652 } else if (type.equalsIgnoreCase("ANY")){
655 value = destListObj.get("value").toString();
659 value = value.replace("\"", "");
662 if (destListString != null) {
663 destListString = destListString.concat(",").concat(value);
665 destListString = value;
668 String destListInsert = "'"+destListString+"'";
670 //getting destServices Array fields from the firewallRulesList
671 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
672 String destPortListString = null;
673 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
674 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
675 String type = destServicesObj.get("type").toString().replace("\"", "");
678 if(type.equals("REFERENCE")||type.equals("GROUP")){
679 value = destServicesObj.get("name").toString();
680 } else if (type.equalsIgnoreCase("ANY")){
683 value = destServicesObj.get("value").toString();
687 value = value.replace("\"", "");
690 if (destPortListString != null) {
691 destPortListString = destPortListString.concat(",").concat(value);
693 destPortListString = value;
696 String destPortListInsert = "'"+destPortListString+"'";
699 * Create Queries to INSERT data into database tables and execute
701 String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST,"
702 + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+","
703 +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+","
704 +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); ";
705 termSql = termSql.replace('"', '\'');
706 st.addBatch(termSql);
708 String actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+"); ";
709 actionSql = actionSql.replace('"', '\'');
710 st.addBatch(actionSql);
718 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
720 if (serviceGroup != null) {
722 int serviceGroupID = 0;
723 int serviceListID = 0;
728 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;");
730 serviceGroupID = rs.getInt("ID");
734 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;");
736 serviceListID = rs.getInt("ID");
740 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;");
742 protocolID = rs.getInt("ID");
746 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;");
748 portID = rs.getInt("ID");
751 for(int i = 0; i < serviceGroup.size() ; i++) {
754 * Populate ArrayLists with values from the JSON
756 //create the JSON object from the JSON Array for each iteration through the for loop
757 JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
759 String serviceListName = svcGroupListobj.get("name").toString();
761 String description = null;
762 if (svcGroupListobj.containsKey("description")){
763 description = svcGroupListobj.get("description").toString();
766 //getting members Array from the serviceGroup
767 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
769 //String type = svcGroupListobj.get("type").toString();
770 Boolean isServiceGroup = false;
771 if (membersArray!=null){
772 String membersType = membersArray.getJsonObject(0).get("type").toString();
773 if (membersType.contains("REFERENCE")) {
774 isServiceGroup = true;
778 //Insert values into GROUPSERVICELIST table if name begins with Group
779 if (isServiceGroup) {
781 //increment ID Primary Keys
782 serviceListID = serviceListID + 1;
785 for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) {
786 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
787 //String value = membersObj.get("name").toString();
788 String type = membersObj.get("type").toString().replace("\"", "");
791 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
792 value = membersObj.get("name").toString();
793 } else if (type.equalsIgnoreCase("ANY")){
796 value = membersObj.get("value").toString();
800 value = value.replace("\"", "");
804 name = name.concat(",").concat(value);
809 String nameInsert = "'"+name+"'";
811 insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) "
812 + "VALUES("+serviceListID+","+serviceListName+","+nameInsert+")";
814 //Replace double quote with single quote
815 insertQuery = insertQuery.replace('"', '\'');
817 //Execute the queries to Insert data
818 st.executeUpdate(insertQuery);
820 } else { //Insert JSON data serviceList table, protollist table, and portlist table
822 //increment ID Primary Keys
823 protocolID = protocolID + 1;
825 serviceGroupID = serviceGroupID + 1;
827 String type = svcGroupListobj.get("type").toString();
828 String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
829 String ports = svcGroupListobj.get("ports").toString();
832 * Create Queries to INSERT data into database table and execute
834 String serviceSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) "
835 + "VALUES("+serviceGroupID+","+serviceListName+","+description+","+type+","
836 + transportProtocol+","+"null,"+ports+"); ";
837 serviceSql = serviceSql.replace('"', '\'');
838 st.addBatch(serviceSql);
840 String protSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); ";
841 protSql = protSql.replace('"', '\'');
842 st.addBatch(protSql);
844 String portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+");";
845 portSql = portSql.replace('"', '\'');
846 st.addBatch(portSql);
855 * Inserting addressGroup data into the ADDRESSGROUP table
857 if (addressGroup != null) {
861 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;");
863 prefixID = rs.getInt("ID");
867 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;");
869 addressID = rs.getInt("ID");
872 for(int i = 0; i < addressGroup.size(); i++) {
874 * Populate ArrayLists with values from the JSON
876 //create the JSON object from the JSON Array for each iteration through the for loop
877 JsonObject addressGroupObj = addressGroup.getJsonObject(i);
879 //create JSON array for members
880 JsonArray membersArray = addressGroupObj.getJsonArray("members");
881 String addressGroupName = addressGroupObj.get("name").toString();
883 String description = null;
884 if (addressGroupObj.containsKey("description")){
885 description = addressGroupObj.get("description").toString();
888 String prefixIP = null;
890 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
891 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
892 //String value = membersObj.get("value").toString();
893 type = membersObj.get("type").toString().replace("\"", "");
896 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
897 value = membersObj.get("name").toString();
898 } else if (type.equalsIgnoreCase("ANY")){
901 value = membersObj.get("value").toString();
905 value = value.replace("\"", "");
908 if (prefixIP != null) {
909 prefixIP = prefixIP.concat(",").concat(value);
914 String prefixList = "'"+prefixIP+"'";
916 Boolean isAddressGroup = type.contains("REFERENCE");
918 if (isAddressGroup) {
919 //increment ID Primary Keys
920 addressID = addressID + 1;
922 insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) "
923 + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")";
925 //increment ID Primary Key
926 prefixID = prefixID + 1;
928 insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) "
929 + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")";
934 //Replace double quote with single quote
935 insertQuery = insertQuery.replace('"', '\'');
937 //Execute the queries to Insert data
938 st.executeUpdate(insertQuery);
944 * Remove duplicate values from 'lookup' dictionary tables
947 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
948 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
949 st.addBatch(protoDelete);
952 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
953 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
954 st.addBatch(portListDelete);
957 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
958 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
959 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
960 st.addBatch(prefixListDelete);
963 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
964 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
965 + "groupservicelist.serviceList = g1.serviceList; ";
966 st.addBatch(groupServiceDelete);
970 } catch (ClassNotFoundException e) {
971 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries ");
972 System.out.println(e.getMessage());
975 } catch (SQLException e) {
976 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
977 System.out.println(e.getMessage());
979 } catch (Exception e) {
980 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
981 System.out.println(e.getMessage());
985 if (con!=null) con.close();
986 if (rs!=null) rs.close();
987 if (st!=null) st.close();
988 } catch (Exception ex){}
999 private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
1001 JsonObject oldJson = null;
1002 JsonObject newJson = null;
1004 if (jsonBody != null || prevJsonBody != null) {
1006 oldJson = stringToJson(prevJsonBody);
1007 newJson = stringToJson(jsonBody);
1009 //if no changes to the json then return true
1010 if (oldJson.equals(newJson)) {
1014 JsonArray firewallRules = null;
1015 JsonArray serviceGroup = null;
1016 JsonArray addressGroup = null;
1018 firewallRules = newJson.getJsonArray("firewallRuleList");
1019 serviceGroup = newJson.getJsonArray("serviceGroups");
1020 addressGroup = newJson.getJsonArray("addressGroups");
1022 Connection con = null;
1023 Statement st = null;
1024 ResultSet rs = null;
1027 * Retrieve the property values for db access from the xacml.pap.properties
1029 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
1030 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
1031 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
1032 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
1034 //insert data into tables
1038 Class.forName(papDbDriver);
1039 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
1040 st = con.createStatement();
1042 JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
1045 for (int i = 0; i<jsonDiff.size(); i++) {
1046 //String path = jsonDiff.get(i).asText();
1047 String jsonpatch = jsonDiff.get(i).toString();
1049 JsonObject patchObj = stringToJson(jsonpatch);
1051 String path = patchObj.get("path").toString().replace('"', ' ').trim();
1053 if (path.contains("firewallRuleList")) {
1058 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;");
1060 termID = rs.getInt("ID");
1064 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;");
1066 zoneID = rs.getInt("ID");
1070 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;");
1072 actionID = rs.getInt("ID");
1077 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
1079 for(int ri = 0; ri < firewallRules.size(); ri++) {
1081 //increment ID Primary Keys
1082 termID = termID + 1;
1083 zoneID = zoneID + 1;
1084 actionID = actionID + 1;
1087 * Populate ArrayLists with values from the JSON
1089 //create the JSON object from the JSON Array for each iteration through the for loop
1090 JsonObject ruleListobj = firewallRules.getJsonObject(ri);
1092 //get values from JSON fields of firewallRulesList Array
1093 String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
1094 String action = ruleListobj.get("action").toString().replace('"', '\'');
1095 String description = ruleListobj.get("description").toString().replace('"', '\'');
1097 rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";");
1100 st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";");
1104 //getting fromZone Array field from the firewallRulesList
1105 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
1106 String fromZoneString = null;
1108 for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) {
1109 String value = fromZoneArray.get(fromZoneIndex).toString();
1110 value = value.replace("\"", "");
1112 if (fromZoneString != null) {
1113 fromZoneString = fromZoneString.concat(",").concat(value);
1116 fromZoneString = value;
1120 String fromZoneInsert = "'"+fromZoneString+"'";
1122 //getting toZone Array field from the firewallRulesList
1123 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
1124 String toZoneString = null;
1127 for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
1128 String value = toZoneArray.get(toZoneIndex).toString();
1129 value = value.replace("\"", "");
1131 if (toZoneString != null) {
1132 toZoneString = toZoneString.concat(",").concat(value);
1135 toZoneString = value;
1139 String toZoneInsert = "'"+toZoneString+"'";
1140 //getting sourceList Array fields from the firewallRulesList
1141 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
1142 String srcListString = null;
1143 for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) {
1144 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
1145 String type = srcListObj.get("type").toString().replace("\"", "");
1147 String value = null;
1148 if(type.equals("REFERENCE")||type.equals("GROUP")){
1149 value = srcListObj.get("name").toString();
1150 } else if (type.equalsIgnoreCase("ANY")){
1153 value = srcListObj.get("value").toString();
1157 value = value.replace("\"", "");
1160 if (srcListString != null) {
1161 srcListString = srcListString.concat(",").concat(value);
1164 srcListString = value;
1168 String srcListInsert = "'"+srcListString+"'";
1170 //getting destinationList Array fields from the firewallRulesList
1171 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
1172 String destListString = null;
1173 for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) {
1174 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
1175 String type = destListObj.get("type").toString().replace("\"", "");
1177 String value = null;
1178 if(type.equals("REFERENCE")||type.equals("GROUP")){
1179 value = destListObj.get("name").toString();
1180 } else if (type.equalsIgnoreCase("ANY")){
1183 value = destListObj.get("value").toString();
1187 value = value.replace("\"", "");
1190 if (destListString != null) {
1191 destListString = destListString.concat(",").concat(value);
1193 destListString = value;
1196 String destListInsert = "'"+destListString+"'";
1198 //getting destServices Array fields from the firewallRulesList
1199 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
1200 String destPortListString = null;
1201 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
1202 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
1203 String type = destServicesObj.get("type").toString().replace("\"", "");
1205 String value = null;
1206 if(type.equals("REFERENCE")||type.equals("GROUP")){
1207 value = destServicesObj.get("name").toString();
1208 } else if (type.equalsIgnoreCase("ANY")){
1211 value = destServicesObj.get("value").toString();
1215 value = value.replace("\"", "");
1218 if (destPortListString != null) {
1219 destPortListString = destPortListString.concat(",").concat(value);
1221 destPortListString = value;
1224 String destPortListInsert = "'"+destPortListString+"'";
1227 * Create Queries to INSERT data into database tables and execute
1230 //Insert Into Terms table
1231 String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST,"
1232 + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+","
1233 +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+","
1234 +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); ";
1236 termSql = termSql.replace('"', '\'');
1237 st.addBatch(termSql);
1239 rs = st.executeQuery("SELECT * FROM ACTIONLIST WHERE ACTIONNAME = " + action + ";");
1241 String actionSql = null;
1245 actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+") ";
1246 actionSql = actionSql.replace('"', '\'');
1247 st.addBatch(actionSql);
1254 if (path.contains("serviceGroups")) {
1255 int serviceGroupID = 0;
1256 int serviceListID = 0;
1261 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;");
1263 serviceGroupID = rs.getInt("ID");
1267 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;");
1269 serviceListID = rs.getInt("ID");
1273 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;");
1275 protocolID = rs.getInt("ID");
1279 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;");
1281 portID = rs.getInt("ID");
1285 String insertQuery = null;
1288 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
1290 for(int si = 0; si < serviceGroup.size(); si++) {
1292 * Populate ArrayLists with values from the JSON
1294 //create the JSON object from the JSON Array for each iteration through the for loop
1295 JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
1297 String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');
1299 String description = null;
1300 if (svcGroupListobj.containsKey("description")){
1301 description = svcGroupListobj.get("description").toString().replace('"', '\'');
1304 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
1306 Boolean isServiceGroup = false;
1307 if (membersArray!=null){
1308 String membersType = membersArray.getJsonObject(0).get("type").toString();
1309 if (membersType.contains("REFERENCE")) {
1310 isServiceGroup = true;
1314 //Insert values into GROUPSERVICELIST table if name begins with Group
1315 if (isServiceGroup) {
1317 rs = st.executeQuery("SELECT * FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";");
1320 st.executeUpdate("DELETE FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";");
1323 //increment ID Primary Keys
1324 serviceListID = serviceListID + 1;
1326 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
1327 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1328 String type = membersObj.get("type").toString().replace("\"", "");
1330 String value = null;
1331 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1332 value = membersObj.get("name").toString();
1333 } else if (type.equalsIgnoreCase("ANY")){
1336 value = membersObj.get("value").toString();
1340 value = value.replace("\"", "");
1344 name = name.concat(",").concat(value);
1349 String nameInsert = "'"+name+"'";
1351 insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) "
1352 + "VALUES("+serviceListID+","+groupName+","+nameInsert+")";
1354 //Replace double quote with single quote
1355 insertQuery = insertQuery.replace('"', '\'');
1357 //Execute the queries to Insert data
1358 st.executeUpdate(insertQuery);
1360 } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
1362 //increment ID Primary Keys
1363 protocolID = protocolID + 1;
1364 portID = portID + 1;
1365 serviceGroupID = serviceGroupID + 1;
1367 String type = svcGroupListobj.get("type").toString().replace('"', '\'');
1368 String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
1369 String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
1371 rs = st.executeQuery("SELECT * FROM SERVICEGROUP WHERE NAME = "+ groupName + ";");
1374 st.executeUpdate("DELETE FROM SERVICEGROUP WHERE NAME = "+ groupName + ";");
1378 String svcGroupSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) "
1379 + "VALUES("+serviceGroupID+","+groupName+","+description+","+type+","
1380 + transportProtocol+","+"null,"+ports+"); ";
1381 svcGroupSql = svcGroupSql.replace('"', '\'');
1382 st.addBatch(svcGroupSql);
1384 rs = st.executeQuery("SELECT * FROM PROTOCOLLIST WHERE PROTOCOLNAME = " + transportProtocol + ";");
1386 String protoSql = null;
1390 protoSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) "
1391 + "VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); ";
1392 protoSql = protoSql.replace('"', '\'');
1393 st.addBatch(protoSql);
1398 rs = st.executeQuery("SELECT * FROM PORTLIST WHERE PORTNAME = " + ports + ";");
1400 String portSql = null;
1404 portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+"); ";
1405 portSql = portSql.replace('"', '\'');
1406 st.addBatch(portSql);
1414 if (path.contains("addressGroups")) {
1416 * Inserting addressGroup data into the ADDRESSGROUP table
1421 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;");
1423 prefixID = rs.getInt("ID");
1427 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;");
1429 addressID = rs.getInt("ID");
1433 String insertQuery = null;
1434 for(int ai=0; ai < addressGroup.size() ; ai++) {
1437 * Populate ArrayLists with values from the JSON
1439 //create the JSON object from the JSON Array for each iteration through the for loop
1440 JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
1442 //create JSON array for members
1443 JsonArray membersArray = addressGroupObj.getJsonArray("members");
1444 String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
1446 String description = null;
1447 if (addressGroupObj.containsKey("description")){
1448 description = addressGroupObj.get("description").toString().replace('"', '\'');
1451 String prefixIP = null;
1453 for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) {
1454 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1455 type = membersObj.get("type").toString().replace("\"", "");
1457 String value = null;
1458 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1459 value = membersObj.get("name").toString();
1460 } else if (type.equalsIgnoreCase("ANY")){
1463 value = membersObj.get("value").toString();
1467 value = value.replace("\"", "");
1470 if (prefixIP != null) {
1471 prefixIP = prefixIP.concat(",").concat(value);
1476 String prefixList = "'"+prefixIP+"'";
1478 Boolean isAddressGroup = type.contains("REFERENCE");
1480 if (isAddressGroup) {
1482 rs = st.executeQuery("SELECT * FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";");
1485 st.executeUpdate("DELETE FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";");
1488 //increment ID Primary Keys
1489 addressID = addressID + 1;
1491 insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) "
1492 + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")";
1498 rs = st.executeQuery("SELECT * FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";");
1501 st.executeUpdate("DELETE FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";");
1504 //increment ID Primary Key
1505 prefixID = prefixID + 1;
1507 insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) "
1508 + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")";
1511 //Replace double quote with single quote
1512 insertQuery = insertQuery.replace('"', '\'');
1514 //Execute the queries to Insert data
1515 st.executeUpdate(insertQuery);
1521 * Remove duplicate values from 'lookup' dictionary tables
1523 //ProtocolList Table
1524 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
1525 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
1526 st.addBatch(protoDelete);
1529 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
1530 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
1531 st.addBatch(portListDelete);
1534 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
1535 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
1536 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
1537 st.addBatch(prefixListDelete);
1540 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
1541 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
1542 + "groupservicelist.serviceList = g1.serviceList; ";
1543 st.addBatch(groupServiceDelete);
1547 } catch (ClassNotFoundException e) {
1548 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries");
1549 System.out.println(e.getMessage());
1552 } catch (SQLException e) {
1553 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1554 System.out.println(e.getMessage());
1558 if (con!=null) con.close();
1559 if (rs!=null) rs.close();
1560 if (st!=null) st.close();
1561 } catch (Exception ex){}
1571 private JsonObject stringToJson(String jsonString) {
1573 JsonObject json = null;
1574 if (jsonString != null) {
1576 //Read jsonBody to JsonObject
1577 StringReader in = null;
1579 in = new StringReader(jsonString);
1581 JsonReader jsonReader = Json.createReader(in);
1582 json = jsonReader.readObject();
1589 private JsonNode createPatch(String json, String oldJson) {
1590 JsonNode oldJason = null;
1591 JsonNode updatedJason = null;
1594 oldJason = JsonLoader.fromString(oldJson);
1595 updatedJason = JsonLoader.fromString(json);
1596 } catch (IOException e) {
1597 LOGGER.error("Exception Occured"+e);
1600 JsonPatch jsonPatch = JsonDiff.asJsonPatch(oldJason, updatedJason);
1601 JsonNode patchNode = JsonDiff.asJson(oldJason, updatedJason);
1602 System.out.println("Sending Patch:" + jsonPatch);
1608 public Object getCorrectPolicyDataObject() {
1609 return policyAdapter.getPolicyData();