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) {
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 String content = CONFIG_URL + "/Config/" + policyName + ".json";
378 AttributeValue.getContent().add(content);
379 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
380 advice.getAttributeAssignmentExpression().add(assignment2);
382 //Policy Name Assignment
383 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
384 assignment3.setAttributeId("PolicyName");
385 assignment3.setCategory(CATEGORY_RESOURCE);
386 assignment3.setIssuer("");
387 AttributeValueType attributeValue3 = new AttributeValueType();
388 attributeValue3.setDataType(STRING_DATATYPE);
389 fileName = FilenameUtils.removeExtension(fileName);
390 fileName = fileName + ".xml";
391 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
392 if ((name == null) || (name.equals(""))) {
393 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
395 attributeValue3.getContent().add(name);
396 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
397 advice.getAttributeAssignmentExpression().add(assignment3);
399 //Version Number Assignment
400 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
401 assignment4.setAttributeId("VersionNumber");
402 assignment4.setCategory(CATEGORY_RESOURCE);
403 assignment4.setIssuer("");
404 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
405 configNameAttributeValue4.setDataType(STRING_DATATYPE);
406 configNameAttributeValue4.getContent().add(Integer.toString(version));
407 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
408 advice.getAttributeAssignmentExpression().add(assignment4);
410 //Ecomp Name Assignment
411 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
412 assignment5.setAttributeId("matching:" + ECOMPID);
413 assignment5.setCategory(CATEGORY_RESOURCE);
414 assignment5.setIssuer("");
415 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
416 configNameAttributeValue5.setDataType(STRING_DATATYPE);
417 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
418 advice.getAttributeAssignmentExpression().add(assignment5);
420 //Config Name Assignment
421 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
422 assignment6.setAttributeId("matching:" + CONFIGID);
423 assignment6.setCategory(CATEGORY_RESOURCE);
424 assignment6.setIssuer("");
425 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
426 configNameAttributeValue6.setDataType(STRING_DATATYPE);
427 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
428 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
429 advice.getAttributeAssignmentExpression().add(assignment6);
432 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
433 assignment7.setAttributeId("RiskType");
434 assignment7.setCategory(CATEGORY_RESOURCE);
435 assignment7.setIssuer("");
437 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
438 configNameAttributeValue7.setDataType(STRING_DATATYPE);
439 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
440 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
442 advice.getAttributeAssignmentExpression().add(assignment7);
444 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
445 assignment8.setAttributeId("RiskLevel");
446 assignment8.setCategory(CATEGORY_RESOURCE);
447 assignment8.setIssuer("");
449 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
450 configNameAttributeValue8.setDataType(STRING_DATATYPE);
451 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
452 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
454 advice.getAttributeAssignmentExpression().add(assignment8);
456 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
457 assignment9.setAttributeId("guard");
458 assignment9.setCategory(CATEGORY_RESOURCE);
459 assignment9.setIssuer("");
461 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
462 configNameAttributeValue9.setDataType(STRING_DATATYPE);
463 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
464 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
466 advice.getAttributeAssignmentExpression().add(assignment9);
468 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
469 assignment10.setAttributeId("TTLDate");
470 assignment10.setCategory(CATEGORY_RESOURCE);
471 assignment10.setIssuer("");
473 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
474 configNameAttributeValue10.setDataType(STRING_DATATYPE);
475 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
476 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
478 advice.getAttributeAssignmentExpression().add(assignment10);
479 advices.getAdviceExpression().add(advice);
484 private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
487 JsonObject json = null;
488 if (jsonBody != null) {
490 //Read jsonBody to JsonObject
491 json = stringToJson(jsonBody);
493 JsonArray firewallRules = null;
494 JsonArray serviceGroup = null;
495 JsonArray addressGroup = null;
497 Connection con = null;
502 * Retrieve the property values for db access from the xacml.pap.properties
504 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
505 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
506 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
507 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
509 //insert data into tables
512 Class.forName(papDbDriver);
513 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
514 st = con.createStatement();
516 firewallRules = json.getJsonArray("firewallRuleList");
517 serviceGroup = json.getJsonArray("serviceGroups");
518 addressGroup = json.getJsonArray("addressGroups");
520 String insertQuery = null;
523 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
525 if (firewallRules != null) {
531 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;");
533 termID = rs.getInt("ID");
537 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;");
539 zoneID = rs.getInt("ID");
543 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;");
545 actionID = rs.getInt("ID");
548 for(int i = 0;i<firewallRules.size();i++) {
550 //increment ID Primary Keys
553 actionID = actionID + 1;
556 * Populate ArrayLists with values from the JSON
558 //create the JSON object from the JSON Array for each iteration through the for loop
559 JsonObject ruleListobj = firewallRules.getJsonObject(i);
561 //get values from JSON fields of firewallRulesList Array
562 String ruleName = ruleListobj.get("ruleName").toString();
563 String action = ruleListobj.get("action").toString();
564 String description = ruleListobj.get("description").toString();
566 rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";");
569 st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";");
573 //getting fromZone Array field from the firewallRulesList
574 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
575 String fromZoneString = null;
578 for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) {
579 String value = fromZoneArray.get(fromZoneIndex).toString();
580 value = value.replace("\"", "");
582 if (fromZoneString != null) {
583 fromZoneString = fromZoneString.concat(",").concat(value);
586 fromZoneString = value;
590 String fromZoneInsert = "'"+fromZoneString+"'";
592 //getting toZone Array field from the firewallRulesList
593 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
594 String toZoneString = null;
595 for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) {
596 String value = toZoneArray.get(toZoneIndex).toString();
597 value = value.replace("\"", "");
599 if (toZoneString != null) {
600 toZoneString = toZoneString.concat(",").concat(value);
603 toZoneString = value;
607 String toZoneInsert = "'"+toZoneString+"'";
609 //getting sourceList Array fields from the firewallRulesList
610 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
611 String srcListString = null;
612 for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) {
613 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
614 String type = srcListObj.get("type").toString().replace("\"", "");
617 if(type.equals("REFERENCE")||type.equals("GROUP")){
618 value = srcListObj.get("name").toString();
619 } else if (type.equalsIgnoreCase("ANY")){
622 value = srcListObj.get("value").toString();
626 value = value.replace("\"", "");
629 if (srcListString != null) {
630 srcListString = srcListString.concat(",").concat(value);
633 srcListString = value;
637 String srcListInsert = "'"+srcListString+"'";
639 //getting destinationList Array fields from the firewallRulesList
640 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
641 String destListString = null;
642 for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) {
643 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
644 String type = destListObj.get("type").toString().replace("\"", "");
647 if(type.equals("REFERENCE")||type.equals("GROUP")){
648 value = destListObj.get("name").toString();
649 } else if (type.equalsIgnoreCase("ANY")){
652 value = destListObj.get("value").toString();
656 value = value.replace("\"", "");
659 if (destListString != null) {
660 destListString = destListString.concat(",").concat(value);
662 destListString = value;
665 String destListInsert = "'"+destListString+"'";
667 //getting destServices Array fields from the firewallRulesList
668 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
669 String destPortListString = null;
670 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
671 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
672 String type = destServicesObj.get("type").toString().replace("\"", "");
675 if(type.equals("REFERENCE")||type.equals("GROUP")){
676 value = destServicesObj.get("name").toString();
677 } else if (type.equalsIgnoreCase("ANY")){
680 value = destServicesObj.get("value").toString();
684 value = value.replace("\"", "");
687 if (destPortListString != null) {
688 destPortListString = destPortListString.concat(",").concat(value);
690 destPortListString = value;
693 String destPortListInsert = "'"+destPortListString+"'";
696 * Create Queries to INSERT data into database tables and execute
698 String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST,"
699 + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+","
700 +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+","
701 +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); ";
702 termSql = termSql.replace('"', '\'');
703 st.addBatch(termSql);
705 String actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+"); ";
706 actionSql = actionSql.replace('"', '\'');
707 st.addBatch(actionSql);
715 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
717 if (serviceGroup != null) {
719 int serviceGroupID = 0;
720 int serviceListID = 0;
725 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;");
727 serviceGroupID = rs.getInt("ID");
731 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;");
733 serviceListID = rs.getInt("ID");
737 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;");
739 protocolID = rs.getInt("ID");
743 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;");
745 portID = rs.getInt("ID");
748 for(int i = 0; i < serviceGroup.size() ; i++) {
751 * Populate ArrayLists with values from the JSON
753 //create the JSON object from the JSON Array for each iteration through the for loop
754 JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
756 String serviceListName = svcGroupListobj.get("name").toString();
758 String description = null;
759 if (svcGroupListobj.containsKey("description")){
760 description = svcGroupListobj.get("description").toString();
763 //getting members Array from the serviceGroup
764 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
766 //String type = svcGroupListobj.get("type").toString();
767 Boolean isServiceGroup = false;
768 if (membersArray!=null){
769 String membersType = membersArray.getJsonObject(0).get("type").toString();
770 if (membersType.contains("REFERENCE")) {
771 isServiceGroup = true;
775 //Insert values into GROUPSERVICELIST table if name begins with Group
776 if (isServiceGroup) {
778 //increment ID Primary Keys
779 serviceListID = serviceListID + 1;
782 for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) {
783 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
784 //String value = membersObj.get("name").toString();
785 String type = membersObj.get("type").toString().replace("\"", "");
788 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
789 value = membersObj.get("name").toString();
790 } else if (type.equalsIgnoreCase("ANY")){
793 value = membersObj.get("value").toString();
797 value = value.replace("\"", "");
801 name = name.concat(",").concat(value);
806 String nameInsert = "'"+name+"'";
808 insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) "
809 + "VALUES("+serviceListID+","+serviceListName+","+nameInsert+")";
811 //Replace double quote with single quote
812 insertQuery = insertQuery.replace('"', '\'');
814 //Execute the queries to Insert data
815 st.executeUpdate(insertQuery);
817 } else { //Insert JSON data serviceList table, protollist table, and portlist table
819 //increment ID Primary Keys
820 protocolID = protocolID + 1;
822 serviceGroupID = serviceGroupID + 1;
824 String type = svcGroupListobj.get("type").toString();
825 String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
826 String ports = svcGroupListobj.get("ports").toString();
829 * Create Queries to INSERT data into database table and execute
831 String serviceSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) "
832 + "VALUES("+serviceGroupID+","+serviceListName+","+description+","+type+","
833 + transportProtocol+","+"null,"+ports+"); ";
834 serviceSql = serviceSql.replace('"', '\'');
835 st.addBatch(serviceSql);
837 String protSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); ";
838 protSql = protSql.replace('"', '\'');
839 st.addBatch(protSql);
841 String portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+");";
842 portSql = portSql.replace('"', '\'');
843 st.addBatch(portSql);
852 * Inserting addressGroup data into the ADDRESSGROUP table
854 if (addressGroup != null) {
858 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;");
860 prefixID = rs.getInt("ID");
864 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;");
866 addressID = rs.getInt("ID");
869 for(int i = 0; i < addressGroup.size(); i++) {
871 * Populate ArrayLists with values from the JSON
873 //create the JSON object from the JSON Array for each iteration through the for loop
874 JsonObject addressGroupObj = addressGroup.getJsonObject(i);
876 //create JSON array for members
877 JsonArray membersArray = addressGroupObj.getJsonArray("members");
878 String addressGroupName = addressGroupObj.get("name").toString();
880 String description = null;
881 if (addressGroupObj.containsKey("description")){
882 description = addressGroupObj.get("description").toString();
885 String prefixIP = null;
887 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
888 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
889 //String value = membersObj.get("value").toString();
890 type = membersObj.get("type").toString().replace("\"", "");
893 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
894 value = membersObj.get("name").toString();
895 } else if (type.equalsIgnoreCase("ANY")){
898 value = membersObj.get("value").toString();
902 value = value.replace("\"", "");
905 if (prefixIP != null) {
906 prefixIP = prefixIP.concat(",").concat(value);
911 String prefixList = "'"+prefixIP+"'";
913 Boolean isAddressGroup = type.contains("REFERENCE");
915 if (isAddressGroup) {
916 //increment ID Primary Keys
917 addressID = addressID + 1;
919 insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) "
920 + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")";
922 //increment ID Primary Key
923 prefixID = prefixID + 1;
925 insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) "
926 + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")";
931 //Replace double quote with single quote
932 insertQuery = insertQuery.replace('"', '\'');
934 //Execute the queries to Insert data
935 st.executeUpdate(insertQuery);
941 * Remove duplicate values from 'lookup' dictionary tables
944 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
945 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
946 st.addBatch(protoDelete);
949 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
950 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
951 st.addBatch(portListDelete);
954 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
955 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
956 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
957 st.addBatch(prefixListDelete);
960 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
961 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
962 + "groupservicelist.serviceList = g1.serviceList; ";
963 st.addBatch(groupServiceDelete);
967 } catch (ClassNotFoundException e) {
968 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries ");
969 System.out.println(e.getMessage());
972 } catch (SQLException e) {
973 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
974 System.out.println(e.getMessage());
976 } catch (Exception e) {
977 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
978 System.out.println(e.getMessage());
982 if (con!=null) con.close();
983 if (rs!=null) rs.close();
984 if (st!=null) st.close();
985 } catch (Exception ex){}
996 private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
998 JsonObject oldJson = null;
999 JsonObject newJson = null;
1001 if (jsonBody != null || prevJsonBody != null) {
1003 oldJson = stringToJson(prevJsonBody);
1004 newJson = stringToJson(jsonBody);
1006 //if no changes to the json then return true
1007 if (oldJson.equals(newJson)) {
1011 JsonArray firewallRules = null;
1012 JsonArray serviceGroup = null;
1013 JsonArray addressGroup = null;
1015 firewallRules = newJson.getJsonArray("firewallRuleList");
1016 serviceGroup = newJson.getJsonArray("serviceGroups");
1017 addressGroup = newJson.getJsonArray("addressGroups");
1019 Connection con = null;
1020 Statement st = null;
1021 ResultSet rs = null;
1024 * Retrieve the property values for db access from the xacml.pap.properties
1026 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
1027 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
1028 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
1029 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
1031 //insert data into tables
1035 Class.forName(papDbDriver);
1036 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
1037 st = con.createStatement();
1039 JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
1042 for (int i = 0; i<jsonDiff.size(); i++) {
1043 //String path = jsonDiff.get(i).asText();
1044 String jsonpatch = jsonDiff.get(i).toString();
1046 JsonObject patchObj = stringToJson(jsonpatch);
1048 String path = patchObj.get("path").toString().replace('"', ' ').trim();
1050 if (path.contains("firewallRuleList")) {
1055 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;");
1057 termID = rs.getInt("ID");
1061 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;");
1063 zoneID = rs.getInt("ID");
1067 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;");
1069 actionID = rs.getInt("ID");
1074 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
1076 for(int ri = 0; ri < firewallRules.size(); ri++) {
1078 //increment ID Primary Keys
1079 termID = termID + 1;
1080 zoneID = zoneID + 1;
1081 actionID = actionID + 1;
1084 * Populate ArrayLists with values from the JSON
1086 //create the JSON object from the JSON Array for each iteration through the for loop
1087 JsonObject ruleListobj = firewallRules.getJsonObject(ri);
1089 //get values from JSON fields of firewallRulesList Array
1090 String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
1091 String action = ruleListobj.get("action").toString().replace('"', '\'');
1092 String description = ruleListobj.get("description").toString().replace('"', '\'');
1094 rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";");
1097 st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";");
1101 //getting fromZone Array field from the firewallRulesList
1102 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
1103 String fromZoneString = null;
1105 for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) {
1106 String value = fromZoneArray.get(fromZoneIndex).toString();
1107 value = value.replace("\"", "");
1109 if (fromZoneString != null) {
1110 fromZoneString = fromZoneString.concat(",").concat(value);
1113 fromZoneString = value;
1117 String fromZoneInsert = "'"+fromZoneString+"'";
1119 //getting toZone Array field from the firewallRulesList
1120 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
1121 String toZoneString = null;
1124 for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
1125 String value = toZoneArray.get(toZoneIndex).toString();
1126 value = value.replace("\"", "");
1128 if (toZoneString != null) {
1129 toZoneString = toZoneString.concat(",").concat(value);
1132 toZoneString = value;
1136 String toZoneInsert = "'"+toZoneString+"'";
1137 //getting sourceList Array fields from the firewallRulesList
1138 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
1139 String srcListString = null;
1140 for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) {
1141 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
1142 String type = srcListObj.get("type").toString().replace("\"", "");
1144 String value = null;
1145 if(type.equals("REFERENCE")||type.equals("GROUP")){
1146 value = srcListObj.get("name").toString();
1147 } else if (type.equalsIgnoreCase("ANY")){
1150 value = srcListObj.get("value").toString();
1154 value = value.replace("\"", "");
1157 if (srcListString != null) {
1158 srcListString = srcListString.concat(",").concat(value);
1161 srcListString = value;
1165 String srcListInsert = "'"+srcListString+"'";
1167 //getting destinationList Array fields from the firewallRulesList
1168 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
1169 String destListString = null;
1170 for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) {
1171 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
1172 String type = destListObj.get("type").toString().replace("\"", "");
1174 String value = null;
1175 if(type.equals("REFERENCE")||type.equals("GROUP")){
1176 value = destListObj.get("name").toString();
1177 } else if (type.equalsIgnoreCase("ANY")){
1180 value = destListObj.get("value").toString();
1184 value = value.replace("\"", "");
1187 if (destListString != null) {
1188 destListString = destListString.concat(",").concat(value);
1190 destListString = value;
1193 String destListInsert = "'"+destListString+"'";
1195 //getting destServices Array fields from the firewallRulesList
1196 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
1197 String destPortListString = null;
1198 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
1199 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
1200 String type = destServicesObj.get("type").toString().replace("\"", "");
1202 String value = null;
1203 if(type.equals("REFERENCE")||type.equals("GROUP")){
1204 value = destServicesObj.get("name").toString();
1205 } else if (type.equalsIgnoreCase("ANY")){
1208 value = destServicesObj.get("value").toString();
1212 value = value.replace("\"", "");
1215 if (destPortListString != null) {
1216 destPortListString = destPortListString.concat(",").concat(value);
1218 destPortListString = value;
1221 String destPortListInsert = "'"+destPortListString+"'";
1224 * Create Queries to INSERT data into database tables and execute
1227 //Insert Into Terms table
1228 String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST,"
1229 + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+","
1230 +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+","
1231 +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); ";
1233 termSql = termSql.replace('"', '\'');
1234 st.addBatch(termSql);
1236 rs = st.executeQuery("SELECT * FROM ACTIONLIST WHERE ACTIONNAME = " + action + ";");
1238 String actionSql = null;
1242 actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+") ";
1243 actionSql = actionSql.replace('"', '\'');
1244 st.addBatch(actionSql);
1251 if (path.contains("serviceGroups")) {
1252 int serviceGroupID = 0;
1253 int serviceListID = 0;
1258 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;");
1260 serviceGroupID = rs.getInt("ID");
1264 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;");
1266 serviceListID = rs.getInt("ID");
1270 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;");
1272 protocolID = rs.getInt("ID");
1276 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;");
1278 portID = rs.getInt("ID");
1282 String insertQuery = null;
1285 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
1287 for(int si = 0; si < serviceGroup.size(); si++) {
1289 * Populate ArrayLists with values from the JSON
1291 //create the JSON object from the JSON Array for each iteration through the for loop
1292 JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
1294 String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');
1296 String description = null;
1297 if (svcGroupListobj.containsKey("description")){
1298 description = svcGroupListobj.get("description").toString().replace('"', '\'');
1301 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
1303 Boolean isServiceGroup = false;
1304 if (membersArray!=null){
1305 String membersType = membersArray.getJsonObject(0).get("type").toString();
1306 if (membersType.contains("REFERENCE")) {
1307 isServiceGroup = true;
1311 //Insert values into GROUPSERVICELIST table if name begins with Group
1312 if (isServiceGroup) {
1314 rs = st.executeQuery("SELECT * FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";");
1317 st.executeUpdate("DELETE FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";");
1320 //increment ID Primary Keys
1321 serviceListID = serviceListID + 1;
1323 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
1324 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1325 String type = membersObj.get("type").toString().replace("\"", "");
1327 String value = null;
1328 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1329 value = membersObj.get("name").toString();
1330 } else if (type.equalsIgnoreCase("ANY")){
1333 value = membersObj.get("value").toString();
1337 value = value.replace("\"", "");
1341 name = name.concat(",").concat(value);
1346 String nameInsert = "'"+name+"'";
1348 insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) "
1349 + "VALUES("+serviceListID+","+groupName+","+nameInsert+")";
1351 //Replace double quote with single quote
1352 insertQuery = insertQuery.replace('"', '\'');
1354 //Execute the queries to Insert data
1355 st.executeUpdate(insertQuery);
1357 } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
1359 //increment ID Primary Keys
1360 protocolID = protocolID + 1;
1361 portID = portID + 1;
1362 serviceGroupID = serviceGroupID + 1;
1364 String type = svcGroupListobj.get("type").toString().replace('"', '\'');
1365 String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
1366 String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
1368 rs = st.executeQuery("SELECT * FROM SERVICEGROUP WHERE NAME = "+ groupName + ";");
1371 st.executeUpdate("DELETE FROM SERVICEGROUP WHERE NAME = "+ groupName + ";");
1375 String svcGroupSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) "
1376 + "VALUES("+serviceGroupID+","+groupName+","+description+","+type+","
1377 + transportProtocol+","+"null,"+ports+"); ";
1378 svcGroupSql = svcGroupSql.replace('"', '\'');
1379 st.addBatch(svcGroupSql);
1381 rs = st.executeQuery("SELECT * FROM PROTOCOLLIST WHERE PROTOCOLNAME = " + transportProtocol + ";");
1383 String protoSql = null;
1387 protoSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) "
1388 + "VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); ";
1389 protoSql = protoSql.replace('"', '\'');
1390 st.addBatch(protoSql);
1395 rs = st.executeQuery("SELECT * FROM PORTLIST WHERE PORTNAME = " + ports + ";");
1397 String portSql = null;
1401 portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+"); ";
1402 portSql = portSql.replace('"', '\'');
1403 st.addBatch(portSql);
1411 if (path.contains("addressGroups")) {
1413 * Inserting addressGroup data into the ADDRESSGROUP table
1418 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;");
1420 prefixID = rs.getInt("ID");
1424 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;");
1426 addressID = rs.getInt("ID");
1430 String insertQuery = null;
1431 for(int ai=0; ai < addressGroup.size() ; ai++) {
1434 * Populate ArrayLists with values from the JSON
1436 //create the JSON object from the JSON Array for each iteration through the for loop
1437 JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
1439 //create JSON array for members
1440 JsonArray membersArray = addressGroupObj.getJsonArray("members");
1441 String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
1443 String description = null;
1444 if (addressGroupObj.containsKey("description")){
1445 description = addressGroupObj.get("description").toString().replace('"', '\'');
1448 String prefixIP = null;
1450 for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) {
1451 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1452 type = membersObj.get("type").toString().replace("\"", "");
1454 String value = null;
1455 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1456 value = membersObj.get("name").toString();
1457 } else if (type.equalsIgnoreCase("ANY")){
1460 value = membersObj.get("value").toString();
1464 value = value.replace("\"", "");
1467 if (prefixIP != null) {
1468 prefixIP = prefixIP.concat(",").concat(value);
1473 String prefixList = "'"+prefixIP+"'";
1475 Boolean isAddressGroup = type.contains("REFERENCE");
1477 if (isAddressGroup) {
1479 rs = st.executeQuery("SELECT * FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";");
1482 st.executeUpdate("DELETE FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";");
1485 //increment ID Primary Keys
1486 addressID = addressID + 1;
1488 insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) "
1489 + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")";
1495 rs = st.executeQuery("SELECT * FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";");
1498 st.executeUpdate("DELETE FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";");
1501 //increment ID Primary Key
1502 prefixID = prefixID + 1;
1504 insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) "
1505 + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")";
1508 //Replace double quote with single quote
1509 insertQuery = insertQuery.replace('"', '\'');
1511 //Execute the queries to Insert data
1512 st.executeUpdate(insertQuery);
1518 * Remove duplicate values from 'lookup' dictionary tables
1520 //ProtocolList Table
1521 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
1522 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
1523 st.addBatch(protoDelete);
1526 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
1527 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
1528 st.addBatch(portListDelete);
1531 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
1532 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
1533 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
1534 st.addBatch(prefixListDelete);
1537 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
1538 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
1539 + "groupservicelist.serviceList = g1.serviceList; ";
1540 st.addBatch(groupServiceDelete);
1544 } catch (ClassNotFoundException e) {
1545 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries");
1546 System.out.println(e.getMessage());
1549 } catch (SQLException e) {
1550 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1551 System.out.println(e.getMessage());
1555 if (con!=null) con.close();
1556 if (rs!=null) rs.close();
1557 if (st!=null) st.close();
1558 } catch (Exception ex){}
1568 private JsonObject stringToJson(String jsonString) {
1570 JsonObject json = null;
1571 if (jsonString != null) {
1573 //Read jsonBody to JsonObject
1574 StringReader in = null;
1576 in = new StringReader(jsonString);
1578 JsonReader jsonReader = Json.createReader(in);
1579 json = jsonReader.readObject();
1586 private JsonNode createPatch(String json, String oldJson) {
1587 JsonNode oldJason = null;
1588 JsonNode updatedJason = null;
1591 oldJason = JsonLoader.fromString(oldJson);
1592 updatedJason = JsonLoader.fromString(json);
1593 } catch (IOException e) {
1594 e.printStackTrace();
1597 JsonPatch jsonPatch = JsonDiff.asJsonPatch(oldJason, updatedJason);
1598 JsonNode patchNode = JsonDiff.asJson(oldJason, updatedJason);
1599 System.out.println("Sending Patch:" + jsonPatch);
1605 public Object getCorrectPolicyDataObject() {
1606 return policyAdapter.getPolicyData();