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.charset.StandardCharsets;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.sql.Connection;
36 import java.sql.DriverManager;
37 import java.sql.ResultSet;
38 import java.sql.SQLException;
39 import java.sql.Statement;
40 import java.util.HashMap;
42 import java.util.StringTokenizer;
44 import javax.json.Json;
45 import javax.json.JsonArray;
46 import javax.json.JsonException;
47 import javax.json.JsonObject;
48 import javax.json.JsonReader;
49 import javax.json.JsonString;
50 import javax.json.JsonValue;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
66 import org.apache.commons.io.FilenameUtils;
67 import org.apache.commons.logging.Log;
68 import org.apache.commons.logging.LogFactory;
69 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
70 import org.openecomp.policy.rest.XACMLRestProperties;
71 import org.openecomp.policy.common.logging.eelf.MessageCodes;
72 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
74 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
75 import com.att.research.xacml.std.IdentifierImpl;
76 import com.att.research.xacml.util.XACMLProperties;
77 import com.fasterxml.jackson.databind.JsonNode;
78 import com.github.fge.jackson.JsonLoader;
79 import com.github.fge.jsonpatch.JsonPatch;
80 import com.github.fge.jsonpatch.diff.JsonDiff;
81 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
82 import org.openecomp.policy.common.logging.flexlogger.Logger;
84 public class FirewallConfigPolicy extends Policy {
88 private static final Logger logger = FlexLogger.getLogger(FirewallConfigPolicy.class);
90 public static final String JSON_CONFIG = "JSON";
91 public static final String XML_CONFIG = "XML";
92 public static final String PROPERTIES_CONFIG = "PROPERTIES";
93 public static final String OTHER_CONFIG = "OTHER";
96 * These are the parameters needed for DB access from the PAP
98 private static String papDbDriver = null;
99 private static String papDbUrl = null;
100 private static String papDbUser = null;
101 private static String papDbPassword = null;
103 public FirewallConfigPolicy() {
107 public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) {
108 this.policyAdapter = policyAdapter;
109 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
113 // Saving the Configurations file at server location for config policy.
114 protected void saveConfigurations(String policyName, String prevPolicyName, String jsonBody) {
115 final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
116 String policyDir = policyAdapter.getParentPath().toString();
117 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
118 policyDir = policyDir.substring(startIndex, policyDir.length());
119 logger.info("print the main domain value"+policyDir);
120 String path = policyDir.replace('\\', '.');
121 if(path.contains("/")){
122 path = policyDir.replace('/', '.');
123 logger.info("print the path:" +path);
127 String configFileName = getConfigFile(policyName);
130 if(CONFIG_HOME.contains("\\"))
132 file = new File(CONFIG_HOME + "\\" + path + "."+ configFileName);
136 file = new File(CONFIG_HOME + "/" + path + "."+ configFileName);
139 // if file doesnt exists, then create it
140 if (!file.exists()) {
141 file.createNewFile();
144 //Getting the previous policy Config Json file to be used for updating the dictionary tables
145 if (policyAdapter.isEditPolicy()) {
147 String prevConfigFileName = getConfigFile(prevPolicyName);
150 if(CONFIG_HOME.contains("\\"))
152 oldFile = new File(CONFIG_HOME + "\\" + path + "."+ prevConfigFileName);
156 oldFile = new File(CONFIG_HOME + "/" + path + "."+ prevConfigFileName);
159 String filepath = oldFile.toString();
161 String prevJsonBody = readFile(filepath, StandardCharsets.UTF_8);
162 policyAdapter.setPrevJsonBody(prevJsonBody);
166 File configHomeDir = new File(CONFIG_HOME);
167 File[] listOfFiles = configHomeDir.listFiles();
168 if (listOfFiles != null){
169 for(File eachFile : listOfFiles){
170 if(eachFile.isFile()){
171 String fileNameWithoutExtension = FilenameUtils.removeExtension(eachFile.getName());
172 String configFileNameWithoutExtension = FilenameUtils.removeExtension(configFileName);
173 if (fileNameWithoutExtension.equals(configFileNameWithoutExtension)){
181 FileWriter fw = new FileWriter(file.getAbsoluteFile());
182 BufferedWriter bw = new BufferedWriter(fw);
185 if (logger.isDebugEnabled()) {
186 logger.debug("Configuration is succesfully saved");
188 } catch (IOException e) {
193 //Utility to read json data from the existing file to a string
194 static String readFile(String path, Charset encoding) throws IOException {
196 byte[] encoded = Files.readAllBytes(Paths.get(path));
197 return new String(encoded, encoding);
201 // Here we are adding the extension for the configurations file based on the
202 // config type selection for saving.
203 private String getConfigFile(String filename) {
204 filename = FilenameUtils.removeExtension(filename);
205 if (filename.endsWith(".json")) {
206 filename = filename.substring(0, filename.length() - 4);
209 filename=filename+".json";
214 // Validations for Config form
215 public boolean validateConfigForm() {
217 // Validating mandatory Fields.
224 public Map<String, String> savePolicies() throws Exception {
226 Map<String, String> successMap = new HashMap<String,String>();
227 if(isPolicyExists()){
228 successMap.put("EXISTS", "This Policy already exist on the PAP");
232 if(!isPreparedToSave()){
236 // Until here we prepared the data and here calling the method to create xml.
237 Path newPolicyPath = null;
238 newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(), policyName);
239 Boolean dbIsUpdated = false;
240 if (policyAdapter.getApiflag().equalsIgnoreCase("admin")){
243 if (policyAdapter.isEditPolicy()) {
244 dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
246 dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
251 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() );
253 //TODO:EELF Cleanup - Remove logger
254 //logger.error("Failed to Update the Database Dictionary Tables.");
255 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
257 //remove the new json file
258 String jsonBody = policyAdapter.getPrevJsonBody();
260 saveConfigurations(policyName, "", jsonBody);
262 saveConfigurations(policyName, "", "");
264 successMap.put("fwdberror", "DB UPDATE");
267 if (successMap.containsKey("success")) {
268 Path finalPolicyPath = getFinalPolicyPath();
269 policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
274 //This is the method for preparing the policy for saving. We have broken it out
275 //separately because the fully configured policy is used for multiple things
277 public boolean prepareToSave() throws Exception{
279 if(isPreparedToSave()){
280 //we have already done this
285 String policyID = policyAdapter.getPolicyID();
287 if (policyAdapter.isEditPolicy()) {
288 version = policyAdapter.getHighestVersion() + 1;
293 // Create the Instance for pojo, PolicyType object is used in marshalling.
294 if (policyAdapter.getPolicyType().equals("Config")) {
295 PolicyType policyConfig = new PolicyType();
297 policyConfig.setVersion(Integer.toString(version));
298 policyConfig.setPolicyId(policyID);
299 policyConfig.setTarget(new TargetType());
300 policyAdapter.setData(policyConfig);
303 if (policyAdapter.getData() != null) {
305 // Save off everything
306 // making ready all the required elements to generate the action policy xml.
307 // Get the uniqueness for policy name.
308 String prevPolicyName = null;
309 if(policyAdapter.isEditPolicy()){
310 prevPolicyName = "Config_FW_" + policyAdapter.getPolicyName() + "." + policyAdapter.getHighestVersion() + ".xml";
313 Path newFile = getNextFilename(Paths.get(policyAdapter.getParentPath().toString()),
314 (policyAdapter.getPolicyType() + "_FW"), policyAdapter.getPolicyName(), version);
316 if (newFile == null) {
317 //TODO:EELF Cleanup - Remove logger
318 //logger.error("Policy already Exists, cannot create the policy.");
319 PolicyLogger.error("Policy already Exists, cannot create the policy.");
320 setPolicyExists(true);
323 policyName = newFile.getFileName().toString();
325 String jsonBody = policyAdapter.getJsonBody();
326 saveConfigurations(policyName, prevPolicyName, jsonBody);
328 // Make sure the filename ends with an extension
329 if (policyName.endsWith(".xml") == false) {
330 policyName = policyName + ".xml";
333 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
335 configPolicy.setDescription(policyAdapter.getPolicyDescription());
337 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
339 AllOfType allOfOne = new AllOfType();
340 File policyFilePath = new File(policyAdapter.getParentPath().toString(), policyName);
341 String policyDir = policyFilePath.getParentFile().getName();
342 String fileName = FilenameUtils.removeExtension(policyName);
343 fileName = policyDir + "." + fileName + ".xml";
344 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
345 if ((name == null) || (name.equals(""))) {
346 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
348 allOfOne.getMatch().add(createMatch("PolicyName", name));
349 AllOfType allOf = new AllOfType();
351 // Match for ConfigName
352 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
353 // Match for riskType
354 allOf.getMatch().add(
355 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
356 // Match for riskLevel
357 allOf.getMatch().add(
358 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
359 // Match for riskguard
360 allOf.getMatch().add(
361 createDynamicMatch("guard", policyAdapter.getGuard()));
363 allOf.getMatch().add(
364 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
365 AnyOfType anyOf = new AnyOfType();
366 anyOf.getAllOf().add(allOfOne);
367 anyOf.getAllOf().add(allOf);
369 TargetType target = new TargetType();
370 ((TargetType) target).getAnyOf().add(anyOf);
372 // Adding the target to the policy element
373 configPolicy.setTarget((TargetType) target);
375 RuleType rule = new RuleType();
376 rule.setRuleId(policyAdapter.getRuleID());
378 rule.setEffect(EffectType.PERMIT);
380 // Create Target in Rule
381 AllOfType allOfInRule = new AllOfType();
383 // Creating match for ACCESS in rule target
384 MatchType accessMatch = new MatchType();
385 AttributeValueType accessAttributeValue = new AttributeValueType();
386 accessAttributeValue.setDataType(STRING_DATATYPE);
387 accessAttributeValue.getContent().add("ACCESS");
388 accessMatch.setAttributeValue(accessAttributeValue);
389 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
390 URI accessURI = null;
392 accessURI = new URI(ACTION_ID);
393 } catch (URISyntaxException e) {
394 //TODO:EELF Cleanup - Remove logger
395 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
396 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
398 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
399 accessAttributeDesignator.setDataType(STRING_DATATYPE);
400 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
401 accessMatch.setAttributeDesignator(accessAttributeDesignator);
402 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
404 // Creating Config Match in rule Target
405 MatchType configMatch = new MatchType();
406 AttributeValueType configAttributeValue = new AttributeValueType();
407 configAttributeValue.setDataType(STRING_DATATYPE);
409 configAttributeValue.getContent().add("Config");
411 configMatch.setAttributeValue(configAttributeValue);
412 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
413 URI configURI = null;
415 configURI = new URI(RESOURCE_ID);
416 } catch (URISyntaxException e) {
417 //TODO:EELF Cleanup - Remove logger
418 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
419 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
422 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
423 configAttributeDesignator.setDataType(STRING_DATATYPE);
424 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
425 configMatch.setAttributeDesignator(configAttributeDesignator);
426 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
428 allOfInRule.getMatch().add(accessMatch);
429 allOfInRule.getMatch().add(configMatch);
431 AnyOfType anyOfInRule = new AnyOfType();
432 anyOfInRule.getAllOf().add(allOfInRule);
434 TargetType targetInRule = new TargetType();
435 targetInRule.getAnyOf().add(anyOfInRule);
437 rule.setTarget(targetInRule);
438 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
440 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
441 policyAdapter.setPolicyData(configPolicy);
444 //TODO:EELF Cleanup - Remove logger
445 //logger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
446 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
448 setPreparedToSave(true);
452 // Data required for Advice part is setting here.
453 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
455 //Firewall Config ID Assignment
456 AdviceExpressionsType advices = new AdviceExpressionsType();
457 AdviceExpressionType advice = new AdviceExpressionType();
458 advice.setAdviceId("firewallConfigID");
459 advice.setAppliesTo(EffectType.PERMIT);
461 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
462 assignment1.setAttributeId("type");
463 assignment1.setCategory(CATEGORY_RESOURCE);
464 assignment1.setIssuer("");
465 AttributeValueType configNameAttributeValue = new AttributeValueType();
466 configNameAttributeValue.setDataType(STRING_DATATYPE);
467 configNameAttributeValue.getContent().add("Configuration");
468 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
469 advice.getAttributeAssignmentExpression().add(assignment1);
471 // For Config file Url if configurations are provided.
473 final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
474 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
475 assignment2.setAttributeId("URLID");
476 assignment2.setCategory(CATEGORY_RESOURCE);
477 assignment2.setIssuer("");
478 AttributeValueType AttributeValue = new AttributeValueType();
479 AttributeValue.setDataType(URI_DATATYPE);
480 String policyDir1 = policyAdapter.getParentPath().toString();
481 int startIndex1 = policyDir1.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
482 policyDir1 = policyDir1.substring(startIndex1, policyDir1.length());
483 logger.info("print the main domain value"+policyDir1);
484 String path = policyDir1.replace('\\', '.');
485 if(path.contains("/")){
486 path = policyDir1.replace('/', '.');
487 logger.info("print the path:" +path);
489 String content = CONFIG_URL + "/Config/" + path + "." + getConfigFile(policyName);
491 AttributeValue.getContent().add(content);
492 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
493 advice.getAttributeAssignmentExpression().add(assignment2);
495 //Policy Name Assignment
496 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
497 assignment3.setAttributeId("PolicyName");
498 assignment3.setCategory(CATEGORY_RESOURCE);
499 assignment3.setIssuer("");
500 AttributeValueType attributeValue3 = new AttributeValueType();
501 attributeValue3.setDataType(STRING_DATATYPE);
502 String policyDir = policyAdapter.getParentPath().toString();
503 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
504 policyDir = policyDir.substring(startIndex, policyDir.length());
505 StringTokenizer tokenizer = null;
506 StringBuffer buffer = new StringBuffer();
507 if (policyDir.contains("\\")) {
508 tokenizer = new StringTokenizer(policyDir, "\\");
510 tokenizer = new StringTokenizer(policyDir, "/");
512 if (tokenizer != null) {
513 while (tokenizer.hasMoreElements()) {
514 String value = tokenizer.nextToken();
515 buffer.append(value);
519 fileName = FilenameUtils.removeExtension(fileName);
520 fileName = buffer.toString() + fileName + ".xml";
521 System.out.println(fileName);
522 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
523 if ((name == null) || (name.equals(""))) {
524 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
526 System.out.println(name);
527 attributeValue3.getContent().add(name);
528 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
529 advice.getAttributeAssignmentExpression().add(assignment3);
531 //Version Number Assignment
532 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
533 assignment4.setAttributeId("VersionNumber");
534 assignment4.setCategory(CATEGORY_RESOURCE);
535 assignment4.setIssuer("");
536 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
537 configNameAttributeValue4.setDataType(STRING_DATATYPE);
538 configNameAttributeValue4.getContent().add(Integer.toString(version));
539 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
540 advice.getAttributeAssignmentExpression().add(assignment4);
542 //Ecomp Name Assignment
543 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
544 assignment5.setAttributeId("matching:" + this.ECOMPID);
545 assignment5.setCategory(CATEGORY_RESOURCE);
546 assignment5.setIssuer("");
547 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
548 configNameAttributeValue5.setDataType(STRING_DATATYPE);
549 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
550 advice.getAttributeAssignmentExpression().add(assignment5);
552 //Config Name Assignment
553 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
554 assignment6.setAttributeId("matching:" + this.CONFIGID);
555 assignment6.setCategory(CATEGORY_RESOURCE);
556 assignment6.setIssuer("");
557 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
558 configNameAttributeValue6.setDataType(STRING_DATATYPE);
559 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
560 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
561 advice.getAttributeAssignmentExpression().add(assignment6);
564 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
565 assignment7.setAttributeId("RiskType");
566 assignment7.setCategory(CATEGORY_RESOURCE);
567 assignment7.setIssuer("");
569 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
570 configNameAttributeValue7.setDataType(STRING_DATATYPE);
571 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
572 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
574 advice.getAttributeAssignmentExpression().add(assignment7);
576 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
577 assignment8.setAttributeId("RiskLevel");
578 assignment8.setCategory(CATEGORY_RESOURCE);
579 assignment8.setIssuer("");
581 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
582 configNameAttributeValue8.setDataType(STRING_DATATYPE);
583 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
584 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
586 advice.getAttributeAssignmentExpression().add(assignment8);
588 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
589 assignment9.setAttributeId("guard");
590 assignment9.setCategory(CATEGORY_RESOURCE);
591 assignment9.setIssuer("");
593 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
594 configNameAttributeValue9.setDataType(STRING_DATATYPE);
595 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
596 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
598 advice.getAttributeAssignmentExpression().add(assignment9);
600 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
601 assignment10.setAttributeId("TTLDate");
602 assignment10.setCategory(CATEGORY_RESOURCE);
603 assignment10.setIssuer("");
605 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
606 configNameAttributeValue10.setDataType(STRING_DATATYPE);
607 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
608 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
610 advice.getAttributeAssignmentExpression().add(assignment10);
614 advices.getAdviceExpression().add(advice);
619 private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
622 JsonObject json = null;
623 if (jsonBody != null) {
625 //Read jsonBody to JsonObject
626 json = stringToJson(jsonBody);
628 JsonArray firewallRules = null;
629 JsonArray serviceGroup = null;
630 JsonArray addressGroup = null;
631 String securityZone=null;
633 Connection con = null;
638 * Retrieve the property values for db access from the xacml.pap.properties
640 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
641 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
642 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
643 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
645 //insert data into tables
648 Class.forName(papDbDriver);
649 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
650 st = con.createStatement();
652 firewallRules = json.getJsonArray("firewallRuleList");
653 serviceGroup = json.getJsonArray("serviceGroups");
654 addressGroup = json.getJsonArray("addressGroups");
655 securityZone=json.getString("primaryParentZoneId").toString();
657 logger.info("Parent child: securityZone from JSON: "+securityZone);
658 String insertQuery = null;
660 //Inserting childPolicy and its parent to the FWChildToParent DB table
661 if(securityZone!=null){
662 //Its a child Policy.
663 //Retrieve the parent name from the securityZone Id
664 String retrieveParentQuery= "select parent from fwparent where securityZone='";
666 retrieveParentQuery=retrieveParentQuery+securityZone+"';";
667 logger.info("Parent child: Query to retrieve parent "+retrieveParentQuery);
668 rs = st.executeQuery(retrieveParentQuery);
672 parent = rs.getString("parent");
677 String insertQueryChildTable="INSERT INTO FWChildToParent(child, parent) VALUES ('";
678 insertQueryChildTable=insertQueryChildTable+policyAdapter.getPolicyName()+"','"+parent+"');";
679 logger.info("Parent child: Insert child and parent to DB: "+insertQueryChildTable);
680 st.executeUpdate(insertQueryChildTable);
685 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
687 if (firewallRules != null) {
693 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;");
695 termID = rs.getInt("ID");
699 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;");
701 zoneID = rs.getInt("ID");
705 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;");
707 actionID = rs.getInt("ID");
712 for(JsonValue jsonValue : firewallRules) {
714 //increment ID Primary Keys
717 actionID = actionID + 1;
720 * Populate ArrayLists with values from the JSON
722 //create the JSON object from the JSON Array for each iteration through the for loop
723 JsonObject ruleListobj = firewallRules.getJsonObject(i);
725 //get values from JSON fields of firewallRulesList Array
726 String ruleName = ruleListobj.get("ruleName").toString();
727 String action = ruleListobj.get("action").toString();
728 String description = ruleListobj.get("description").toString();
730 rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";");
733 st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";");
737 //getting fromZone Array field from the firewallRulesList
738 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
739 String fromZoneString = null;
741 int fromZoneIndex = 0;
742 for (JsonValue fromZoneJsonValue : fromZoneArray) {
743 String value = fromZoneArray.get(fromZoneIndex).toString();
744 value = value.replace("\"", "");
746 if (fromZoneString != null) {
747 fromZoneString = fromZoneString.concat(",").concat(value);
750 fromZoneString = value;
756 String fromZoneInsert = "'"+fromZoneString+"'";
758 //getting toZone Array field from the firewallRulesList
759 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
760 String toZoneString = null;
763 for (JsonValue toZoneJsonValue : toZoneArray) {
764 String value = toZoneArray.get(toZoneIndex).toString();
765 value = value.replace("\"", "");
767 if (toZoneString != null) {
768 toZoneString = toZoneString.concat(",").concat(value);
771 toZoneString = value;
777 String toZoneInsert = "'"+toZoneString+"'";
779 //getting sourceList Array fields from the firewallRulesList
780 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
781 String srcListString = null;
783 int srcListIndex = 0;
784 for (JsonValue srcListJsonValue : srcListArray) {
785 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
786 String type = srcListObj.get("type").toString().replace("\"", "");
789 if(type.equals("REFERENCE")||type.equals("GROUP")){
790 value = srcListObj.get("name").toString();
791 } else if (type.equalsIgnoreCase("ANY")){
794 value = srcListObj.get("value").toString();
798 value = value.replace("\"", "");
801 if (srcListString != null) {
802 srcListString = srcListString.concat(",").concat(value);
805 srcListString = value;
811 String srcListInsert = "'"+srcListString+"'";
813 //getting destinationList Array fields from the firewallRulesList
814 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
815 String destListString = null;
817 int destListIndex = 0;
818 for (JsonValue destListJsonValue : destListArray) {
819 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
820 String type = destListObj.get("type").toString().replace("\"", "");
823 if(type.equals("REFERENCE")||type.equals("GROUP")){
824 value = destListObj.get("name").toString();
825 } else if (type.equalsIgnoreCase("ANY")){
828 value = destListObj.get("value").toString();
832 value = value.replace("\"", "");
835 if (destListString != null) {
836 destListString = destListString.concat(",").concat(value);
838 destListString = value;
843 String destListInsert = "'"+destListString+"'";
845 //getting destServices Array fields from the firewallRulesList
846 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
847 String destPortListString = null;
849 int destPortListIndex = 0;
850 for (JsonValue destListJsonValue : destServicesArray) {
851 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
852 String type = destServicesObj.get("type").toString().replace("\"", "");
855 if(type.equals("REFERENCE")||type.equals("GROUP")){
856 value = destServicesObj.get("name").toString();
857 } else if (type.equalsIgnoreCase("ANY")){
860 value = destServicesObj.get("value").toString();
864 value = value.replace("\"", "");
867 if (destPortListString != null) {
868 destPortListString = destPortListString.concat(",").concat(value);
870 destPortListString = value;
875 String destPortListInsert = "'"+destPortListString+"'";
878 * Create Queries to INSERT data into database tables and execute
880 String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST,"
881 + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+","
882 +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+","
883 +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); ";
884 termSql = termSql.replace('"', '\'');
885 st.addBatch(termSql);
887 String actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+"); ";
888 actionSql = actionSql.replace('"', '\'');
889 st.addBatch(actionSql);
899 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
901 if (serviceGroup != null) {
903 int serviceGroupID = 0;
904 int serviceListID = 0;
909 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;");
911 serviceGroupID = rs.getInt("ID");
915 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;");
917 serviceListID = rs.getInt("ID");
921 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;");
923 protocolID = rs.getInt("ID");
927 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;");
929 portID = rs.getInt("ID");
934 for(JsonValue jsonValue : serviceGroup) {
937 * Populate ArrayLists with values from the JSON
939 //create the JSON object from the JSON Array for each iteration through the for loop
940 JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
942 String serviceListName = svcGroupListobj.get("name").toString();
944 String description = null;
945 if (svcGroupListobj.containsKey("description")){
946 description = svcGroupListobj.get("description").toString();
949 //getting members Array from the serviceGroup
950 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
952 //String type = svcGroupListobj.get("type").toString();
953 Boolean isServiceGroup = false;
954 if (membersArray!=null){
955 String membersType = membersArray.getJsonObject(0).get("type").toString();
956 if (membersType.contains("REFERENCE")) {
957 isServiceGroup = true;
961 //Insert values into GROUPSERVICELIST table if name begins with Group
962 if (isServiceGroup) {
964 //increment ID Primary Keys
965 serviceListID = serviceListID + 1;
969 int membersIndex = 0;
970 for (JsonValue membersValue : membersArray) {
971 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
972 //String value = membersObj.get("name").toString();
973 String type = membersObj.get("type").toString().replace("\"", "");
976 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
977 value = membersObj.get("name").toString();
978 } else if (type.equalsIgnoreCase("ANY")){
981 value = membersObj.get("value").toString();
985 value = value.replace("\"", "");
989 name = name.concat(",").concat(value);
996 String nameInsert = "'"+name+"'";
998 insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) "
999 + "VALUES("+serviceListID+","+serviceListName+","+nameInsert+")";
1001 //Replace double quote with single quote
1002 insertQuery = insertQuery.replace('"', '\'');
1004 //Execute the queries to Insert data
1005 st.executeUpdate(insertQuery);
1007 } else { //Insert JSON data serviceList table, protollist table, and portlist table
1009 //increment ID Primary Keys
1010 protocolID = protocolID + 1;
1011 portID = portID + 1;
1012 serviceGroupID = serviceGroupID + 1;
1014 String type = svcGroupListobj.get("type").toString();
1015 String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
1016 String ports = svcGroupListobj.get("ports").toString();
1019 * Create Queries to INSERT data into database table and execute
1021 String serviceSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) "
1022 + "VALUES("+serviceGroupID+","+serviceListName+","+description+","+type+","
1023 + transportProtocol+","+"null,"+ports+"); ";
1024 serviceSql = serviceSql.replace('"', '\'');
1025 st.addBatch(serviceSql);
1027 String protSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); ";
1028 protSql = protSql.replace('"', '\'');
1029 st.addBatch(protSql);
1031 String portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+");";
1032 portSql = portSql.replace('"', '\'');
1033 st.addBatch(portSql);
1046 * Inserting addressGroup data into the ADDRESSGROUP table
1048 if (addressGroup != null) {
1052 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;");
1054 prefixID = rs.getInt("ID");
1058 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;");
1060 addressID = rs.getInt("ID");
1066 for(JsonValue jsonValue : addressGroup) {
1069 * Populate ArrayLists with values from the JSON
1071 //create the JSON object from the JSON Array for each iteration through the for loop
1072 JsonObject addressGroupObj = addressGroup.getJsonObject(i);
1074 //create JSON array for members
1075 JsonArray membersArray = addressGroupObj.getJsonArray("members");
1076 String addressGroupName = addressGroupObj.get("name").toString();
1078 String description = null;
1079 if (addressGroupObj.containsKey("description")){
1080 description = addressGroupObj.get("description").toString();
1083 String prefixIP = null;
1086 int membersIndex = 0;
1087 for (JsonValue membersValue : membersArray) {
1088 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1089 //String value = membersObj.get("value").toString();
1090 type = membersObj.get("type").toString().replace("\"", "");
1092 String value = null;
1093 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1094 value = membersObj.get("name").toString();
1095 } else if (type.equalsIgnoreCase("ANY")){
1098 value = membersObj.get("value").toString();
1102 value = value.replace("\"", "");
1105 if (prefixIP != null) {
1106 prefixIP = prefixIP.concat(",").concat(value);
1113 String prefixList = "'"+prefixIP+"'";
1115 Boolean isAddressGroup = type.contains("REFERENCE");
1117 if (isAddressGroup) {
1118 //increment ID Primary Keys
1119 addressID = addressID + 1;
1121 insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) "
1122 + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")";
1124 //increment ID Primary Key
1125 prefixID = prefixID + 1;
1127 insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) "
1128 + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")";
1133 //Replace double quote with single quote
1134 insertQuery = insertQuery.replace('"', '\'');
1136 //Execute the queries to Insert data
1137 st.executeUpdate(insertQuery);
1145 * Remove duplicate values from 'lookup' dictionary tables
1147 //ProtocolList Table
1148 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
1149 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
1150 st.addBatch(protoDelete);
1153 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
1154 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
1155 st.addBatch(portListDelete);
1158 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
1159 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
1160 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
1161 st.addBatch(prefixListDelete);
1164 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
1165 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
1166 + "groupservicelist.serviceList = g1.serviceList; ";
1167 st.addBatch(groupServiceDelete);
1171 } catch (ClassNotFoundException e) {
1172 //TODO:EELF Cleanup - Remove logger
1173 //logger.error(e.getMessage());
1174 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries ");
1175 System.out.println(e.getMessage());
1178 } catch (SQLException e) {
1179 //TODO:EELF Cleanup - Remove logger
1180 //logger.error(e.getMessage());
1181 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1182 System.out.println(e.getMessage());
1184 } catch (Exception e) {
1185 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
1186 System.out.println(e.getMessage());
1190 if (con!=null) con.close();
1191 if (rs!=null) rs.close();
1192 if (st!=null) st.close();
1193 } catch (Exception ex){}
1204 private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
1206 JsonObject oldJson = null;
1207 JsonObject newJson = null;
1209 if (jsonBody != null || prevJsonBody != null) {
1211 oldJson = stringToJson(prevJsonBody);
1212 newJson = stringToJson(jsonBody);
1214 //if no changes to the json then return true
1215 if (oldJson.equals(newJson)) {
1219 JsonArray firewallRules = null;
1220 JsonArray serviceGroup = null;
1221 JsonArray addressGroup = null;
1223 firewallRules = newJson.getJsonArray("firewallRuleList");
1224 serviceGroup = newJson.getJsonArray("serviceGroups");
1225 addressGroup = newJson.getJsonArray("addressGroups");
1227 Connection con = null;
1228 Statement st = null;
1229 ResultSet rs = null;
1232 * Retrieve the property values for db access from the xacml.pap.properties
1234 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
1235 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
1236 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
1237 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
1239 //insert data into tables
1243 Class.forName(papDbDriver);
1244 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
1245 st = con.createStatement();
1247 JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
1250 for (JsonNode node : jsonDiff) {
1251 //String path = jsonDiff.get(i).asText();
1252 String jsonpatch = jsonDiff.get(i).toString();
1254 JsonObject patchObj = stringToJson(jsonpatch);
1256 String path = patchObj.get("path").toString().replace('"', ' ').trim();
1258 if (path.contains("firewallRuleList")) {
1263 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;");
1265 termID = rs.getInt("ID");
1269 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;");
1271 zoneID = rs.getInt("ID");
1275 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;");
1277 actionID = rs.getInt("ID");
1281 String insertQuery = null;
1284 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
1287 for(JsonValue jsonValue : firewallRules) {
1289 //increment ID Primary Keys
1290 termID = termID + 1;
1291 zoneID = zoneID + 1;
1292 actionID = actionID + 1;
1295 * Populate ArrayLists with values from the JSON
1297 //create the JSON object from the JSON Array for each iteration through the for loop
1298 JsonObject ruleListobj = firewallRules.getJsonObject(ri);
1300 //get values from JSON fields of firewallRulesList Array
1301 String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
1302 String action = ruleListobj.get("action").toString().replace('"', '\'');
1303 String description = ruleListobj.get("description").toString().replace('"', '\'');
1305 rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";");
1308 st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";");
1312 //getting fromZone Array field from the firewallRulesList
1313 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
1314 String fromZoneString = null;
1316 int fromZoneIndex = 0;
1317 for (JsonValue fromZoneJsonValue : fromZoneArray) {
1318 String value = fromZoneArray.get(fromZoneIndex).toString();
1319 value = value.replace("\"", "");
1321 if (fromZoneString != null) {
1322 fromZoneString = fromZoneString.concat(",").concat(value);
1325 fromZoneString = value;
1331 String fromZoneInsert = "'"+fromZoneString+"'";
1333 //getting toZone Array field from the firewallRulesList
1334 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
1335 String toZoneString = null;
1337 int toZoneIndex = 0;
1338 for (JsonValue toZoneJsonValue : toZoneArray) {
1339 String value = toZoneArray.get(toZoneIndex).toString();
1340 value = value.replace("\"", "");
1342 if (toZoneString != null) {
1343 toZoneString = toZoneString.concat(",").concat(value);
1346 toZoneString = value;
1352 String toZoneInsert = "'"+toZoneString+"'";
1353 //getting sourceList Array fields from the firewallRulesList
1354 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
1355 String srcListString = null;
1357 int srcListIndex = 0;
1358 for (JsonValue srcListJsonValue : srcListArray) {
1359 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
1360 String type = srcListObj.get("type").toString().replace("\"", "");
1362 String value = null;
1363 if(type.equals("REFERENCE")||type.equals("GROUP")){
1364 value = srcListObj.get("name").toString();
1365 } else if (type.equalsIgnoreCase("ANY")){
1368 value = srcListObj.get("value").toString();
1372 value = value.replace("\"", "");
1375 if (srcListString != null) {
1376 srcListString = srcListString.concat(",").concat(value);
1379 srcListString = value;
1385 String srcListInsert = "'"+srcListString+"'";
1387 //getting destinationList Array fields from the firewallRulesList
1388 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
1389 String destListString = null;
1391 int destListIndex = 0;
1392 for (JsonValue destListJsonValue : destListArray) {
1393 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
1394 String type = destListObj.get("type").toString().replace("\"", "");
1396 String value = null;
1397 if(type.equals("REFERENCE")||type.equals("GROUP")){
1398 value = destListObj.get("name").toString();
1399 } else if (type.equalsIgnoreCase("ANY")){
1402 value = destListObj.get("value").toString();
1406 value = value.replace("\"", "");
1409 if (destListString != null) {
1410 destListString = destListString.concat(",").concat(value);
1412 destListString = value;
1417 String destListInsert = "'"+destListString+"'";
1419 //getting destServices Array fields from the firewallRulesList
1420 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
1421 String destPortListString = null;
1423 int destPortListIndex = 0;
1424 for (JsonValue destListJsonValue : destServicesArray) {
1425 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
1426 String type = destServicesObj.get("type").toString().replace("\"", "");
1428 String value = null;
1429 if(type.equals("REFERENCE")||type.equals("GROUP")){
1430 value = destServicesObj.get("name").toString();
1431 } else if (type.equalsIgnoreCase("ANY")){
1434 value = destServicesObj.get("value").toString();
1438 value = value.replace("\"", "");
1441 if (destPortListString != null) {
1442 destPortListString = destPortListString.concat(",").concat(value);
1444 destPortListString = value;
1447 destPortListIndex++;
1449 String destPortListInsert = "'"+destPortListString+"'";
1452 * Create Queries to INSERT data into database tables and execute
1455 //Insert Into Terms table
1456 String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST,"
1457 + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+","
1458 +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+","
1459 +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); ";
1461 termSql = termSql.replace('"', '\'');
1462 st.addBatch(termSql);
1464 rs = st.executeQuery("SELECT * FROM ACTIONLIST WHERE ACTIONNAME = " + action + ";");
1466 String actionSql = null;
1470 actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+") ";
1471 actionSql = actionSql.replace('"', '\'');
1472 st.addBatch(actionSql);
1482 if (path.contains("serviceGroups")) {
1483 int serviceGroupID = 0;
1484 int serviceListID = 0;
1489 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;");
1491 serviceGroupID = rs.getInt("ID");
1495 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;");
1497 serviceListID = rs.getInt("ID");
1501 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;");
1503 protocolID = rs.getInt("ID");
1507 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;");
1509 portID = rs.getInt("ID");
1513 String insertQuery = null;
1516 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
1519 for(JsonValue jsonValue : serviceGroup) {
1522 * Populate ArrayLists with values from the JSON
1524 //create the JSON object from the JSON Array for each iteration through the for loop
1525 JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
1527 String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');
1529 String description = null;
1530 if (svcGroupListobj.containsKey("description")){
1531 description = svcGroupListobj.get("description").toString().replace('"', '\'');
1534 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
1536 Boolean isServiceGroup = false;
1537 if (membersArray!=null){
1538 String membersType = membersArray.getJsonObject(0).get("type").toString();
1539 if (membersType.contains("REFERENCE")) {
1540 isServiceGroup = true;
1544 //Insert values into GROUPSERVICELIST table if name begins with Group
1545 if (isServiceGroup) {
1547 rs = st.executeQuery("SELECT * FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";");
1550 st.executeUpdate("DELETE FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";");
1553 //increment ID Primary Keys
1554 serviceListID = serviceListID + 1;
1557 int membersIndex = 0;
1558 for (JsonValue membersValue : membersArray) {
1559 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1560 String type = membersObj.get("type").toString().replace("\"", "");
1562 String value = null;
1563 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1564 value = membersObj.get("name").toString();
1565 } else if (type.equalsIgnoreCase("ANY")){
1568 value = membersObj.get("value").toString();
1572 value = value.replace("\"", "");
1576 name = name.concat(",").concat(value);
1583 String nameInsert = "'"+name+"'";
1585 insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) "
1586 + "VALUES("+serviceListID+","+groupName+","+nameInsert+")";
1588 //Replace double quote with single quote
1589 insertQuery = insertQuery.replace('"', '\'');
1591 //Execute the queries to Insert data
1592 st.executeUpdate(insertQuery);
1594 } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
1596 //increment ID Primary Keys
1597 protocolID = protocolID + 1;
1598 portID = portID + 1;
1599 serviceGroupID = serviceGroupID + 1;
1601 String type = svcGroupListobj.get("type").toString().replace('"', '\'');
1602 String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
1603 String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
1605 rs = st.executeQuery("SELECT * FROM SERVICEGROUP WHERE NAME = "+ groupName + ";");
1608 st.executeUpdate("DELETE FROM SERVICEGROUP WHERE NAME = "+ groupName + ";");
1612 String svcGroupSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) "
1613 + "VALUES("+serviceGroupID+","+groupName+","+description+","+type+","
1614 + transportProtocol+","+"null,"+ports+"); ";
1615 svcGroupSql = svcGroupSql.replace('"', '\'');
1616 st.addBatch(svcGroupSql);
1618 rs = st.executeQuery("SELECT * FROM PROTOCOLLIST WHERE PROTOCOLNAME = " + transportProtocol + ";");
1620 String protoSql = null;
1624 protoSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) "
1625 + "VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); ";
1626 protoSql = protoSql.replace('"', '\'');
1627 st.addBatch(protoSql);
1632 rs = st.executeQuery("SELECT * FROM PORTLIST WHERE PORTNAME = " + ports + ";");
1634 String portSql = null;
1638 portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+"); ";
1639 portSql = portSql.replace('"', '\'');
1640 st.addBatch(portSql);
1654 if (path.contains("addressGroups")) {
1656 * Inserting addressGroup data into the ADDRESSGROUP table
1661 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;");
1663 prefixID = rs.getInt("ID");
1667 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;");
1669 addressID = rs.getInt("ID");
1673 String insertQuery = null;
1676 for(JsonValue jsonValue : addressGroup) {
1679 * Populate ArrayLists with values from the JSON
1681 //create the JSON object from the JSON Array for each iteration through the for loop
1682 JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
1684 //create JSON array for members
1685 JsonArray membersArray = addressGroupObj.getJsonArray("members");
1686 String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
1688 String description = null;
1689 if (addressGroupObj.containsKey("description")){
1690 description = addressGroupObj.get("description").toString().replace('"', '\'');
1693 String prefixIP = null;
1695 int membersIndex = 0;
1696 for (JsonValue membersValue : membersArray) {
1697 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1698 type = membersObj.get("type").toString().replace("\"", "");
1700 String value = null;
1701 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1702 value = membersObj.get("name").toString();
1703 } else if (type.equalsIgnoreCase("ANY")){
1706 value = membersObj.get("value").toString();
1710 value = value.replace("\"", "");
1713 if (prefixIP != null) {
1714 prefixIP = prefixIP.concat(",").concat(value);
1721 String prefixList = "'"+prefixIP+"'";
1723 Boolean isAddressGroup = type.contains("REFERENCE");
1725 if (isAddressGroup) {
1727 rs = st.executeQuery("SELECT * FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";");
1730 st.executeUpdate("DELETE FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";");
1733 //increment ID Primary Keys
1734 addressID = addressID + 1;
1736 insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) "
1737 + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")";
1743 rs = st.executeQuery("SELECT * FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";");
1746 st.executeUpdate("DELETE FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";");
1749 //increment ID Primary Key
1750 prefixID = prefixID + 1;
1752 insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) "
1753 + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")";
1758 //Replace double quote with single quote
1759 insertQuery = insertQuery.replace('"', '\'');
1761 //Execute the queries to Insert data
1762 st.executeUpdate(insertQuery);
1773 * Remove duplicate values from 'lookup' dictionary tables
1775 //ProtocolList Table
1776 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
1777 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
1778 st.addBatch(protoDelete);
1781 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
1782 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
1783 st.addBatch(portListDelete);
1786 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
1787 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
1788 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
1789 st.addBatch(prefixListDelete);
1792 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
1793 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
1794 + "groupservicelist.serviceList = g1.serviceList; ";
1795 st.addBatch(groupServiceDelete);
1799 } catch (ClassNotFoundException e) {
1800 //TODO:EELF Cleanup - Remove logger
1801 //logger.error(e.getMessage());
1802 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries");
1803 System.out.println(e.getMessage());
1806 } catch (SQLException e) {
1807 //TODO:EELF Cleanup - Remove logger
1808 //logger.error(e.getMessage());
1809 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1810 System.out.println(e.getMessage());
1814 if (con!=null) con.close();
1815 if (rs!=null) rs.close();
1816 if (st!=null) st.close();
1817 } catch (Exception ex){}
1827 private JsonObject stringToJson(String jsonString) {
1829 JsonObject json = null;
1830 if (jsonString != null) {
1832 //Read jsonBody to JsonObject
1833 StringReader in = null;
1835 in = new StringReader(jsonString);
1837 JsonReader jsonReader = Json.createReader(in);
1838 json = jsonReader.readObject();
1845 private JsonNode createPatch(String json, String oldJson) {
1846 JsonNode oldJason = null;
1847 JsonNode updatedJason = null;
1850 oldJason = JsonLoader.fromString(oldJson);
1851 updatedJason = JsonLoader.fromString(json);
1852 } catch (IOException e) {
1853 e.printStackTrace();
1856 JsonPatch jsonPatch = JsonDiff.asJsonPatch(oldJason, updatedJason);
1857 JsonNode patchNode = JsonDiff.asJson(oldJason, updatedJason);
1858 System.out.println("Sending Patch:" + jsonPatch);
1864 public Object getCorrectPolicyDataObject() {
1865 return policyAdapter.getPolicyData();