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;
30 import java.io.BufferedWriter;
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.io.StringReader;
36 import java.net.URISyntaxException;
37 import java.nio.charset.Charset;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.sql.SQLException;
42 import java.util.HashMap;
43 import java.util.List;
46 import javax.json.Json;
47 import javax.json.JsonArray;
48 import javax.json.JsonObject;
49 import javax.json.JsonReader;
50 import javax.script.SimpleBindings;
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.onap.policy.common.logging.eelf.MessageCodes;
68 import org.onap.policy.common.logging.eelf.PolicyLogger;
69 import org.onap.policy.common.logging.flexlogger.FlexLogger;
70 import org.onap.policy.common.logging.flexlogger.Logger;
71 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
72 import org.onap.policy.rest.adapter.PolicyRestAdapter;
73 import org.onap.policy.rest.dao.CommonClassDao;
74 import org.onap.policy.rest.jpa.ActionList;
75 import org.onap.policy.rest.jpa.AddressGroup;
76 import org.onap.policy.rest.jpa.GroupServiceList;
77 import org.onap.policy.rest.jpa.PolicyEntity;
78 import org.onap.policy.rest.jpa.PortList;
79 import org.onap.policy.rest.jpa.PrefixList;
80 import org.onap.policy.rest.jpa.ProtocolList;
81 import org.onap.policy.rest.jpa.ServiceList;
82 import org.onap.policy.rest.jpa.TermList;
83 import org.onap.policy.rest.jpa.UserInfo;
84 import org.springframework.beans.factory.annotation.Autowired;
85 import org.springframework.stereotype.Component;
88 public class FirewallConfigPolicy extends Policy {
90 private static final Logger LOGGER = FlexLogger.getLogger(FirewallConfigPolicy.class);
92 public FirewallConfigPolicy() {
96 private static CommonClassDao commonClassDao;
99 public FirewallConfigPolicy(CommonClassDao commonClassDao) {
100 FirewallConfigPolicy.commonClassDao = commonClassDao;
103 public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) {
104 this.policyAdapter = policyAdapter;
105 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
108 // Saving the Configurations file at server location for config policy.
109 protected void saveConfigurations(String policyName, String jsonBody) {
110 String configurationName = policyName;
111 if (configurationName.endsWith(".xml")) {
112 configurationName = configurationName.replace(".xml", "");
114 String fileName = CONFIG_HOME + File.separator + configurationName + ".json";
115 try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
117 if (LOGGER.isDebugEnabled()) {
118 LOGGER.debug("Configuration is succesfully saved");
120 } catch (IOException e) {
121 LOGGER.error("Save of configuration to file" + fileName + "failed", 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 PAPException {
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()) {
149 updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
152 dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
153 } catch (SQLException e) {
154 throw new PAPException(e);
162 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
164 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
166 // remove the new json file
167 String jsonBody = policyAdapter.getPrevJsonBody();
168 if (jsonBody != null) {
169 saveConfigurations(policyName, jsonBody);
171 saveConfigurations(policyName, "");
173 successMap.put("fwdberror", "DB UPDATE");
179 // This is the method for preparing the policy for saving. We have broken it out
180 // separately because the fully configured policy is used for multiple things
182 public boolean prepareToSave() throws PAPException {
184 if (isPreparedToSave()) {
185 // we have already done this
190 String policyID = policyAdapter.getPolicyID();
191 version = policyAdapter.getHighestVersion();
193 // Create the Instance for pojo, PolicyType object is used in marshaling.
194 if ("Config".equals(policyAdapter.getPolicyType())) {
195 PolicyType policyConfig = new PolicyType();
197 policyConfig.setVersion(Integer.toString(version));
198 policyConfig.setPolicyId(policyID);
199 policyConfig.setTarget(new TargetType());
200 policyAdapter.setData(policyConfig);
202 policyName = policyAdapter.getNewFileName();
204 // String oldPolicyName = policyName.replace(".xml", "");
205 String scope = policyName.substring(0, policyName.indexOf('.'));
206 String dbPolicyName = policyName.substring(policyName.indexOf('.') + 1).replace(".xml", "");
208 int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.') + 1));
209 dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.') + 1);
210 if (oldversion > 1) {
211 oldversion = oldversion - 1;
212 dbPolicyName = dbPolicyName + oldversion + ".xml";
214 String createPolicyQuery = "SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName";
215 SimpleBindings params = new SimpleBindings();
216 params.put("scope", scope);
217 params.put("policyName", dbPolicyName);
218 List<?> createPolicyQueryList = commonClassDao.getDataByQuery(createPolicyQuery, params);
219 if (!createPolicyQueryList.isEmpty()) {
220 PolicyEntity entitydata = (PolicyEntity) createPolicyQueryList.get(0);
221 policyAdapter.setPrevJsonBody(entitydata.getConfigurationData().getConfigBody());
223 if (policyAdapter.getData() != null) {
224 String jsonBody = policyAdapter.getJsonBody();
225 saveConfigurations(policyName, jsonBody);
227 // Make sure the filename ends with an extension
228 if (!policyName.endsWith(".xml")) {
229 policyName = policyName + ".xml";
232 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
234 configPolicy.setDescription(policyAdapter.getPolicyDescription());
236 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
238 AllOfType allOfOne = new AllOfType();
239 String fileName = policyAdapter.getNewFileName();
240 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
241 if ((name == null) || (name.equals(""))) {
242 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
244 allOfOne.getMatch().add(createMatch("PolicyName", name));
245 AllOfType allOf = new AllOfType();
247 // Match for ConfigName
248 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
249 // Match for riskType
250 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
251 // Match for riskLevel
252 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
253 // Match for riskguard
254 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
256 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
257 AnyOfType anyOf = new AnyOfType();
258 anyOf.getAllOf().add(allOfOne);
259 anyOf.getAllOf().add(allOf);
261 TargetType target = new TargetType();
262 target.getAnyOf().add(anyOf);
264 // Adding the target to the policy element
265 configPolicy.setTarget(target);
267 RuleType rule = new RuleType();
268 rule.setRuleId(policyAdapter.getRuleID());
269 rule.setEffect(EffectType.PERMIT);
271 // Create Target in Rule
272 AllOfType allOfInRule = new AllOfType();
274 // Creating match for ACCESS in rule target
275 MatchType accessMatch = new MatchType();
276 AttributeValueType accessAttributeValue = new AttributeValueType();
277 accessAttributeValue.setDataType(STRING_DATATYPE);
278 accessAttributeValue.getContent().add("ACCESS");
279 accessMatch.setAttributeValue(accessAttributeValue);
280 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
281 URI accessURI = null;
283 accessURI = new URI(ACTION_ID);
284 } catch (URISyntaxException e) {
285 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy",
286 "Exception creating ACCESS URI");
288 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
289 accessAttributeDesignator.setDataType(STRING_DATATYPE);
290 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
291 accessMatch.setAttributeDesignator(accessAttributeDesignator);
292 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
294 // Creating Config Match in rule Target
295 MatchType configMatch = new MatchType();
296 AttributeValueType configAttributeValue = new AttributeValueType();
297 configAttributeValue.setDataType(STRING_DATATYPE);
299 configAttributeValue.getContent().add("Config");
301 configMatch.setAttributeValue(configAttributeValue);
302 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
303 URI configURI = null;
305 configURI = new URI(RESOURCE_ID);
306 } catch (URISyntaxException e) {
307 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy",
308 "Exception creating Config URI");
311 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
312 configAttributeDesignator.setDataType(STRING_DATATYPE);
313 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
314 configMatch.setAttributeDesignator(configAttributeDesignator);
315 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
317 allOfInRule.getMatch().add(accessMatch);
318 allOfInRule.getMatch().add(configMatch);
320 AnyOfType anyOfInRule = new AnyOfType();
321 anyOfInRule.getAllOf().add(allOfInRule);
323 TargetType targetInRule = new TargetType();
324 targetInRule.getAnyOf().add(anyOfInRule);
326 rule.setTarget(targetInRule);
327 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
329 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
330 policyAdapter.setPolicyData(configPolicy);
333 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
335 setPreparedToSave(true);
339 // Data required for Advice part is setting here.
340 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
342 // Firewall Config ID Assignment
343 AdviceExpressionsType advices = new AdviceExpressionsType();
344 AdviceExpressionType advice = new AdviceExpressionType();
345 advice.setAdviceId("firewallConfigID");
346 advice.setAppliesTo(EffectType.PERMIT);
348 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
349 assignment1.setAttributeId("type");
350 assignment1.setCategory(CATEGORY_RESOURCE);
351 assignment1.setIssuer("");
352 AttributeValueType configNameAttributeValue = new AttributeValueType();
353 configNameAttributeValue.setDataType(STRING_DATATYPE);
354 configNameAttributeValue.getContent().add("Configuration");
355 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
356 advice.getAttributeAssignmentExpression().add(assignment1);
358 // For Config file Url if configurations are provided.
360 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
361 assignment2.setAttributeId("URLID");
362 assignment2.setCategory(CATEGORY_RESOURCE);
363 assignment2.setIssuer("");
364 AttributeValueType AttributeValue = new AttributeValueType();
365 AttributeValue.setDataType(URI_DATATYPE);
366 if (policyName.endsWith(".xml")) {
367 policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
369 String content = CONFIG_URL + "/Config/" + policyName + ".json";
371 AttributeValue.getContent().add(content);
372 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
373 advice.getAttributeAssignmentExpression().add(assignment2);
375 // Policy Name Assignment
376 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
377 assignment3.setAttributeId("PolicyName");
378 assignment3.setCategory(CATEGORY_RESOURCE);
379 assignment3.setIssuer("");
380 AttributeValueType attributeValue3 = new AttributeValueType();
381 attributeValue3.setDataType(STRING_DATATYPE);
382 fileName = FilenameUtils.removeExtension(fileName);
383 fileName = fileName + ".xml";
384 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
385 if ((name == null) || (name.equals(""))) {
386 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
388 attributeValue3.getContent().add(name);
389 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
390 advice.getAttributeAssignmentExpression().add(assignment3);
392 // Version Number Assignment
393 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
394 assignment4.setAttributeId("VersionNumber");
395 assignment4.setCategory(CATEGORY_RESOURCE);
396 assignment4.setIssuer("");
397 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
398 configNameAttributeValue4.setDataType(STRING_DATATYPE);
399 configNameAttributeValue4.getContent().add(Integer.toString(version));
400 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
401 advice.getAttributeAssignmentExpression().add(assignment4);
403 // Onap Name Assignment
404 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
405 assignment5.setAttributeId("matching:" + ONAPID);
406 assignment5.setCategory(CATEGORY_RESOURCE);
407 assignment5.setIssuer("");
408 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
409 configNameAttributeValue5.setDataType(STRING_DATATYPE);
410 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
411 advice.getAttributeAssignmentExpression().add(assignment5);
413 // Config Name Assignment
414 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
415 assignment6.setAttributeId("matching:" + CONFIGID);
416 assignment6.setCategory(CATEGORY_RESOURCE);
417 assignment6.setIssuer("");
418 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
419 configNameAttributeValue6.setDataType(STRING_DATATYPE);
420 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
421 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
422 advice.getAttributeAssignmentExpression().add(assignment6);
425 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
426 assignment7.setAttributeId("RiskType");
427 assignment7.setCategory(CATEGORY_RESOURCE);
428 assignment7.setIssuer("");
430 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
431 configNameAttributeValue7.setDataType(STRING_DATATYPE);
432 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
433 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
435 advice.getAttributeAssignmentExpression().add(assignment7);
437 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
438 assignment8.setAttributeId("RiskLevel");
439 assignment8.setCategory(CATEGORY_RESOURCE);
440 assignment8.setIssuer("");
442 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
443 configNameAttributeValue8.setDataType(STRING_DATATYPE);
444 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
445 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
447 advice.getAttributeAssignmentExpression().add(assignment8);
449 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
450 assignment9.setAttributeId("guard");
451 assignment9.setCategory(CATEGORY_RESOURCE);
452 assignment9.setIssuer("");
454 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
455 configNameAttributeValue9.setDataType(STRING_DATATYPE);
456 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
457 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
459 advice.getAttributeAssignmentExpression().add(assignment9);
461 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
462 assignment10.setAttributeId("TTLDate");
463 assignment10.setCategory(CATEGORY_RESOURCE);
464 assignment10.setIssuer("");
466 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
467 configNameAttributeValue10.setDataType(STRING_DATATYPE);
468 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
469 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
471 advice.getAttributeAssignmentExpression().add(assignment10);
472 advices.getAdviceExpression().add(advice);
476 private Boolean insertFirewallDicionaryData(String jsonBody) throws SQLException {
477 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
478 JsonObject json = null;
479 if (jsonBody != null) {
481 // Read jsonBody to JsonObject
482 json = stringToJson(jsonBody);
484 JsonArray firewallRules = null;
485 JsonArray serviceGroup = null;
486 JsonArray addressGroup = null;
487 // insert data into tables
489 firewallRules = json.getJsonArray("firewallRuleList");
490 serviceGroup = json.getJsonArray("serviceGroups");
491 addressGroup = json.getJsonArray("addressGroups");
493 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
495 if (firewallRules != null) {
496 for (int i = 0; i < firewallRules.size(); i++) {
498 * Populate ArrayLists with values from the JSON
500 // create the JSON object from the JSON Array for each iteration through the for loop
501 JsonObject ruleListobj = firewallRules.getJsonObject(i);
503 // get values from JSON fields of firewallRulesList Array
504 String ruleName = ruleListobj.get("ruleName").toString();
505 String action = ruleListobj.get("action").toString();
506 String description = ruleListobj.get("description").toString();
507 List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
508 if (result != null && !result.isEmpty()) {
509 TermList termEntry = (TermList) result.get(0);
510 dbConnection.delete(termEntry);
513 // getting fromZone Array field from the firewallRulesList
514 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
515 String fromZoneString = null;
517 for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) {
518 String value = fromZoneArray.get(fromZoneIndex).toString();
519 value = value.replace("\"", "");
520 if (fromZoneString != null) {
521 fromZoneString = fromZoneString.concat(",").concat(value);
523 fromZoneString = value;
526 String fromZoneInsert = "'" + fromZoneString + "'";
528 // getting toZone Array field from the firewallRulesList
529 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
530 String toZoneString = null;
531 for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
532 String value = toZoneArray.get(toZoneIndex).toString();
533 value = value.replace("\"", "");
534 if (toZoneString != null) {
535 toZoneString = toZoneString.concat(",").concat(value);
537 toZoneString = value;
540 String toZoneInsert = "'" + toZoneString + "'";
542 // getting sourceList Array fields from the firewallRulesList
543 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
544 String srcListString = null;
545 for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) {
546 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
547 String type = srcListObj.get("type").toString().replace("\"", "");
550 if (type.equals("REFERENCE") || type.equals("GROUP")) {
551 value = srcListObj.get("name").toString();
552 } else if (type.equalsIgnoreCase("ANY")) {
555 value = srcListObj.get("value").toString();
558 srcListString = getLeftOrRight(srcListString, value);
561 String srcListInsert = "'" + srcListString + "'";
563 // getting destinationList Array fields from the firewallRulesList
564 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
565 String destListString = null;
566 for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) {
567 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
568 String type = destListObj.get("type").toString().replace("\"", "");
571 if (type.equals("REFERENCE") || type.equals("GROUP")) {
572 value = destListObj.get("name").toString();
573 } else if (type.equalsIgnoreCase("ANY")) {
576 value = destListObj.get("value").toString();
579 destListString = getLeftOrRight(destListString, value);
581 String destListInsert = "'" + destListString + "'";
583 // getting destServices Array fields from the firewallRulesList
584 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
585 String destPortListString = null;
586 for (int destPortListIndex = 0; destPortListIndex < destServicesArray
587 .size(); destPortListIndex++) {
588 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
589 String type = destServicesObj.get("type").toString().replace("\"", "");
592 if (type.equals("REFERENCE") || type.equals("GROUP")) {
593 value = destServicesObj.get("name").toString();
594 } else if (type.equalsIgnoreCase("ANY")) {
597 value = destServicesObj.get("value").toString();
600 destPortListString = getLeftOrRight(destPortListString, value);
602 String destPortListInsert = "'" + destPortListString + "'";
605 * Create Queries to INSERT data into database tables and execute
607 UserInfo userInfo = new UserInfo();
608 userInfo.setUserLoginId("API");
609 userInfo.setUserName("API");
611 TermList termEntry = new TermList();
612 termEntry.setTermName(ruleName);
613 termEntry.setSrcIPList(srcListInsert);
614 termEntry.setDestIPList(destListInsert);
615 termEntry.setProtocolList("null");
616 termEntry.setPortList("null");
617 termEntry.setSrcPortList("null");
618 termEntry.setDestPortList(destPortListInsert);
619 termEntry.setAction(action);
620 termEntry.setDescription(description);
621 termEntry.setFromZones(fromZoneInsert);
622 termEntry.setToZones(toZoneInsert);
623 termEntry.setUserCreatedBy(userInfo);
624 dbConnection.save(termEntry);
626 saveActionListToDb(dbConnection, action);
631 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
633 if (serviceGroup != null) {
634 for (int i = 0; i < serviceGroup.size(); i++) {
636 * Populate ArrayLists with values from the JSON
638 // create the JSON object from the JSON Array for each iteration through the for loop
639 JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
641 String serviceListName = svcGroupListobj.get("name").toString();
642 String description = null;
643 if (svcGroupListobj.containsKey("description")) {
644 description = svcGroupListobj.get("description").toString();
647 // getting members Array from the serviceGroup
648 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
650 // String type = svcGroupListobj.get("type").toString();
651 Boolean isServiceGroup = false;
652 if (membersArray != null) {
653 String membersType = membersArray.getJsonObject(0).get("type").toString();
654 if (membersType.contains("REFERENCE")) {
655 isServiceGroup = true;
659 // Insert values into GROUPSERVICELIST table if name begins with Group
660 if (isServiceGroup) {
661 saveGroupServiceListTableToDb(dbConnection, serviceListName, membersArray);
662 } else { // Insert JSON data serviceList table, protollist table, and portlist table
663 String type = svcGroupListobj.get("type").toString();
664 String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
665 String ports = svcGroupListobj.get("ports").toString();
668 * Create Queries to INSERT data into database table and execute
670 saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol,
673 saveProtocolListToDb(dbConnection, transportProtocol);
675 savePortListToDb(dbConnection, ports);
681 * Inserting addressGroup data into the ADDRESSGROUP table
683 if (addressGroup != null) {
684 for (int i = 0; i < addressGroup.size(); i++) {
686 * Populate ArrayLists with values from the JSON
688 // create the JSON object from the JSON Array for each iteration through the for loop
689 JsonObject addressGroupObj = addressGroup.getJsonObject(i);
691 // create JSON array for members
692 JsonArray membersArray = addressGroupObj.getJsonArray("members");
693 String addressGroupName = addressGroupObj.get("name").toString();
695 String description = null;
696 if (addressGroupObj.containsKey("description")) {
697 description = addressGroupObj.get("description").toString();
700 String prefixIP = null;
702 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
703 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
704 type = membersObj.get("type").toString().replace("\"", "");
706 prefixIP = getName(prefixIP, membersObj, type);
708 String prefixList = "'" + prefixIP + "'";
710 Boolean isAddressGroup = type.contains("REFERENCE");
712 if (isAddressGroup) {
713 saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
715 savePrefixListToDb(dbConnection, addressGroupName, description, prefixList);
719 removeDuplicateValuesFromLookup(dbConnection);
720 } catch (Exception e) {
721 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy",
722 "Exception getting Json values");
734 * Remove duplicate values from 'lookup' dictionary tables
736 private void removeDuplicateValuesFromLookup(CommonClassDaoImpl dbConnection) {
737 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
738 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
739 dbConnection.updateQuery(protoDelete);
742 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
743 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
744 dbConnection.updateQuery(portListDelete);
747 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
748 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
749 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
750 dbConnection.updateQuery(prefixListDelete);
753 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
754 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
755 + "groupservicelist.serviceList = g1.serviceList; ";
756 dbConnection.updateQuery(groupServiceDelete);
759 private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName,
760 JsonArray membersArray) {
762 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
763 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
764 String type = membersObj.get("type").toString().replace("\"", "");
766 name = getName(name, membersObj, type);
768 String nameInsert = "'" + name + "'";
769 GroupServiceList groupServiceEntry = new GroupServiceList();
770 groupServiceEntry.setGroupName(serviceListName);
771 groupServiceEntry.setServiceList(nameInsert);
772 dbConnection.save(groupServiceEntry);
775 private String getName(String name, JsonObject membersObj, String type) {
777 if (type.equals("REFERENCE") || type.equals("GROUP") || type.equals("SERVICE")) {
778 value = membersObj.get("name").toString();
779 } else if (type.equalsIgnoreCase("ANY")) {
782 value = membersObj.get("value").toString();
785 name = getLeftOrRight(name, value);
789 private String getLeftOrRight(String name, String value) {
791 value = value.replace("\"", "");
795 name = name.concat(",").concat(value);
797 name = value.replace("\"", "");;
802 private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
803 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
804 JsonObject oldJson = null;
805 JsonObject newJson = null;
807 if (jsonBody != null || prevJsonBody != null) {
809 oldJson = stringToJson(prevJsonBody);
810 newJson = stringToJson(jsonBody);
812 // if no changes to the json then return true
813 if (oldJson != null && oldJson.equals(newJson)) {
817 JsonArray firewallRules = null;
818 JsonArray serviceGroup = null;
819 JsonArray addressGroup = null;
821 firewallRules = newJson.getJsonArray("firewallRuleList");
822 serviceGroup = newJson.getJsonArray("serviceGroups");
823 addressGroup = newJson.getJsonArray("addressGroups");
825 // insert data into tables
827 JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
829 for (int i = 0; i < jsonDiff.size(); i++) {
830 // String path = jsonDiff.get(i).asText();
831 String jsonpatch = jsonDiff.get(i).toString();
833 JsonObject patchObj = stringToJson(jsonpatch);
835 String path = patchObj.get("path").toString().replace('"', ' ').trim();
837 if (path.contains("firewallRuleList")) {
839 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
841 for (int ri = 0; ri < firewallRules.size(); ri++) {
843 * Populate ArrayLists with values from the JSON
845 // create the JSON object from the JSON Array for each iteration through the for loop
846 JsonObject ruleListobj = firewallRules.getJsonObject(ri);
848 // get values from JSON fields of firewallRulesList Array
849 String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
850 String action = ruleListobj.get("action").toString().replace('"', '\'');
851 String description = ruleListobj.get("description").toString().replace('"', '\'');
853 List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
854 if (result != null && !result.isEmpty()) {
855 TermList termEntry = (TermList) result.get(0);
856 dbConnection.delete(termEntry);
859 // getting fromZone Array field from the firewallRulesList
860 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
861 String fromZoneString = null;
863 for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) {
864 String value = fromZoneArray.get(fromZoneIndex).toString();
865 value = value.replace("\"", "");
867 if (fromZoneString != null) {
868 fromZoneString = fromZoneString.concat(",").concat(value);
871 fromZoneString = value;
875 String fromZoneInsert = "'" + fromZoneString + "'";
877 // getting toZone Array field from the firewallRulesList
878 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
879 String toZoneString = null;
881 for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
882 String value = toZoneArray.get(toZoneIndex).toString();
883 value = value.replace("\"", "");
885 if (toZoneString != null) {
886 toZoneString = toZoneString.concat(",").concat(value);
889 toZoneString = value;
893 String toZoneInsert = "'" + toZoneString + "'";
894 // getting sourceList Array fields from the firewallRulesList
895 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
896 String srcListString = null;
897 for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) {
898 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
899 String type = srcListObj.get("type").toString().replace("\"", "");
902 if (type.equals("REFERENCE") || type.equals("GROUP")) {
903 value = srcListObj.get("name").toString();
904 } else if (type.equalsIgnoreCase("ANY")) {
907 value = srcListObj.get("value").toString();
910 srcListString = getLeftOrRight(srcListString, value);
913 String srcListInsert = "'" + srcListString + "'";
915 // getting destinationList Array fields from the firewallRulesList
916 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
917 String destListString = null;
918 for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) {
919 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
920 String type = destListObj.get("type").toString().replace("\"", "");
923 if (type.equals("REFERENCE") || type.equals("GROUP")) {
924 value = destListObj.get("name").toString();
925 } else if (type.equalsIgnoreCase("ANY")) {
928 value = destListObj.get("value").toString();
931 destListString = getLeftOrRight(destListString, value);
933 String destListInsert = "'" + destListString + "'";
935 // getting destServices Array fields from the firewallRulesList
936 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
937 String destPortListString = null;
938 for (int destPortListIndex = 0; destPortListIndex < destServicesArray
939 .size(); destPortListIndex++) {
940 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
941 String type = destServicesObj.get("type").toString().replace("\"", "");
944 if (type.equals("REFERENCE") || type.equals("GROUP")) {
945 value = destServicesObj.get("name").toString();
946 } else if (type.equalsIgnoreCase("ANY")) {
949 value = destServicesObj.get("value").toString();
952 destPortListString = getLeftOrRight(destPortListString, value);
954 String destPortListInsert = "'" + destPortListString + "'";
957 * Create Queries to INSERT data into database tables and execute
959 UserInfo userInfo = new UserInfo();
960 userInfo.setUserLoginId("API");
961 userInfo.setUserName("API");
963 TermList termEntry = new TermList();
964 termEntry.setTermName(ruleName);
965 termEntry.setSrcIPList(srcListInsert);
966 termEntry.setDestIPList(destListInsert);
967 termEntry.setProtocolList("null");
968 termEntry.setPortList("null");
969 termEntry.setSrcPortList("null");
970 termEntry.setDestPortList(destPortListInsert);
971 termEntry.setAction(action);
972 termEntry.setDescription(description);
973 termEntry.setFromZones(fromZoneInsert);
974 termEntry.setToZones(toZoneInsert);
975 termEntry.setUserCreatedBy(userInfo);
976 dbConnection.save(termEntry);
978 List<Object> actionResult =
979 dbConnection.getDataById(ActionList.class, "actionName", action);
980 if (actionResult == null || actionResult.isEmpty()) {
981 saveActionListToDb(dbConnection, action);
986 if (path.contains("serviceGroups")) {
988 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList
991 for (int si = 0; si < serviceGroup.size(); si++) {
993 * Populate ArrayLists with values from the JSON
995 // create the JSON object from the JSON Array for each iteration through the for loop
996 JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
998 String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');
1000 String description = null;
1001 if (svcGroupListobj.containsKey("description")) {
1002 description = svcGroupListobj.get("description").toString().replace('"', '\'');
1005 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
1007 Boolean isServiceGroup = false;
1008 if (membersArray != null) {
1009 String membersType = membersArray.getJsonObject(0).get("type").toString();
1010 if (membersType.contains("REFERENCE")) {
1011 isServiceGroup = true;
1015 // Insert values into GROUPSERVICELIST table if name begins with Group
1016 if (isServiceGroup) {
1017 List<Object> result =
1018 dbConnection.getDataById(GroupServiceList.class, "name", groupName);
1019 if (result != null && !result.isEmpty()) {
1020 GroupServiceList groupEntry = (GroupServiceList) result.get(0);
1021 dbConnection.delete(groupEntry);
1024 saveGroupServiceListTableToDb(dbConnection, groupName, membersArray);
1025 } else { // Insert JSON data serviceGroup table, protocollist table, and portlist table
1026 String type = svcGroupListobj.get("type").toString().replace('"', '\'');
1027 String transportProtocol =
1028 svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
1029 String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
1031 List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName);
1032 if (result != null && !result.isEmpty()) {
1033 ServiceList serviceEntry = (ServiceList) result.get(0);
1034 dbConnection.delete(serviceEntry);
1037 saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol,
1040 List<Object> protocolResult =
1041 dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
1042 if (protocolResult == null || protocolResult.isEmpty()) {
1043 saveProtocolListToDb(dbConnection, transportProtocol);
1046 List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports);
1047 if (portResult == null || portResult.isEmpty()) {
1048 savePortListToDb(dbConnection, ports);
1054 if (path.contains("addressGroups")) {
1056 * Inserting addressGroup data into the ADDRESSGROUP table
1058 for (int ai = 0; ai < addressGroup.size(); ai++) {
1061 * Populate ArrayLists with values from the JSON
1063 // create the JSON object from the JSON Array for each iteration through the for loop
1064 JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
1066 // create JSON array for members
1067 JsonArray membersArray = addressGroupObj.getJsonArray("members");
1068 String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
1070 String description = null;
1071 if (addressGroupObj.containsKey("description")) {
1072 description = addressGroupObj.get("description").toString().replace('"', '\'');
1075 String prefixIP = null;
1077 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
1078 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1079 type = membersObj.get("type").toString().replace("\"", "");
1081 prefixIP = getName(prefixIP, membersObj, type);
1084 String prefixList = "'" + prefixIP + "'";
1085 Boolean isAddressGroup = type.contains("REFERENCE");
1087 if (isAddressGroup) {
1088 List<Object> result =
1089 dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
1090 if (result != null && !result.isEmpty()) {
1091 AddressGroup addressGroupEntry = (AddressGroup) result.get(0);
1092 dbConnection.delete(addressGroupEntry);
1094 saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
1096 List<Object> result =
1097 dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
1098 if (result != null && !result.isEmpty()) {
1099 PrefixList prefixListEntry = (PrefixList) result.get(0);
1100 dbConnection.delete(prefixListEntry);
1102 savePrefixListToDb(dbConnection, addressGroupName, description, prefixList);
1107 removeDuplicateValuesFromLookup(dbConnection);
1108 } catch (Exception e) {
1109 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy",
1110 "Exception executing Firewall queries");
1120 private void saveActionListToDb(CommonClassDaoImpl dbConnection, String action) {
1121 ActionList actionEntry = new ActionList();
1122 actionEntry.setActionName(action);
1123 actionEntry.setDescription(action);
1124 dbConnection.save(actionEntry);
1127 private void savePortListToDb(CommonClassDaoImpl dbConnection, String ports) {
1128 PortList portEntry = new PortList();
1129 portEntry.setPortName(ports);
1130 portEntry.setDescription(ports);
1131 dbConnection.save(portEntry);
1134 private void saveProtocolListToDb(CommonClassDaoImpl dbConnection, String transportProtocol) {
1135 ProtocolList protocolEntry = new ProtocolList();
1136 protocolEntry.setProtocolName(transportProtocol);
1137 protocolEntry.setDescription(transportProtocol);
1138 dbConnection.save(protocolEntry);
1141 private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type,
1142 String transportProtocol, String ports) {
1143 ServiceList serviceListEntry = new ServiceList();
1144 serviceListEntry.setServiceName(groupName);
1145 serviceListEntry.setServiceDescription(description);
1146 serviceListEntry.setServiceType(type);
1147 serviceListEntry.setServiceTransProtocol(transportProtocol);
1148 serviceListEntry.setServiceAppProtocol("null");
1149 serviceListEntry.setServicePorts(ports);
1150 dbConnection.save(serviceListEntry);
1153 private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description,
1154 String prefixList) {
1155 PrefixList newPrefixList = new PrefixList();
1156 newPrefixList.setPrefixListName(addressGroupName);
1157 newPrefixList.setDescription(description);
1158 newPrefixList.setPrefixListValue(prefixList);
1159 dbConnection.save(newPrefixList);
1162 private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description,
1163 String prefixList) {
1164 AddressGroup newAddressGroup = new AddressGroup();
1165 newAddressGroup.setGroupName(addressGroupName);
1166 newAddressGroup.setDescription(description);
1167 newAddressGroup.setServiceList(prefixList);
1168 dbConnection.save(newAddressGroup);
1171 private JsonObject stringToJson(String jsonString) {
1172 // Read jsonBody to JsonObject
1173 StringReader in = new StringReader(jsonString);
1174 JsonReader jsonReader = Json.createReader(in);
1175 JsonObject json = jsonReader.readObject();
1180 private JsonNode createPatch(String json, String oldJson) {
1181 JsonNode oldJason = null;
1182 JsonNode updatedJason = null;
1185 oldJason = JsonLoader.fromString(oldJson);
1186 updatedJason = JsonLoader.fromString(json);
1187 } catch (IOException e) {
1188 LOGGER.error("Exception Occured" + e);
1190 return JsonDiff.asJson(oldJason, updatedJason);
1194 public Object getCorrectPolicyDataObject() {
1195 return policyAdapter.getPolicyData();