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.onap.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.SQLException;
35 import java.util.HashMap;
36 import java.util.List;
39 import javax.json.Json;
40 import javax.json.JsonArray;
41 import javax.json.JsonObject;
42 import javax.json.JsonReader;
43 import javax.persistence.EntityManager;
44 import javax.persistence.Query;
46 import org.apache.commons.io.FilenameUtils;
47 import org.onap.policy.common.logging.eelf.MessageCodes;
48 import org.onap.policy.common.logging.eelf.PolicyLogger;
49 import org.onap.policy.common.logging.flexlogger.FlexLogger;
50 import org.onap.policy.common.logging.flexlogger.Logger;
51 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
52 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
53 import org.onap.policy.rest.adapter.PolicyRestAdapter;
54 import org.onap.policy.rest.jpa.ActionList;
55 import org.onap.policy.rest.jpa.AddressGroup;
56 import org.onap.policy.rest.jpa.GroupServiceList;
57 import org.onap.policy.rest.jpa.PolicyEntity;
58 import org.onap.policy.rest.jpa.PortList;
59 import org.onap.policy.rest.jpa.PrefixList;
60 import org.onap.policy.rest.jpa.ProtocolList;
61 import org.onap.policy.rest.jpa.ServiceList;
62 import org.onap.policy.rest.jpa.TermList;
63 import org.onap.policy.rest.jpa.UserInfo;
65 import com.att.research.xacml.std.IdentifierImpl;
66 import com.fasterxml.jackson.databind.JsonNode;
67 import com.github.fge.jackson.JsonLoader;
68 import com.github.fge.jsonpatch.diff.JsonDiff;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
84 public class FirewallConfigPolicy extends Policy {
86 private static final Logger LOGGER = FlexLogger.getLogger(FirewallConfigPolicy.class);
88 public FirewallConfigPolicy() {
92 public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) {
93 this.policyAdapter = policyAdapter;
94 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
97 // Saving the Configurations file at server location for config policy.
98 protected void saveConfigurations(String policyName, String jsonBody) {
99 String configurationName = policyName;
100 FileWriter fw = null;
102 if(configurationName.endsWith(".xml")){
103 configurationName = configurationName.replace(".xml", "");
105 fw = new FileWriter(CONFIG_HOME + File.separator + configurationName + ".json");
106 BufferedWriter bw = new BufferedWriter(fw);
109 if (LOGGER.isDebugEnabled()) {
110 LOGGER.debug("Configuration is succesfully saved");
112 } catch (IOException e) {
113 LOGGER.error("Exception Occured"+e);
120 LOGGER.error("Exception Occured"+e);
125 //Utility to read json data from the existing file to a string
126 static String readFile(String path, Charset encoding) throws IOException {
127 byte[] encoded = Files.readAllBytes(Paths.get(path));
128 return new String(encoded, encoding);
132 public Map<String, String> savePolicies() throws Exception {
133 Map<String, String> successMap = new HashMap<>();
134 if(isPolicyExists()){
135 successMap.put("EXISTS", "This Policy already exist on the PAP");
138 if(!isPreparedToSave()){
142 // Until here we prepared the data and here calling the method to create xml.
143 Path newPolicyPath = null;
144 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
145 Boolean dbIsUpdated = false;
146 if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){
147 if (policyAdapter.isEditPolicy()) {
148 dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
150 dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
157 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
159 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
161 //remove the new json file
162 String jsonBody = policyAdapter.getPrevJsonBody();
164 saveConfigurations(policyName, jsonBody);
166 saveConfigurations(policyName, "");
168 successMap.put("fwdberror", "DB UPDATE");
174 //This is the method for preparing the policy for saving. We have broken it out
175 //separately because the fully configured policy is used for multiple things
177 public boolean prepareToSave() throws Exception{
179 if(isPreparedToSave()){
180 //we have already done this
185 String policyID = policyAdapter.getPolicyID();
186 version = policyAdapter.getHighestVersion();
188 // Create the Instance for pojo, PolicyType object is used in marshaling.
189 if ("Config".equals(policyAdapter.getPolicyType())) {
190 PolicyType policyConfig = new PolicyType();
192 policyConfig.setVersion(Integer.toString(version));
193 policyConfig.setPolicyId(policyID);
194 policyConfig.setTarget(new TargetType());
195 policyAdapter.setData(policyConfig);
197 policyName = policyAdapter.getNewFileName();
199 //String oldPolicyName = policyName.replace(".xml", "");
200 String scope = policyName.substring(0, policyName.indexOf('.'));
201 String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", "");
203 int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1));
204 dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1);
206 oldversion = oldversion - 1;
207 dbPolicyName = dbPolicyName + oldversion + ".xml";
209 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
210 Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
211 createPolicyQuery.setParameter("scope", scope);
212 createPolicyQuery.setParameter("policyName", dbPolicyName);
213 List<?> createPolicyQueryList = createPolicyQuery.getResultList();
214 if(!createPolicyQueryList.isEmpty()){
215 PolicyEntity entitydata = (PolicyEntity) createPolicyQueryList.get(0);
216 policyAdapter.setPrevJsonBody(entitydata.getConfigurationData().getConfigBody());
219 if (policyAdapter.getData() != null) {
220 String jsonBody = policyAdapter.getJsonBody();
221 saveConfigurations(policyName, jsonBody);
223 // Make sure the filename ends with an extension
224 if (!policyName.endsWith(".xml")) {
225 policyName = policyName + ".xml";
228 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
230 configPolicy.setDescription(policyAdapter.getPolicyDescription());
232 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
234 AllOfType allOfOne = new AllOfType();
235 String fileName = policyAdapter.getNewFileName();
236 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
237 if ((name == null) || (name.equals(""))) {
238 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
240 allOfOne.getMatch().add(createMatch("PolicyName", name));
241 AllOfType allOf = new AllOfType();
243 // Match for ConfigName
244 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
245 // Match for riskType
246 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
247 // Match for riskLevel
248 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
249 // Match for riskguard
250 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
252 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
253 AnyOfType anyOf = new AnyOfType();
254 anyOf.getAllOf().add(allOfOne);
255 anyOf.getAllOf().add(allOf);
257 TargetType target = new TargetType();
258 target.getAnyOf().add(anyOf);
260 // Adding the target to the policy element
261 configPolicy.setTarget((TargetType) target);
263 RuleType rule = new RuleType();
264 rule.setRuleId(policyAdapter.getRuleID());
265 rule.setEffect(EffectType.PERMIT);
267 // Create Target in Rule
268 AllOfType allOfInRule = new AllOfType();
270 // Creating match for ACCESS in rule target
271 MatchType accessMatch = new MatchType();
272 AttributeValueType accessAttributeValue = new AttributeValueType();
273 accessAttributeValue.setDataType(STRING_DATATYPE);
274 accessAttributeValue.getContent().add("ACCESS");
275 accessMatch.setAttributeValue(accessAttributeValue);
276 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
277 URI accessURI = null;
279 accessURI = new URI(ACTION_ID);
280 } catch (URISyntaxException e) {
281 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
283 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
284 accessAttributeDesignator.setDataType(STRING_DATATYPE);
285 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
286 accessMatch.setAttributeDesignator(accessAttributeDesignator);
287 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
289 // Creating Config Match in rule Target
290 MatchType configMatch = new MatchType();
291 AttributeValueType configAttributeValue = new AttributeValueType();
292 configAttributeValue.setDataType(STRING_DATATYPE);
294 configAttributeValue.getContent().add("Config");
296 configMatch.setAttributeValue(configAttributeValue);
297 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
298 URI configURI = null;
300 configURI = new URI(RESOURCE_ID);
301 } catch (URISyntaxException e) {
302 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
305 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
306 configAttributeDesignator.setDataType(STRING_DATATYPE);
307 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
308 configMatch.setAttributeDesignator(configAttributeDesignator);
309 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
311 allOfInRule.getMatch().add(accessMatch);
312 allOfInRule.getMatch().add(configMatch);
314 AnyOfType anyOfInRule = new AnyOfType();
315 anyOfInRule.getAllOf().add(allOfInRule);
317 TargetType targetInRule = new TargetType();
318 targetInRule.getAnyOf().add(anyOfInRule);
320 rule.setTarget(targetInRule);
321 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
323 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
324 policyAdapter.setPolicyData(configPolicy);
327 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
329 setPreparedToSave(true);
333 // Data required for Advice part is setting here.
334 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
336 //Firewall Config ID Assignment
337 AdviceExpressionsType advices = new AdviceExpressionsType();
338 AdviceExpressionType advice = new AdviceExpressionType();
339 advice.setAdviceId("firewallConfigID");
340 advice.setAppliesTo(EffectType.PERMIT);
342 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
343 assignment1.setAttributeId("type");
344 assignment1.setCategory(CATEGORY_RESOURCE);
345 assignment1.setIssuer("");
346 AttributeValueType configNameAttributeValue = new AttributeValueType();
347 configNameAttributeValue.setDataType(STRING_DATATYPE);
348 configNameAttributeValue.getContent().add("Configuration");
349 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
350 advice.getAttributeAssignmentExpression().add(assignment1);
352 // For Config file Url if configurations are provided.
354 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
355 assignment2.setAttributeId("URLID");
356 assignment2.setCategory(CATEGORY_RESOURCE);
357 assignment2.setIssuer("");
358 AttributeValueType AttributeValue = new AttributeValueType();
359 AttributeValue.setDataType(URI_DATATYPE);
360 if (policyName.endsWith(".xml")) {
361 policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
363 String content = CONFIG_URL + "/Config/" + policyName + ".json";
365 AttributeValue.getContent().add(content);
366 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
367 advice.getAttributeAssignmentExpression().add(assignment2);
369 //Policy Name Assignment
370 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
371 assignment3.setAttributeId("PolicyName");
372 assignment3.setCategory(CATEGORY_RESOURCE);
373 assignment3.setIssuer("");
374 AttributeValueType attributeValue3 = new AttributeValueType();
375 attributeValue3.setDataType(STRING_DATATYPE);
376 fileName = FilenameUtils.removeExtension(fileName);
377 fileName = fileName + ".xml";
378 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
379 if ((name == null) || (name.equals(""))) {
380 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
382 attributeValue3.getContent().add(name);
383 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
384 advice.getAttributeAssignmentExpression().add(assignment3);
386 //Version Number Assignment
387 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
388 assignment4.setAttributeId("VersionNumber");
389 assignment4.setCategory(CATEGORY_RESOURCE);
390 assignment4.setIssuer("");
391 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
392 configNameAttributeValue4.setDataType(STRING_DATATYPE);
393 configNameAttributeValue4.getContent().add(Integer.toString(version));
394 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
395 advice.getAttributeAssignmentExpression().add(assignment4);
397 //Onap Name Assignment
398 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
399 assignment5.setAttributeId("matching:" + ONAPID);
400 assignment5.setCategory(CATEGORY_RESOURCE);
401 assignment5.setIssuer("");
402 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
403 configNameAttributeValue5.setDataType(STRING_DATATYPE);
404 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
405 advice.getAttributeAssignmentExpression().add(assignment5);
407 //Config Name Assignment
408 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
409 assignment6.setAttributeId("matching:" + CONFIGID);
410 assignment6.setCategory(CATEGORY_RESOURCE);
411 assignment6.setIssuer("");
412 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
413 configNameAttributeValue6.setDataType(STRING_DATATYPE);
414 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
415 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
416 advice.getAttributeAssignmentExpression().add(assignment6);
419 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
420 assignment7.setAttributeId("RiskType");
421 assignment7.setCategory(CATEGORY_RESOURCE);
422 assignment7.setIssuer("");
424 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
425 configNameAttributeValue7.setDataType(STRING_DATATYPE);
426 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
427 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
429 advice.getAttributeAssignmentExpression().add(assignment7);
431 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
432 assignment8.setAttributeId("RiskLevel");
433 assignment8.setCategory(CATEGORY_RESOURCE);
434 assignment8.setIssuer("");
436 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
437 configNameAttributeValue8.setDataType(STRING_DATATYPE);
438 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
439 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
441 advice.getAttributeAssignmentExpression().add(assignment8);
443 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
444 assignment9.setAttributeId("guard");
445 assignment9.setCategory(CATEGORY_RESOURCE);
446 assignment9.setIssuer("");
448 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
449 configNameAttributeValue9.setDataType(STRING_DATATYPE);
450 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
451 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
453 advice.getAttributeAssignmentExpression().add(assignment9);
455 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
456 assignment10.setAttributeId("TTLDate");
457 assignment10.setCategory(CATEGORY_RESOURCE);
458 assignment10.setIssuer("");
460 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
461 configNameAttributeValue10.setDataType(STRING_DATATYPE);
462 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
463 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
465 advice.getAttributeAssignmentExpression().add(assignment10);
466 advices.getAdviceExpression().add(advice);
471 private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
472 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
473 JsonObject json = null;
474 if (jsonBody != null) {
476 //Read jsonBody to JsonObject
477 json = stringToJson(jsonBody);
479 JsonArray firewallRules = null;
480 JsonArray serviceGroup = null;
481 JsonArray addressGroup = null;
482 //insert data into tables
484 firewallRules = json.getJsonArray("firewallRuleList");
485 serviceGroup = json.getJsonArray("serviceGroups");
486 addressGroup = json.getJsonArray("addressGroups");
488 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
490 if (firewallRules != null) {
491 for(int i = 0;i<firewallRules.size();i++) {
493 * Populate ArrayLists with values from the JSON
495 //create the JSON object from the JSON Array for each iteration through the for loop
496 JsonObject ruleListobj = firewallRules.getJsonObject(i);
498 //get values from JSON fields of firewallRulesList Array
499 String ruleName = ruleListobj.get("ruleName").toString();
500 String action = ruleListobj.get("action").toString();
501 String description = ruleListobj.get("description").toString();
502 List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
503 if(result != null && !result.isEmpty()){
504 TermList termEntry = (TermList) result.get(0);
505 dbConnection.delete(termEntry);
508 //getting fromZone Array field from the firewallRulesList
509 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
510 String fromZoneString = null;
512 for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) {
513 String value = fromZoneArray.get(fromZoneIndex).toString();
514 value = value.replace("\"", "");
515 if (fromZoneString != null) {
516 fromZoneString = fromZoneString.concat(",").concat(value);
518 fromZoneString = value;
521 String fromZoneInsert = "'"+fromZoneString+"'";
523 //getting toZone Array field from the firewallRulesList
524 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
525 String toZoneString = null;
526 for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) {
527 String value = toZoneArray.get(toZoneIndex).toString();
528 value = value.replace("\"", "");
529 if (toZoneString != null) {
530 toZoneString = toZoneString.concat(",").concat(value);
532 toZoneString = value;
535 String toZoneInsert = "'"+toZoneString+"'";
537 //getting sourceList Array fields from the firewallRulesList
538 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
539 String srcListString = null;
540 for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) {
541 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
542 String type = srcListObj.get("type").toString().replace("\"", "");
545 if(type.equals("REFERENCE")||type.equals("GROUP")){
546 value = srcListObj.get("name").toString();
547 } else if (type.equalsIgnoreCase("ANY")){
550 value = srcListObj.get("value").toString();
554 value = value.replace("\"", "");
557 if (srcListString != null) {
558 srcListString = srcListString.concat(",").concat(value);
561 srcListString = value;
565 String srcListInsert = "'"+srcListString+"'";
567 //getting destinationList Array fields from the firewallRulesList
568 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
569 String destListString = null;
570 for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) {
571 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
572 String type = destListObj.get("type").toString().replace("\"", "");
575 if(type.equals("REFERENCE")||type.equals("GROUP")){
576 value = destListObj.get("name").toString();
577 } else if (type.equalsIgnoreCase("ANY")){
580 value = destListObj.get("value").toString();
584 value = value.replace("\"", "");
587 if (destListString != null) {
588 destListString = destListString.concat(",").concat(value);
590 destListString = value;
593 String destListInsert = "'"+destListString+"'";
595 //getting destServices Array fields from the firewallRulesList
596 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
597 String destPortListString = null;
598 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
599 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
600 String type = destServicesObj.get("type").toString().replace("\"", "");
603 if(type.equals("REFERENCE")||type.equals("GROUP")){
604 value = destServicesObj.get("name").toString();
605 } else if (type.equalsIgnoreCase("ANY")){
608 value = destServicesObj.get("value").toString();
612 value = value.replace("\"", "");
615 if (destPortListString != null) {
616 destPortListString = destPortListString.concat(",").concat(value);
618 destPortListString = value;
621 String destPortListInsert = "'"+destPortListString+"'";
624 * Create Queries to INSERT data into database tables and execute
626 UserInfo userInfo = new UserInfo();
627 userInfo.setUserLoginId("API");
628 userInfo.setUserName("API");
630 TermList termEntry = new TermList();
631 termEntry.setTermName(ruleName);
632 termEntry.setSrcIPList(srcListInsert);
633 termEntry.setDestIPList(destListInsert);
634 termEntry.setProtocolList("null");
635 termEntry.setPortList("null");
636 termEntry.setSrcPortList("null");
637 termEntry.setDestPortList(destPortListInsert);
638 termEntry.setAction(action);
639 termEntry.setDescription(description);
640 termEntry.setFromZones(fromZoneInsert);
641 termEntry.setToZones(toZoneInsert);
642 termEntry.setUserCreatedBy(userInfo);
643 dbConnection.save(termEntry);
645 ActionList actionEntry = new ActionList();
646 actionEntry.setActionName(action);
647 actionEntry.setDescription(action);
648 dbConnection.save(actionEntry);
653 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
655 if (serviceGroup != null) {
656 for(int i = 0; i < serviceGroup.size() ; i++) {
658 * Populate ArrayLists with values from the JSON
660 //create the JSON object from the JSON Array for each iteration through the for loop
661 JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
663 String serviceListName = svcGroupListobj.get("name").toString();
664 String description = null;
665 if (svcGroupListobj.containsKey("description")){
666 description = svcGroupListobj.get("description").toString();
669 //getting members Array from the serviceGroup
670 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
672 //String type = svcGroupListobj.get("type").toString();
673 Boolean isServiceGroup = false;
674 if (membersArray!=null){
675 String membersType = membersArray.getJsonObject(0).get("type").toString();
676 if (membersType.contains("REFERENCE")) {
677 isServiceGroup = true;
681 //Insert values into GROUPSERVICELIST table if name begins with Group
682 if (isServiceGroup) {
684 for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) {
685 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
686 //String value = membersObj.get("name").toString();
687 String type = membersObj.get("type").toString().replace("\"", "");
690 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
691 value = membersObj.get("name").toString();
692 } else if (type.equalsIgnoreCase("ANY")){
695 value = membersObj.get("value").toString();
699 value = value.replace("\"", "");
703 name = name.concat(",").concat(value);
708 String nameInsert = "'"+name+"'";
709 GroupServiceList groupServiceEntry = new GroupServiceList();
710 groupServiceEntry.setGroupName(serviceListName);
711 groupServiceEntry.setServiceList(nameInsert);
712 dbConnection.save(groupServiceEntry);
713 } else { //Insert JSON data serviceList table, protollist table, and portlist table
714 String type = svcGroupListobj.get("type").toString();
715 String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
716 String ports = svcGroupListobj.get("ports").toString();
719 * Create Queries to INSERT data into database table and execute
721 ServiceList serviceListEntry = new ServiceList();
722 serviceListEntry.setServiceName(serviceListName);
723 serviceListEntry.setServiceDescription(description);
724 serviceListEntry.setServiceType(type);
725 serviceListEntry.setServiceTransProtocol(transportProtocol);
726 serviceListEntry.setServiceAppProtocol("null");
727 serviceListEntry.setServicePorts(ports);
728 dbConnection.save(serviceListEntry);
730 ProtocolList protocolEntry = new ProtocolList();
731 protocolEntry.setProtocolName(transportProtocol);
732 protocolEntry.setDescription(transportProtocol);
733 dbConnection.save(protocolEntry);
735 PortList portListEntry = new PortList();
736 portListEntry.setPortName(ports);
737 portListEntry.setDescription(ports);
738 dbConnection.save(portListEntry);
744 * Inserting addressGroup data into the ADDRESSGROUP table
746 if (addressGroup != null) {
747 for(int i = 0; i < addressGroup.size(); i++) {
749 * Populate ArrayLists with values from the JSON
751 //create the JSON object from the JSON Array for each iteration through the for loop
752 JsonObject addressGroupObj = addressGroup.getJsonObject(i);
754 //create JSON array for members
755 JsonArray membersArray = addressGroupObj.getJsonArray("members");
756 String addressGroupName = addressGroupObj.get("name").toString();
758 String description = null;
759 if (addressGroupObj.containsKey("description")){
760 description = addressGroupObj.get("description").toString();
763 String prefixIP = null;
765 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
766 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
767 //String value = membersObj.get("value").toString();
768 type = membersObj.get("type").toString().replace("\"", "");
771 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
772 value = membersObj.get("name").toString();
773 } else if (type.equalsIgnoreCase("ANY")){
776 value = membersObj.get("value").toString();
780 value = value.replace("\"", "");
783 if (prefixIP != null) {
784 prefixIP = prefixIP.concat(",").concat(value);
789 String prefixList = "'"+prefixIP+"'";
791 Boolean isAddressGroup = type.contains("REFERENCE");
793 if (isAddressGroup) {
794 AddressGroup addressGroupEntry = new AddressGroup();
795 addressGroupEntry.setGroupName(addressGroupName);
796 addressGroupEntry.setDescription(description);
797 addressGroupEntry.setServiceList(prefixList);
798 dbConnection.save(addressGroupEntry);
800 PrefixList prefixListEntry = new PrefixList();
801 prefixListEntry.setPrefixListName(addressGroupName);
802 prefixListEntry.setDescription(description);
803 prefixListEntry.setPrefixListValue(prefixList);
804 dbConnection.save(prefixListEntry);
810 * Remove duplicate values from 'lookup' dictionary tables
813 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
814 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
815 dbConnection.updateQuery(protoDelete);
818 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
819 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
820 dbConnection.updateQuery(portListDelete);
823 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
824 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
825 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
826 dbConnection.updateQuery(prefixListDelete);
829 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
830 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
831 + "groupservicelist.serviceList = g1.serviceList; ";
832 dbConnection.updateQuery(groupServiceDelete);
833 }catch (Exception e) {
834 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
846 private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
847 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
848 JsonObject oldJson = null;
849 JsonObject newJson = null;
851 if (jsonBody != null || prevJsonBody != null) {
853 oldJson = stringToJson(prevJsonBody);
854 newJson = stringToJson(jsonBody);
856 //if no changes to the json then return true
857 if (oldJson != null && oldJson.equals(newJson)) {
861 JsonArray firewallRules = null;
862 JsonArray serviceGroup = null;
863 JsonArray addressGroup = null;
865 firewallRules = newJson.getJsonArray("firewallRuleList");
866 serviceGroup = newJson.getJsonArray("serviceGroups");
867 addressGroup = newJson.getJsonArray("addressGroups");
869 //insert data into tables
871 JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
873 for (int i = 0; i<jsonDiff.size(); i++) {
874 //String path = jsonDiff.get(i).asText();
875 String jsonpatch = jsonDiff.get(i).toString();
877 JsonObject patchObj = stringToJson(jsonpatch);
879 String path = patchObj.get("path").toString().replace('"', ' ').trim();
881 if (path.contains("firewallRuleList")) {
883 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
885 for(int ri = 0; ri < firewallRules.size(); ri++) {
887 * Populate ArrayLists with values from the JSON
889 //create the JSON object from the JSON Array for each iteration through the for loop
890 JsonObject ruleListobj = firewallRules.getJsonObject(ri);
892 //get values from JSON fields of firewallRulesList Array
893 String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
894 String action = ruleListobj.get("action").toString().replace('"', '\'');
895 String description = ruleListobj.get("description").toString().replace('"', '\'');
897 List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
898 if(result != null && !result.isEmpty()){
899 TermList termEntry = (TermList) result.get(0);
900 dbConnection.delete(termEntry);
903 //getting fromZone Array field from the firewallRulesList
904 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
905 String fromZoneString = null;
907 for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) {
908 String value = fromZoneArray.get(fromZoneIndex).toString();
909 value = value.replace("\"", "");
911 if (fromZoneString != null) {
912 fromZoneString = fromZoneString.concat(",").concat(value);
915 fromZoneString = value;
919 String fromZoneInsert = "'"+fromZoneString+"'";
921 //getting toZone Array field from the firewallRulesList
922 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
923 String toZoneString = null;
926 for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
927 String value = toZoneArray.get(toZoneIndex).toString();
928 value = value.replace("\"", "");
930 if (toZoneString != null) {
931 toZoneString = toZoneString.concat(",").concat(value);
934 toZoneString = value;
938 String toZoneInsert = "'"+toZoneString+"'";
939 //getting sourceList Array fields from the firewallRulesList
940 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
941 String srcListString = null;
942 for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) {
943 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
944 String type = srcListObj.get("type").toString().replace("\"", "");
947 if(type.equals("REFERENCE")||type.equals("GROUP")){
948 value = srcListObj.get("name").toString();
949 } else if (type.equalsIgnoreCase("ANY")){
952 value = srcListObj.get("value").toString();
956 value = value.replace("\"", "");
959 if (srcListString != null) {
960 srcListString = srcListString.concat(",").concat(value);
963 srcListString = value;
967 String srcListInsert = "'"+srcListString+"'";
969 //getting destinationList Array fields from the firewallRulesList
970 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
971 String destListString = null;
972 for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) {
973 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
974 String type = destListObj.get("type").toString().replace("\"", "");
977 if(type.equals("REFERENCE")||type.equals("GROUP")){
978 value = destListObj.get("name").toString();
979 } else if (type.equalsIgnoreCase("ANY")){
982 value = destListObj.get("value").toString();
986 value = value.replace("\"", "");
989 if (destListString != null) {
990 destListString = destListString.concat(",").concat(value);
992 destListString = value;
995 String destListInsert = "'"+destListString+"'";
997 //getting destServices Array fields from the firewallRulesList
998 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
999 String destPortListString = null;
1000 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
1001 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
1002 String type = destServicesObj.get("type").toString().replace("\"", "");
1004 String value = null;
1005 if(type.equals("REFERENCE")||type.equals("GROUP")){
1006 value = destServicesObj.get("name").toString();
1007 } else if (type.equalsIgnoreCase("ANY")){
1010 value = destServicesObj.get("value").toString();
1014 value = value.replace("\"", "");
1017 if (destPortListString != null) {
1018 destPortListString = destPortListString.concat(",").concat(value);
1020 destPortListString = value;
1023 String destPortListInsert = "'"+destPortListString+"'";
1026 * Create Queries to INSERT data into database tables and execute
1028 UserInfo userInfo = new UserInfo();
1029 userInfo.setUserLoginId("API");
1030 userInfo.setUserName("API");
1032 TermList termEntry = new TermList();
1033 termEntry.setTermName(ruleName);
1034 termEntry.setSrcIPList(srcListInsert);
1035 termEntry.setDestIPList(destListInsert);
1036 termEntry.setProtocolList("null");
1037 termEntry.setPortList("null");
1038 termEntry.setSrcPortList("null");
1039 termEntry.setDestPortList(destPortListInsert);
1040 termEntry.setAction(action);
1041 termEntry.setDescription(description);
1042 termEntry.setFromZones(fromZoneInsert);
1043 termEntry.setToZones(toZoneInsert);
1044 termEntry.setUserCreatedBy(userInfo);
1045 dbConnection.save(termEntry);
1047 List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action);
1048 if(actionResult == null || actionResult.isEmpty()){
1049 ActionList actionEntry = new ActionList();
1050 actionEntry.setActionName(action);
1051 actionEntry.setDescription(action);
1052 dbConnection.save(actionEntry);
1057 if (path.contains("serviceGroups")) {
1059 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
1061 for(int si = 0; si < serviceGroup.size(); si++) {
1063 * Populate ArrayLists with values from the JSON
1065 //create the JSON object from the JSON Array for each iteration through the for loop
1066 JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
1068 String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');
1070 String description = null;
1071 if (svcGroupListobj.containsKey("description")){
1072 description = svcGroupListobj.get("description").toString().replace('"', '\'');
1075 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
1077 Boolean isServiceGroup = false;
1078 if (membersArray!=null){
1079 String membersType = membersArray.getJsonObject(0).get("type").toString();
1080 if (membersType.contains("REFERENCE")) {
1081 isServiceGroup = true;
1085 //Insert values into GROUPSERVICELIST table if name begins with Group
1086 if (isServiceGroup) {
1087 List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName);
1088 if(result != null && !result.isEmpty()){
1089 GroupServiceList groupEntry = (GroupServiceList) result.get(0);
1090 dbConnection.delete(groupEntry);
1094 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
1095 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1096 String type = membersObj.get("type").toString().replace("\"", "");
1098 String value = null;
1099 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1100 value = membersObj.get("name").toString();
1101 } else if (type.equalsIgnoreCase("ANY")){
1104 value = membersObj.get("value").toString();
1108 value = value.replace("\"", "");
1112 name = name.concat(",").concat(value);
1117 String nameInsert = "'"+name+"'";
1118 GroupServiceList groupServiceEntry = new GroupServiceList();
1119 groupServiceEntry.setGroupName(groupName);
1120 groupServiceEntry.setServiceList(nameInsert);
1121 dbConnection.save(groupServiceEntry);
1122 } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
1123 String type = svcGroupListobj.get("type").toString().replace('"', '\'');
1124 String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
1125 String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
1127 List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName);
1128 if(result != null && !result.isEmpty()){
1129 ServiceList serviceEntry = (ServiceList) result.get(0);
1130 dbConnection.delete(serviceEntry);
1133 ServiceList serviceListEntry = new ServiceList();
1134 serviceListEntry.setServiceName(groupName);
1135 serviceListEntry.setServiceDescription(description);
1136 serviceListEntry.setServiceType(type);
1137 serviceListEntry.setServiceTransProtocol(transportProtocol);
1138 serviceListEntry.setServiceAppProtocol("null");
1139 serviceListEntry.setServicePorts(ports);
1140 dbConnection.save(serviceListEntry);
1142 List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
1143 if(protocolResult == null || protocolResult.isEmpty()){
1144 ProtocolList protocolEntry = new ProtocolList();
1145 protocolEntry.setProtocolName(transportProtocol);
1146 protocolEntry.setDescription(transportProtocol);
1147 dbConnection.save(protocolEntry);
1150 List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports);
1151 if(portResult == null || portResult.isEmpty()){
1152 PortList portEntry = new PortList();
1153 portEntry.setPortName(ports);
1154 portEntry.setDescription(ports);
1155 dbConnection.save(portEntry);
1161 if (path.contains("addressGroups")) {
1163 * Inserting addressGroup data into the ADDRESSGROUP table
1165 for(int ai=0; ai < addressGroup.size() ; ai++) {
1168 * Populate ArrayLists with values from the JSON
1170 //create the JSON object from the JSON Array for each iteration through the for loop
1171 JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
1173 //create JSON array for members
1174 JsonArray membersArray = addressGroupObj.getJsonArray("members");
1175 String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
1177 String description = null;
1178 if (addressGroupObj.containsKey("description")){
1179 description = addressGroupObj.get("description").toString().replace('"', '\'');
1182 String prefixIP = null;
1184 for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) {
1185 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1186 type = membersObj.get("type").toString().replace("\"", "");
1188 String value = null;
1189 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1190 value = membersObj.get("name").toString();
1191 } else if (type.equalsIgnoreCase("ANY")){
1194 value = membersObj.get("value").toString();
1198 value = value.replace("\"", "");
1201 if (prefixIP != null) {
1202 prefixIP = prefixIP.concat(",").concat(value);
1208 String prefixList = "'"+prefixIP+"'";
1209 Boolean isAddressGroup = type.contains("REFERENCE");
1211 if (isAddressGroup) {
1212 List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
1213 if(result != null && !result.isEmpty()){
1214 AddressGroup addressGroupEntry = (AddressGroup) result.get(0);
1215 dbConnection.delete(addressGroupEntry);
1217 AddressGroup newAddressGroup = new AddressGroup();
1218 newAddressGroup.setGroupName(addressGroupName);
1219 newAddressGroup.setDescription(description);
1220 newAddressGroup.setServiceList(prefixList);
1221 dbConnection.save(newAddressGroup);
1223 List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
1224 if(result != null && !result.isEmpty()){
1225 PrefixList prefixListEntry = (PrefixList) result.get(0);
1226 dbConnection.delete(prefixListEntry);
1228 PrefixList newPrefixList = new PrefixList();
1229 newPrefixList.setPrefixListName(addressGroupName);
1230 newPrefixList.setDescription(description);
1231 newPrefixList.setPrefixListValue(prefixList);
1232 dbConnection.save(newPrefixList);
1239 * Remove duplicate values from 'lookup' dictionary tables
1241 //ProtocolList Table
1242 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
1243 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
1244 dbConnection.updateQuery(protoDelete);
1247 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
1248 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
1249 dbConnection.updateQuery(portListDelete);
1252 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
1253 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
1254 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
1255 dbConnection.updateQuery(prefixListDelete);
1258 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
1259 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
1260 + "groupservicelist.serviceList = g1.serviceList; ";
1261 dbConnection.updateQuery(groupServiceDelete);
1262 }catch (Exception e) {
1263 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1273 private JsonObject stringToJson(String jsonString) {
1274 JsonObject json = null;
1275 if (jsonString != null) {
1276 //Read jsonBody to JsonObject
1277 StringReader in = null;
1278 in = new StringReader(jsonString);
1280 JsonReader jsonReader = Json.createReader(in);
1281 json = jsonReader.readObject();
1287 private JsonNode createPatch(String json, String oldJson) {
1288 JsonNode oldJason = null;
1289 JsonNode updatedJason = null;
1292 oldJason = JsonLoader.fromString(oldJson);
1293 updatedJason = JsonLoader.fromString(json);
1294 } catch (IOException e) {
1295 LOGGER.error("Exception Occured"+e);
1297 return JsonDiff.asJson(oldJason, updatedJason);
1301 public Object getCorrectPolicyDataObject() {
1302 return policyAdapter.getPolicyData();