2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2019 Bell Canada.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.xacml.rest.components;
24 import com.att.research.xacml.api.pap.PAPException;
25 import com.att.research.xacml.std.IdentifierImpl;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.github.fge.jackson.JsonLoader;
28 import com.github.fge.jsonpatch.diff.JsonDiff;
29 import java.io.BufferedWriter;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.StringReader;
35 import java.net.URISyntaxException;
36 import java.nio.charset.Charset;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.sql.SQLException;
41 import java.util.HashMap;
42 import java.util.List;
44 import javax.json.Json;
45 import javax.json.JsonArray;
46 import javax.json.JsonObject;
47 import javax.json.JsonReader;
48 import javax.script.SimpleBindings;
49 import org.apache.commons.io.FilenameUtils;
50 import org.onap.policy.common.logging.eelf.MessageCodes;
51 import org.onap.policy.common.logging.eelf.PolicyLogger;
52 import org.onap.policy.common.logging.flexlogger.FlexLogger;
53 import org.onap.policy.common.logging.flexlogger.Logger;
54 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
55 import org.onap.policy.rest.adapter.PolicyRestAdapter;
56 import org.onap.policy.rest.dao.CommonClassDao;
57 import org.onap.policy.rest.jpa.ActionList;
58 import org.onap.policy.rest.jpa.AddressGroup;
59 import org.onap.policy.rest.jpa.GroupServiceList;
60 import org.onap.policy.rest.jpa.PolicyEntity;
61 import org.onap.policy.rest.jpa.PortList;
62 import org.onap.policy.rest.jpa.PrefixList;
63 import org.onap.policy.rest.jpa.ProtocolList;
64 import org.onap.policy.rest.jpa.ServiceList;
65 import org.onap.policy.rest.jpa.TermList;
66 import org.onap.policy.rest.jpa.UserInfo;
67 import org.springframework.beans.factory.annotation.Autowired;
68 import org.springframework.stereotype.Component;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
81 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 private static CommonClassDao commonClassDao;
95 public FirewallConfigPolicy(CommonClassDao commonClassDao) {
96 FirewallConfigPolicy.commonClassDao = commonClassDao;
99 public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) {
100 this.policyAdapter = policyAdapter;
101 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
104 // Saving the Configurations file at server location for config policy.
105 protected void saveConfigurations(String policyName, String jsonBody) {
106 String configurationName = policyName;
107 if (configurationName.endsWith(".xml")) {
108 configurationName = configurationName.replace(".xml", "");
110 String fileName = CONFIG_HOME + File.separator + configurationName + ".json";
111 try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
113 if (LOGGER.isDebugEnabled()) {
114 LOGGER.debug("Configuration is succesfully saved");
116 } catch (IOException e) {
117 LOGGER.error("Save of configuration to file" +fileName+ "failed",e);
121 //Utility to read json data from the existing file to a string
122 static String readFile(String path, Charset encoding) throws IOException {
123 byte[] encoded = Files.readAllBytes(Paths.get(path));
124 return new String(encoded, encoding);
128 public Map<String, String> savePolicies() throws PAPException {
129 Map<String, String> successMap = new HashMap<>();
130 if(isPolicyExists()){
131 successMap.put("EXISTS", "This Policy already exist on the PAP");
134 if(!isPreparedToSave()){
138 // Until here we prepared the data and here calling the method to create xml.
139 Path newPolicyPath = null;
140 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
141 Boolean dbIsUpdated = false;
142 if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){
143 if (policyAdapter.isEditPolicy()) {
144 dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
147 dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
148 } catch (SQLException e) {
149 throw new PAPException(e);
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 PAPException{
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 String createPolicyQuery = "SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName";
210 SimpleBindings params = new SimpleBindings();
211 params.put("scope", scope);
212 params.put("policyName", dbPolicyName);
213 List<?> createPolicyQueryList = commonClassDao.getDataByQuery(createPolicyQuery, params);
214 if (!createPolicyQueryList.isEmpty()) {
215 PolicyEntity entitydata = (PolicyEntity) createPolicyQueryList.get(0);
216 policyAdapter.setPrevJsonBody(entitydata.getConfigurationData().getConfigBody());
218 if (policyAdapter.getData() != null) {
219 String jsonBody = policyAdapter.getJsonBody();
220 saveConfigurations(policyName, jsonBody);
222 // Make sure the filename ends with an extension
223 if (!policyName.endsWith(".xml")) {
224 policyName = policyName + ".xml";
227 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
229 configPolicy.setDescription(policyAdapter.getPolicyDescription());
231 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
233 AllOfType allOfOne = new AllOfType();
234 String fileName = policyAdapter.getNewFileName();
235 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
236 if ((name == null) || (name.equals(""))) {
237 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
239 allOfOne.getMatch().add(createMatch("PolicyName", name));
240 AllOfType allOf = new AllOfType();
242 // Match for ConfigName
243 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
244 // Match for riskType
245 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
246 // Match for riskLevel
247 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
248 // Match for riskguard
249 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
251 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
252 AnyOfType anyOf = new AnyOfType();
253 anyOf.getAllOf().add(allOfOne);
254 anyOf.getAllOf().add(allOf);
256 TargetType target = new TargetType();
257 target.getAnyOf().add(anyOf);
259 // Adding the target to the policy element
260 configPolicy.setTarget(target);
262 RuleType rule = new RuleType();
263 rule.setRuleId(policyAdapter.getRuleID());
264 rule.setEffect(EffectType.PERMIT);
266 // Create Target in Rule
267 AllOfType allOfInRule = new AllOfType();
269 // Creating match for ACCESS in rule target
270 MatchType accessMatch = new MatchType();
271 AttributeValueType accessAttributeValue = new AttributeValueType();
272 accessAttributeValue.setDataType(STRING_DATATYPE);
273 accessAttributeValue.getContent().add("ACCESS");
274 accessMatch.setAttributeValue(accessAttributeValue);
275 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
276 URI accessURI = null;
278 accessURI = new URI(ACTION_ID);
279 } catch (URISyntaxException e) {
280 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
282 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
283 accessAttributeDesignator.setDataType(STRING_DATATYPE);
284 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
285 accessMatch.setAttributeDesignator(accessAttributeDesignator);
286 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
288 // Creating Config Match in rule Target
289 MatchType configMatch = new MatchType();
290 AttributeValueType configAttributeValue = new AttributeValueType();
291 configAttributeValue.setDataType(STRING_DATATYPE);
293 configAttributeValue.getContent().add("Config");
295 configMatch.setAttributeValue(configAttributeValue);
296 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
297 URI configURI = null;
299 configURI = new URI(RESOURCE_ID);
300 } catch (URISyntaxException e) {
301 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
304 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
305 configAttributeDesignator.setDataType(STRING_DATATYPE);
306 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
307 configMatch.setAttributeDesignator(configAttributeDesignator);
308 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
310 allOfInRule.getMatch().add(accessMatch);
311 allOfInRule.getMatch().add(configMatch);
313 AnyOfType anyOfInRule = new AnyOfType();
314 anyOfInRule.getAllOf().add(allOfInRule);
316 TargetType targetInRule = new TargetType();
317 targetInRule.getAnyOf().add(anyOfInRule);
319 rule.setTarget(targetInRule);
320 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
322 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
323 policyAdapter.setPolicyData(configPolicy);
326 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
328 setPreparedToSave(true);
332 // Data required for Advice part is setting here.
333 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
335 //Firewall Config ID Assignment
336 AdviceExpressionsType advices = new AdviceExpressionsType();
337 AdviceExpressionType advice = new AdviceExpressionType();
338 advice.setAdviceId("firewallConfigID");
339 advice.setAppliesTo(EffectType.PERMIT);
341 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
342 assignment1.setAttributeId("type");
343 assignment1.setCategory(CATEGORY_RESOURCE);
344 assignment1.setIssuer("");
345 AttributeValueType configNameAttributeValue = new AttributeValueType();
346 configNameAttributeValue.setDataType(STRING_DATATYPE);
347 configNameAttributeValue.getContent().add("Configuration");
348 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
349 advice.getAttributeAssignmentExpression().add(assignment1);
351 // For Config file Url if configurations are provided.
353 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
354 assignment2.setAttributeId("URLID");
355 assignment2.setCategory(CATEGORY_RESOURCE);
356 assignment2.setIssuer("");
357 AttributeValueType AttributeValue = new AttributeValueType();
358 AttributeValue.setDataType(URI_DATATYPE);
359 if (policyName.endsWith(".xml")) {
360 policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
362 String content = CONFIG_URL + "/Config/" + policyName + ".json";
364 AttributeValue.getContent().add(content);
365 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
366 advice.getAttributeAssignmentExpression().add(assignment2);
368 //Policy Name Assignment
369 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
370 assignment3.setAttributeId("PolicyName");
371 assignment3.setCategory(CATEGORY_RESOURCE);
372 assignment3.setIssuer("");
373 AttributeValueType attributeValue3 = new AttributeValueType();
374 attributeValue3.setDataType(STRING_DATATYPE);
375 fileName = FilenameUtils.removeExtension(fileName);
376 fileName = fileName + ".xml";
377 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
378 if ((name == null) || (name.equals(""))) {
379 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
381 attributeValue3.getContent().add(name);
382 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
383 advice.getAttributeAssignmentExpression().add(assignment3);
385 //Version Number Assignment
386 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
387 assignment4.setAttributeId("VersionNumber");
388 assignment4.setCategory(CATEGORY_RESOURCE);
389 assignment4.setIssuer("");
390 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
391 configNameAttributeValue4.setDataType(STRING_DATATYPE);
392 configNameAttributeValue4.getContent().add(Integer.toString(version));
393 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
394 advice.getAttributeAssignmentExpression().add(assignment4);
396 //Onap Name Assignment
397 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
398 assignment5.setAttributeId("matching:" + ONAPID);
399 assignment5.setCategory(CATEGORY_RESOURCE);
400 assignment5.setIssuer("");
401 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
402 configNameAttributeValue5.setDataType(STRING_DATATYPE);
403 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
404 advice.getAttributeAssignmentExpression().add(assignment5);
406 //Config Name Assignment
407 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
408 assignment6.setAttributeId("matching:" + CONFIGID);
409 assignment6.setCategory(CATEGORY_RESOURCE);
410 assignment6.setIssuer("");
411 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
412 configNameAttributeValue6.setDataType(STRING_DATATYPE);
413 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
414 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
415 advice.getAttributeAssignmentExpression().add(assignment6);
418 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
419 assignment7.setAttributeId("RiskType");
420 assignment7.setCategory(CATEGORY_RESOURCE);
421 assignment7.setIssuer("");
423 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
424 configNameAttributeValue7.setDataType(STRING_DATATYPE);
425 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
426 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
428 advice.getAttributeAssignmentExpression().add(assignment7);
430 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
431 assignment8.setAttributeId("RiskLevel");
432 assignment8.setCategory(CATEGORY_RESOURCE);
433 assignment8.setIssuer("");
435 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
436 configNameAttributeValue8.setDataType(STRING_DATATYPE);
437 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
438 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
440 advice.getAttributeAssignmentExpression().add(assignment8);
442 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
443 assignment9.setAttributeId("guard");
444 assignment9.setCategory(CATEGORY_RESOURCE);
445 assignment9.setIssuer("");
447 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
448 configNameAttributeValue9.setDataType(STRING_DATATYPE);
449 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
450 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
452 advice.getAttributeAssignmentExpression().add(assignment9);
454 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
455 assignment10.setAttributeId("TTLDate");
456 assignment10.setCategory(CATEGORY_RESOURCE);
457 assignment10.setIssuer("");
459 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
460 configNameAttributeValue10.setDataType(STRING_DATATYPE);
461 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
462 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
464 advice.getAttributeAssignmentExpression().add(assignment10);
465 advices.getAdviceExpression().add(advice);
470 private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
471 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
472 JsonObject json = null;
473 if (jsonBody != null) {
475 //Read jsonBody to JsonObject
476 json = stringToJson(jsonBody);
478 JsonArray firewallRules = null;
479 JsonArray serviceGroup = null;
480 JsonArray addressGroup = null;
481 //insert data into tables
483 firewallRules = json.getJsonArray("firewallRuleList");
484 serviceGroup = json.getJsonArray("serviceGroups");
485 addressGroup = json.getJsonArray("addressGroups");
487 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
489 if (firewallRules != null) {
490 for(int i = 0;i<firewallRules.size();i++) {
492 * Populate ArrayLists with values from the JSON
494 //create the JSON object from the JSON Array for each iteration through the for loop
495 JsonObject ruleListobj = firewallRules.getJsonObject(i);
497 //get values from JSON fields of firewallRulesList Array
498 String ruleName = ruleListobj.get("ruleName").toString();
499 String action = ruleListobj.get("action").toString();
500 String description = ruleListobj.get("description").toString();
501 List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
502 if(result != null && !result.isEmpty()){
503 TermList termEntry = (TermList) result.get(0);
504 dbConnection.delete(termEntry);
507 //getting fromZone Array field from the firewallRulesList
508 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
509 String fromZoneString = null;
511 for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) {
512 String value = fromZoneArray.get(fromZoneIndex).toString();
513 value = value.replace("\"", "");
514 if (fromZoneString != null) {
515 fromZoneString = fromZoneString.concat(",").concat(value);
517 fromZoneString = value;
520 String fromZoneInsert = "'"+fromZoneString+"'";
522 //getting toZone Array field from the firewallRulesList
523 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
524 String toZoneString = null;
525 for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) {
526 String value = toZoneArray.get(toZoneIndex).toString();
527 value = value.replace("\"", "");
528 if (toZoneString != null) {
529 toZoneString = toZoneString.concat(",").concat(value);
531 toZoneString = value;
534 String toZoneInsert = "'"+toZoneString+"'";
536 //getting sourceList Array fields from the firewallRulesList
537 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
538 String srcListString = null;
539 for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) {
540 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
541 String type = srcListObj.get("type").toString().replace("\"", "");
544 if(type.equals("REFERENCE")||type.equals("GROUP")){
545 value = srcListObj.get("name").toString();
546 } else if (type.equalsIgnoreCase("ANY")){
549 value = srcListObj.get("value").toString();
552 srcListString = getLeftOrRight(srcListString, value);
555 String srcListInsert = "'"+srcListString+"'";
557 //getting destinationList Array fields from the firewallRulesList
558 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
559 String destListString = null;
560 for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) {
561 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
562 String type = destListObj.get("type").toString().replace("\"", "");
565 if(type.equals("REFERENCE")||type.equals("GROUP")){
566 value = destListObj.get("name").toString();
567 } else if (type.equalsIgnoreCase("ANY")){
570 value = destListObj.get("value").toString();
573 destListString = getLeftOrRight(destListString, value);
575 String destListInsert = "'"+destListString+"'";
577 //getting destServices Array fields from the firewallRulesList
578 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
579 String destPortListString = null;
580 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
581 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
582 String type = destServicesObj.get("type").toString().replace("\"", "");
585 if(type.equals("REFERENCE")||type.equals("GROUP")){
586 value = destServicesObj.get("name").toString();
587 } else if (type.equalsIgnoreCase("ANY")){
590 value = destServicesObj.get("value").toString();
593 destPortListString = getLeftOrRight(destPortListString, value);
595 String destPortListInsert = "'"+destPortListString+"'";
598 * Create Queries to INSERT data into database tables and execute
600 UserInfo userInfo = new UserInfo();
601 userInfo.setUserLoginId("API");
602 userInfo.setUserName("API");
604 TermList termEntry = new TermList();
605 termEntry.setTermName(ruleName);
606 termEntry.setSrcIPList(srcListInsert);
607 termEntry.setDestIPList(destListInsert);
608 termEntry.setProtocolList("null");
609 termEntry.setPortList("null");
610 termEntry.setSrcPortList("null");
611 termEntry.setDestPortList(destPortListInsert);
612 termEntry.setAction(action);
613 termEntry.setDescription(description);
614 termEntry.setFromZones(fromZoneInsert);
615 termEntry.setToZones(toZoneInsert);
616 termEntry.setUserCreatedBy(userInfo);
617 dbConnection.save(termEntry);
619 saveActionListToDb(dbConnection, action);
624 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
626 if (serviceGroup != null) {
627 for(int i = 0; i < serviceGroup.size() ; i++) {
629 * Populate ArrayLists with values from the JSON
631 //create the JSON object from the JSON Array for each iteration through the for loop
632 JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
634 String serviceListName = svcGroupListobj.get("name").toString();
635 String description = null;
636 if (svcGroupListobj.containsKey("description")){
637 description = svcGroupListobj.get("description").toString();
640 //getting members Array from the serviceGroup
641 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
643 //String type = svcGroupListobj.get("type").toString();
644 Boolean isServiceGroup = false;
645 if (membersArray!=null){
646 String membersType = membersArray.getJsonObject(0).get("type").toString();
647 if (membersType.contains("REFERENCE")) {
648 isServiceGroup = true;
652 //Insert values into GROUPSERVICELIST table if name begins with Group
653 if (isServiceGroup) {
654 saveGroupServiceListTableToDb(dbConnection, serviceListName, membersArray);
655 } else { //Insert JSON data serviceList table, protollist table, and portlist table
656 String type = svcGroupListobj.get("type").toString();
657 String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
658 String ports = svcGroupListobj.get("ports").toString();
661 * Create Queries to INSERT data into database table and execute
663 saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, ports);
665 saveProtocolListToDb(dbConnection, transportProtocol);
667 savePortListToDb(dbConnection, ports);
673 * Inserting addressGroup data into the ADDRESSGROUP table
675 if (addressGroup != null) {
676 for(int i = 0; i < addressGroup.size(); i++) {
678 * Populate ArrayLists with values from the JSON
680 //create the JSON object from the JSON Array for each iteration through the for loop
681 JsonObject addressGroupObj = addressGroup.getJsonObject(i);
683 //create JSON array for members
684 JsonArray membersArray = addressGroupObj.getJsonArray("members");
685 String addressGroupName = addressGroupObj.get("name").toString();
687 String description = null;
688 if (addressGroupObj.containsKey("description")){
689 description = addressGroupObj.get("description").toString();
692 String prefixIP = null;
694 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
695 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
696 //String value = membersObj.get("value").toString();
697 type = membersObj.get("type").toString().replace("\"", "");
700 prefixIP = getName(prefixIP, membersObj, type);
702 String prefixList = "'"+prefixIP+"'";
704 Boolean isAddressGroup = type.contains("REFERENCE");
706 if (isAddressGroup) {
707 saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
709 savePrefixListToDb(dbConnection, addressGroupName, description, prefixList);
713 removeDuplicateValuesFromLookup(dbConnection);
714 }catch (Exception e) {
715 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
727 * Remove duplicate values from 'lookup' dictionary tables
729 private void removeDuplicateValuesFromLookup(CommonClassDaoImpl dbConnection) {
730 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
731 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
732 dbConnection.updateQuery(protoDelete);
735 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
736 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
737 dbConnection.updateQuery(portListDelete);
740 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
741 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
742 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
743 dbConnection.updateQuery(prefixListDelete);
746 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
747 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
748 + "groupservicelist.serviceList = g1.serviceList; ";
749 dbConnection.updateQuery(groupServiceDelete);
752 private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, JsonArray membersArray) {
754 for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) {
755 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
756 String type = membersObj.get("type").toString().replace("\"", "");
758 name = getName(name, membersObj, type);
760 String nameInsert = "'"+name+"'";
761 GroupServiceList groupServiceEntry = new GroupServiceList();
762 groupServiceEntry.setGroupName(serviceListName);
763 groupServiceEntry.setServiceList(nameInsert);
764 dbConnection.save(groupServiceEntry);
767 private String getName(String name, JsonObject membersObj, String type) {
769 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
770 value = membersObj.get("name").toString();
771 } else if (type.equalsIgnoreCase("ANY")){
774 value = membersObj.get("value").toString();
777 name = getLeftOrRight(name, value);
781 private String getLeftOrRight(String name, String value) {
783 value = value.replace("\"", "");
787 name = name.concat(",").concat(value);
789 name = value.replace("\"", "");;
795 private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
796 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
797 JsonObject oldJson = null;
798 JsonObject newJson = null;
800 if (jsonBody != null || prevJsonBody != null) {
802 oldJson = stringToJson(prevJsonBody);
803 newJson = stringToJson(jsonBody);
805 //if no changes to the json then return true
806 if (oldJson != null && oldJson.equals(newJson)) {
810 JsonArray firewallRules = null;
811 JsonArray serviceGroup = null;
812 JsonArray addressGroup = null;
814 firewallRules = newJson.getJsonArray("firewallRuleList");
815 serviceGroup = newJson.getJsonArray("serviceGroups");
816 addressGroup = newJson.getJsonArray("addressGroups");
818 //insert data into tables
820 JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
822 for (int i = 0; i<jsonDiff.size(); i++) {
823 //String path = jsonDiff.get(i).asText();
824 String jsonpatch = jsonDiff.get(i).toString();
826 JsonObject patchObj = stringToJson(jsonpatch);
828 String path = patchObj.get("path").toString().replace('"', ' ').trim();
830 if (path.contains("firewallRuleList")) {
832 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
834 for(int ri = 0; ri < firewallRules.size(); ri++) {
836 * Populate ArrayLists with values from the JSON
838 //create the JSON object from the JSON Array for each iteration through the for loop
839 JsonObject ruleListobj = firewallRules.getJsonObject(ri);
841 //get values from JSON fields of firewallRulesList Array
842 String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
843 String action = ruleListobj.get("action").toString().replace('"', '\'');
844 String description = ruleListobj.get("description").toString().replace('"', '\'');
846 List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
847 if(result != null && !result.isEmpty()){
848 TermList termEntry = (TermList) result.get(0);
849 dbConnection.delete(termEntry);
852 //getting fromZone Array field from the firewallRulesList
853 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
854 String fromZoneString = null;
856 for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) {
857 String value = fromZoneArray.get(fromZoneIndex).toString();
858 value = value.replace("\"", "");
860 if (fromZoneString != null) {
861 fromZoneString = fromZoneString.concat(",").concat(value);
864 fromZoneString = value;
868 String fromZoneInsert = "'"+fromZoneString+"'";
870 //getting toZone Array field from the firewallRulesList
871 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
872 String toZoneString = null;
875 for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
876 String value = toZoneArray.get(toZoneIndex).toString();
877 value = value.replace("\"", "");
879 if (toZoneString != null) {
880 toZoneString = toZoneString.concat(",").concat(value);
883 toZoneString = value;
887 String toZoneInsert = "'"+toZoneString+"'";
888 //getting sourceList Array fields from the firewallRulesList
889 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
890 String srcListString = null;
891 for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) {
892 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
893 String type = srcListObj.get("type").toString().replace("\"", "");
896 if(type.equals("REFERENCE")||type.equals("GROUP")){
897 value = srcListObj.get("name").toString();
898 } else if (type.equalsIgnoreCase("ANY")){
901 value = srcListObj.get("value").toString();
904 srcListString = getLeftOrRight(srcListString, value);
907 String srcListInsert = "'"+srcListString+"'";
909 //getting destinationList Array fields from the firewallRulesList
910 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
911 String destListString = null;
912 for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) {
913 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
914 String type = destListObj.get("type").toString().replace("\"", "");
917 if(type.equals("REFERENCE")||type.equals("GROUP")){
918 value = destListObj.get("name").toString();
919 } else if (type.equalsIgnoreCase("ANY")){
922 value = destListObj.get("value").toString();
925 destListString = getLeftOrRight(destListString, value);
927 String destListInsert = "'"+destListString+"'";
929 //getting destServices Array fields from the firewallRulesList
930 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
931 String destPortListString = null;
932 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
933 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
934 String type = destServicesObj.get("type").toString().replace("\"", "");
937 if(type.equals("REFERENCE")||type.equals("GROUP")){
938 value = destServicesObj.get("name").toString();
939 } else if (type.equalsIgnoreCase("ANY")){
942 value = destServicesObj.get("value").toString();
945 destPortListString = getLeftOrRight(destPortListString, value);
947 String destPortListInsert = "'"+destPortListString+"'";
950 * Create Queries to INSERT data into database tables and execute
952 UserInfo userInfo = new UserInfo();
953 userInfo.setUserLoginId("API");
954 userInfo.setUserName("API");
956 TermList termEntry = new TermList();
957 termEntry.setTermName(ruleName);
958 termEntry.setSrcIPList(srcListInsert);
959 termEntry.setDestIPList(destListInsert);
960 termEntry.setProtocolList("null");
961 termEntry.setPortList("null");
962 termEntry.setSrcPortList("null");
963 termEntry.setDestPortList(destPortListInsert);
964 termEntry.setAction(action);
965 termEntry.setDescription(description);
966 termEntry.setFromZones(fromZoneInsert);
967 termEntry.setToZones(toZoneInsert);
968 termEntry.setUserCreatedBy(userInfo);
969 dbConnection.save(termEntry);
971 List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action);
972 if(actionResult == null || actionResult.isEmpty()){
973 saveActionListToDb(dbConnection, action);
978 if (path.contains("serviceGroups")) {
980 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
982 for(int si = 0; si < serviceGroup.size(); si++) {
984 * Populate ArrayLists with values from the JSON
986 //create the JSON object from the JSON Array for each iteration through the for loop
987 JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
989 String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');
991 String description = null;
992 if (svcGroupListobj.containsKey("description")){
993 description = svcGroupListobj.get("description").toString().replace('"', '\'');
996 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
998 Boolean isServiceGroup = false;
999 if (membersArray!=null){
1000 String membersType = membersArray.getJsonObject(0).get("type").toString();
1001 if (membersType.contains("REFERENCE")) {
1002 isServiceGroup = true;
1006 //Insert values into GROUPSERVICELIST table if name begins with Group
1007 if (isServiceGroup) {
1008 List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName);
1009 if(result != null && !result.isEmpty()){
1010 GroupServiceList groupEntry = (GroupServiceList) result.get(0);
1011 dbConnection.delete(groupEntry);
1014 saveGroupServiceListTableToDb(dbConnection, groupName, membersArray);
1015 } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
1016 String type = svcGroupListobj.get("type").toString().replace('"', '\'');
1017 String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
1018 String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
1020 List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName);
1021 if(result != null && !result.isEmpty()){
1022 ServiceList serviceEntry = (ServiceList) result.get(0);
1023 dbConnection.delete(serviceEntry);
1026 saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, ports);
1028 List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
1029 if(protocolResult == null || protocolResult.isEmpty()){
1030 saveProtocolListToDb(dbConnection, transportProtocol);
1033 List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports);
1034 if(portResult == null || portResult.isEmpty()){
1035 savePortListToDb(dbConnection, ports);
1041 if (path.contains("addressGroups")) {
1043 * Inserting addressGroup data into the ADDRESSGROUP table
1045 for(int ai=0; ai < addressGroup.size() ; ai++) {
1048 * Populate ArrayLists with values from the JSON
1050 //create the JSON object from the JSON Array for each iteration through the for loop
1051 JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
1053 //create JSON array for members
1054 JsonArray membersArray = addressGroupObj.getJsonArray("members");
1055 String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
1057 String description = null;
1058 if (addressGroupObj.containsKey("description")){
1059 description = addressGroupObj.get("description").toString().replace('"', '\'');
1062 String prefixIP = null;
1064 for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) {
1065 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1066 type = membersObj.get("type").toString().replace("\"", "");
1068 String value = null;
1069 prefixIP = getName(prefixIP, membersObj, type);
1072 String prefixList = "'"+prefixIP+"'";
1073 Boolean isAddressGroup = type.contains("REFERENCE");
1075 if (isAddressGroup) {
1076 List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
1077 if(result != null && !result.isEmpty()){
1078 AddressGroup addressGroupEntry = (AddressGroup) result.get(0);
1079 dbConnection.delete(addressGroupEntry);
1081 saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
1083 List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
1084 if(result != null && !result.isEmpty()){
1085 PrefixList prefixListEntry = (PrefixList) result.get(0);
1086 dbConnection.delete(prefixListEntry);
1088 savePrefixListToDb(dbConnection, addressGroupName, description, prefixList);
1093 removeDuplicateValuesFromLookup(dbConnection);
1094 }catch (Exception e) {
1095 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1105 private void saveActionListToDb(CommonClassDaoImpl dbConnection, String action) {
1106 ActionList actionEntry = new ActionList();
1107 actionEntry.setActionName(action);
1108 actionEntry.setDescription(action);
1109 dbConnection.save(actionEntry);
1112 private void savePortListToDb(CommonClassDaoImpl dbConnection, String ports) {
1113 PortList portEntry = new PortList();
1114 portEntry.setPortName(ports);
1115 portEntry.setDescription(ports);
1116 dbConnection.save(portEntry);
1119 private void saveProtocolListToDb(CommonClassDaoImpl dbConnection, String transportProtocol) {
1120 ProtocolList protocolEntry = new ProtocolList();
1121 protocolEntry.setProtocolName(transportProtocol);
1122 protocolEntry.setDescription(transportProtocol);
1123 dbConnection.save(protocolEntry);
1126 private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, String transportProtocol, String ports) {
1127 ServiceList serviceListEntry = new ServiceList();
1128 serviceListEntry.setServiceName(groupName);
1129 serviceListEntry.setServiceDescription(description);
1130 serviceListEntry.setServiceType(type);
1131 serviceListEntry.setServiceTransProtocol(transportProtocol);
1132 serviceListEntry.setServiceAppProtocol("null");
1133 serviceListEntry.setServicePorts(ports);
1134 dbConnection.save(serviceListEntry);
1137 private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
1138 PrefixList newPrefixList = new PrefixList();
1139 newPrefixList.setPrefixListName(addressGroupName);
1140 newPrefixList.setDescription(description);
1141 newPrefixList.setPrefixListValue(prefixList);
1142 dbConnection.save(newPrefixList);
1145 private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
1146 AddressGroup newAddressGroup = new AddressGroup();
1147 newAddressGroup.setGroupName(addressGroupName);
1148 newAddressGroup.setDescription(description);
1149 newAddressGroup.setServiceList(prefixList);
1150 dbConnection.save(newAddressGroup);
1153 private JsonObject stringToJson(String jsonString) {
1154 //Read jsonBody to JsonObject
1155 StringReader in = new StringReader(jsonString);
1156 JsonReader jsonReader = Json.createReader(in);
1157 JsonObject json = jsonReader.readObject();
1162 private JsonNode createPatch(String json, String oldJson) {
1163 JsonNode oldJason = null;
1164 JsonNode updatedJason = null;
1167 oldJason = JsonLoader.fromString(oldJson);
1168 updatedJason = JsonLoader.fromString(json);
1169 } catch (IOException e) {
1170 LOGGER.error("Exception Occured"+e);
1172 return JsonDiff.asJson(oldJason, updatedJason);
1176 public Object getCorrectPolicyDataObject() {
1177 return policyAdapter.getPolicyData();