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.api.pap.PAPException;
66 import com.att.research.xacml.std.IdentifierImpl;
67 import com.fasterxml.jackson.databind.JsonNode;
68 import com.github.fge.jackson.JsonLoader;
69 import com.github.fge.jsonpatch.diff.JsonDiff;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
85 public class FirewallConfigPolicy extends Policy {
87 private static final Logger LOGGER = FlexLogger.getLogger(FirewallConfigPolicy.class);
89 public FirewallConfigPolicy() {
93 public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) {
94 this.policyAdapter = policyAdapter;
95 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
98 // Saving the Configurations file at server location for config policy.
99 protected void saveConfigurations(String policyName, String jsonBody) {
100 String configurationName = policyName;
101 if(configurationName.endsWith(".xml")){
102 configurationName = configurationName.replace(".xml", "");
104 String fileName = CONFIG_HOME + File.separator + configurationName + ".json";
105 try(BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))){
107 if (LOGGER.isDebugEnabled()) {
108 LOGGER.debug("Configuration is succesfully saved");
110 } catch (IOException e) {
111 LOGGER.error("Save of configuration to file" +fileName+ "failed",e);
115 //Utility to read json data from the existing file to a string
116 static String readFile(String path, Charset encoding) throws IOException {
117 byte[] encoded = Files.readAllBytes(Paths.get(path));
118 return new String(encoded, encoding);
122 public Map<String, String> savePolicies() throws PAPException {
123 Map<String, String> successMap = new HashMap<>();
124 if(isPolicyExists()){
125 successMap.put("EXISTS", "This Policy already exist on the PAP");
128 if(!isPreparedToSave()){
132 // Until here we prepared the data and here calling the method to create xml.
133 Path newPolicyPath = null;
134 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
135 Boolean dbIsUpdated = false;
136 if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){
137 if (policyAdapter.isEditPolicy()) {
138 dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
141 dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
142 } catch (SQLException e) {
143 throw new PAPException(e);
151 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
153 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
155 //remove the new json file
156 String jsonBody = policyAdapter.getPrevJsonBody();
158 saveConfigurations(policyName, jsonBody);
160 saveConfigurations(policyName, "");
162 successMap.put("fwdberror", "DB UPDATE");
168 //This is the method for preparing the policy for saving. We have broken it out
169 //separately because the fully configured policy is used for multiple things
171 public boolean prepareToSave() throws PAPException{
173 if(isPreparedToSave()){
174 //we have already done this
179 String policyID = policyAdapter.getPolicyID();
180 version = policyAdapter.getHighestVersion();
182 // Create the Instance for pojo, PolicyType object is used in marshaling.
183 if ("Config".equals(policyAdapter.getPolicyType())) {
184 PolicyType policyConfig = new PolicyType();
186 policyConfig.setVersion(Integer.toString(version));
187 policyConfig.setPolicyId(policyID);
188 policyConfig.setTarget(new TargetType());
189 policyAdapter.setData(policyConfig);
191 policyName = policyAdapter.getNewFileName();
193 //String oldPolicyName = policyName.replace(".xml", "");
194 String scope = policyName.substring(0, policyName.indexOf('.'));
195 String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", "");
197 int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1));
198 dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1);
200 oldversion = oldversion - 1;
201 dbPolicyName = dbPolicyName + oldversion + ".xml";
203 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
204 Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
205 createPolicyQuery.setParameter("scope", scope);
206 createPolicyQuery.setParameter("policyName", dbPolicyName);
207 List<?> createPolicyQueryList = createPolicyQuery.getResultList();
208 if(!createPolicyQueryList.isEmpty()){
209 PolicyEntity entitydata = (PolicyEntity) createPolicyQueryList.get(0);
210 policyAdapter.setPrevJsonBody(entitydata.getConfigurationData().getConfigBody());
213 if (policyAdapter.getData() != null) {
214 String jsonBody = policyAdapter.getJsonBody();
215 saveConfigurations(policyName, jsonBody);
217 // Make sure the filename ends with an extension
218 if (!policyName.endsWith(".xml")) {
219 policyName = policyName + ".xml";
222 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
224 configPolicy.setDescription(policyAdapter.getPolicyDescription());
226 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
228 AllOfType allOfOne = new AllOfType();
229 String fileName = policyAdapter.getNewFileName();
230 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
231 if ((name == null) || (name.equals(""))) {
232 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
234 allOfOne.getMatch().add(createMatch("PolicyName", name));
235 AllOfType allOf = new AllOfType();
237 // Match for ConfigName
238 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
239 // Match for riskType
240 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
241 // Match for riskLevel
242 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
243 // Match for riskguard
244 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
246 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
247 AnyOfType anyOf = new AnyOfType();
248 anyOf.getAllOf().add(allOfOne);
249 anyOf.getAllOf().add(allOf);
251 TargetType target = new TargetType();
252 target.getAnyOf().add(anyOf);
254 // Adding the target to the policy element
255 configPolicy.setTarget((TargetType) target);
257 RuleType rule = new RuleType();
258 rule.setRuleId(policyAdapter.getRuleID());
259 rule.setEffect(EffectType.PERMIT);
261 // Create Target in Rule
262 AllOfType allOfInRule = new AllOfType();
264 // Creating match for ACCESS in rule target
265 MatchType accessMatch = new MatchType();
266 AttributeValueType accessAttributeValue = new AttributeValueType();
267 accessAttributeValue.setDataType(STRING_DATATYPE);
268 accessAttributeValue.getContent().add("ACCESS");
269 accessMatch.setAttributeValue(accessAttributeValue);
270 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
271 URI accessURI = null;
273 accessURI = new URI(ACTION_ID);
274 } catch (URISyntaxException e) {
275 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
277 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
278 accessAttributeDesignator.setDataType(STRING_DATATYPE);
279 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
280 accessMatch.setAttributeDesignator(accessAttributeDesignator);
281 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
283 // Creating Config Match in rule Target
284 MatchType configMatch = new MatchType();
285 AttributeValueType configAttributeValue = new AttributeValueType();
286 configAttributeValue.setDataType(STRING_DATATYPE);
288 configAttributeValue.getContent().add("Config");
290 configMatch.setAttributeValue(configAttributeValue);
291 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
292 URI configURI = null;
294 configURI = new URI(RESOURCE_ID);
295 } catch (URISyntaxException e) {
296 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
299 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
300 configAttributeDesignator.setDataType(STRING_DATATYPE);
301 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
302 configMatch.setAttributeDesignator(configAttributeDesignator);
303 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
305 allOfInRule.getMatch().add(accessMatch);
306 allOfInRule.getMatch().add(configMatch);
308 AnyOfType anyOfInRule = new AnyOfType();
309 anyOfInRule.getAllOf().add(allOfInRule);
311 TargetType targetInRule = new TargetType();
312 targetInRule.getAnyOf().add(anyOfInRule);
314 rule.setTarget(targetInRule);
315 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
317 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
318 policyAdapter.setPolicyData(configPolicy);
321 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
323 setPreparedToSave(true);
327 // Data required for Advice part is setting here.
328 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
330 //Firewall Config ID Assignment
331 AdviceExpressionsType advices = new AdviceExpressionsType();
332 AdviceExpressionType advice = new AdviceExpressionType();
333 advice.setAdviceId("firewallConfigID");
334 advice.setAppliesTo(EffectType.PERMIT);
336 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
337 assignment1.setAttributeId("type");
338 assignment1.setCategory(CATEGORY_RESOURCE);
339 assignment1.setIssuer("");
340 AttributeValueType configNameAttributeValue = new AttributeValueType();
341 configNameAttributeValue.setDataType(STRING_DATATYPE);
342 configNameAttributeValue.getContent().add("Configuration");
343 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
344 advice.getAttributeAssignmentExpression().add(assignment1);
346 // For Config file Url if configurations are provided.
348 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
349 assignment2.setAttributeId("URLID");
350 assignment2.setCategory(CATEGORY_RESOURCE);
351 assignment2.setIssuer("");
352 AttributeValueType AttributeValue = new AttributeValueType();
353 AttributeValue.setDataType(URI_DATATYPE);
354 if (policyName.endsWith(".xml")) {
355 policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
357 String content = CONFIG_URL + "/Config/" + policyName + ".json";
359 AttributeValue.getContent().add(content);
360 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
361 advice.getAttributeAssignmentExpression().add(assignment2);
363 //Policy Name Assignment
364 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
365 assignment3.setAttributeId("PolicyName");
366 assignment3.setCategory(CATEGORY_RESOURCE);
367 assignment3.setIssuer("");
368 AttributeValueType attributeValue3 = new AttributeValueType();
369 attributeValue3.setDataType(STRING_DATATYPE);
370 fileName = FilenameUtils.removeExtension(fileName);
371 fileName = fileName + ".xml";
372 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
373 if ((name == null) || (name.equals(""))) {
374 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
376 attributeValue3.getContent().add(name);
377 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
378 advice.getAttributeAssignmentExpression().add(assignment3);
380 //Version Number Assignment
381 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
382 assignment4.setAttributeId("VersionNumber");
383 assignment4.setCategory(CATEGORY_RESOURCE);
384 assignment4.setIssuer("");
385 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
386 configNameAttributeValue4.setDataType(STRING_DATATYPE);
387 configNameAttributeValue4.getContent().add(Integer.toString(version));
388 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
389 advice.getAttributeAssignmentExpression().add(assignment4);
391 //Onap Name Assignment
392 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
393 assignment5.setAttributeId("matching:" + ONAPID);
394 assignment5.setCategory(CATEGORY_RESOURCE);
395 assignment5.setIssuer("");
396 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
397 configNameAttributeValue5.setDataType(STRING_DATATYPE);
398 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
399 advice.getAttributeAssignmentExpression().add(assignment5);
401 //Config Name Assignment
402 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
403 assignment6.setAttributeId("matching:" + CONFIGID);
404 assignment6.setCategory(CATEGORY_RESOURCE);
405 assignment6.setIssuer("");
406 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
407 configNameAttributeValue6.setDataType(STRING_DATATYPE);
408 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
409 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
410 advice.getAttributeAssignmentExpression().add(assignment6);
413 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
414 assignment7.setAttributeId("RiskType");
415 assignment7.setCategory(CATEGORY_RESOURCE);
416 assignment7.setIssuer("");
418 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
419 configNameAttributeValue7.setDataType(STRING_DATATYPE);
420 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
421 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
423 advice.getAttributeAssignmentExpression().add(assignment7);
425 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
426 assignment8.setAttributeId("RiskLevel");
427 assignment8.setCategory(CATEGORY_RESOURCE);
428 assignment8.setIssuer("");
430 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
431 configNameAttributeValue8.setDataType(STRING_DATATYPE);
432 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
433 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
435 advice.getAttributeAssignmentExpression().add(assignment8);
437 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
438 assignment9.setAttributeId("guard");
439 assignment9.setCategory(CATEGORY_RESOURCE);
440 assignment9.setIssuer("");
442 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
443 configNameAttributeValue9.setDataType(STRING_DATATYPE);
444 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
445 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
447 advice.getAttributeAssignmentExpression().add(assignment9);
449 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
450 assignment10.setAttributeId("TTLDate");
451 assignment10.setCategory(CATEGORY_RESOURCE);
452 assignment10.setIssuer("");
454 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
455 configNameAttributeValue10.setDataType(STRING_DATATYPE);
456 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
457 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
459 advice.getAttributeAssignmentExpression().add(assignment10);
460 advices.getAdviceExpression().add(advice);
465 private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
466 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
467 JsonObject json = null;
468 if (jsonBody != null) {
470 //Read jsonBody to JsonObject
471 json = stringToJson(jsonBody);
473 JsonArray firewallRules = null;
474 JsonArray serviceGroup = null;
475 JsonArray addressGroup = null;
476 //insert data into tables
478 firewallRules = json.getJsonArray("firewallRuleList");
479 serviceGroup = json.getJsonArray("serviceGroups");
480 addressGroup = json.getJsonArray("addressGroups");
482 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
484 if (firewallRules != null) {
485 for(int i = 0;i<firewallRules.size();i++) {
487 * Populate ArrayLists with values from the JSON
489 //create the JSON object from the JSON Array for each iteration through the for loop
490 JsonObject ruleListobj = firewallRules.getJsonObject(i);
492 //get values from JSON fields of firewallRulesList Array
493 String ruleName = ruleListobj.get("ruleName").toString();
494 String action = ruleListobj.get("action").toString();
495 String description = ruleListobj.get("description").toString();
496 List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
497 if(result != null && !result.isEmpty()){
498 TermList termEntry = (TermList) result.get(0);
499 dbConnection.delete(termEntry);
502 //getting fromZone Array field from the firewallRulesList
503 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
504 String fromZoneString = null;
506 for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) {
507 String value = fromZoneArray.get(fromZoneIndex).toString();
508 value = value.replace("\"", "");
509 if (fromZoneString != null) {
510 fromZoneString = fromZoneString.concat(",").concat(value);
512 fromZoneString = value;
515 String fromZoneInsert = "'"+fromZoneString+"'";
517 //getting toZone Array field from the firewallRulesList
518 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
519 String toZoneString = null;
520 for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) {
521 String value = toZoneArray.get(toZoneIndex).toString();
522 value = value.replace("\"", "");
523 if (toZoneString != null) {
524 toZoneString = toZoneString.concat(",").concat(value);
526 toZoneString = value;
529 String toZoneInsert = "'"+toZoneString+"'";
531 //getting sourceList Array fields from the firewallRulesList
532 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
533 String srcListString = null;
534 for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) {
535 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
536 String type = srcListObj.get("type").toString().replace("\"", "");
539 if(type.equals("REFERENCE")||type.equals("GROUP")){
540 value = srcListObj.get("name").toString();
541 } else if (type.equalsIgnoreCase("ANY")){
544 value = srcListObj.get("value").toString();
548 value = value.replace("\"", "");
551 if (srcListString != null) {
552 srcListString = srcListString.concat(",").concat(value);
555 srcListString = value;
559 String srcListInsert = "'"+srcListString+"'";
561 //getting destinationList Array fields from the firewallRulesList
562 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
563 String destListString = null;
564 for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) {
565 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
566 String type = destListObj.get("type").toString().replace("\"", "");
569 if(type.equals("REFERENCE")||type.equals("GROUP")){
570 value = destListObj.get("name").toString();
571 } else if (type.equalsIgnoreCase("ANY")){
574 value = destListObj.get("value").toString();
578 value = value.replace("\"", "");
581 if (destListString != null) {
582 destListString = destListString.concat(",").concat(value);
584 destListString = value;
587 String destListInsert = "'"+destListString+"'";
589 //getting destServices Array fields from the firewallRulesList
590 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
591 String destPortListString = null;
592 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
593 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
594 String type = destServicesObj.get("type").toString().replace("\"", "");
597 if(type.equals("REFERENCE")||type.equals("GROUP")){
598 value = destServicesObj.get("name").toString();
599 } else if (type.equalsIgnoreCase("ANY")){
602 value = destServicesObj.get("value").toString();
606 value = value.replace("\"", "");
609 if (destPortListString != null) {
610 destPortListString = destPortListString.concat(",").concat(value);
612 destPortListString = value;
615 String destPortListInsert = "'"+destPortListString+"'";
618 * Create Queries to INSERT data into database tables and execute
620 UserInfo userInfo = new UserInfo();
621 userInfo.setUserLoginId("API");
622 userInfo.setUserName("API");
624 TermList termEntry = new TermList();
625 termEntry.setTermName(ruleName);
626 termEntry.setSrcIPList(srcListInsert);
627 termEntry.setDestIPList(destListInsert);
628 termEntry.setProtocolList("null");
629 termEntry.setPortList("null");
630 termEntry.setSrcPortList("null");
631 termEntry.setDestPortList(destPortListInsert);
632 termEntry.setAction(action);
633 termEntry.setDescription(description);
634 termEntry.setFromZones(fromZoneInsert);
635 termEntry.setToZones(toZoneInsert);
636 termEntry.setUserCreatedBy(userInfo);
637 dbConnection.save(termEntry);
639 ActionList actionEntry = new ActionList();
640 actionEntry.setActionName(action);
641 actionEntry.setDescription(action);
642 dbConnection.save(actionEntry);
647 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
649 if (serviceGroup != null) {
650 for(int i = 0; i < serviceGroup.size() ; i++) {
652 * Populate ArrayLists with values from the JSON
654 //create the JSON object from the JSON Array for each iteration through the for loop
655 JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
657 String serviceListName = svcGroupListobj.get("name").toString();
658 String description = null;
659 if (svcGroupListobj.containsKey("description")){
660 description = svcGroupListobj.get("description").toString();
663 //getting members Array from the serviceGroup
664 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
666 //String type = svcGroupListobj.get("type").toString();
667 Boolean isServiceGroup = false;
668 if (membersArray!=null){
669 String membersType = membersArray.getJsonObject(0).get("type").toString();
670 if (membersType.contains("REFERENCE")) {
671 isServiceGroup = true;
675 //Insert values into GROUPSERVICELIST table if name begins with Group
676 if (isServiceGroup) {
678 for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) {
679 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
680 //String value = membersObj.get("name").toString();
681 String type = membersObj.get("type").toString().replace("\"", "");
684 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
685 value = membersObj.get("name").toString();
686 } else if (type.equalsIgnoreCase("ANY")){
689 value = membersObj.get("value").toString();
693 value = value.replace("\"", "");
697 name = name.concat(",").concat(value);
702 String nameInsert = "'"+name+"'";
703 GroupServiceList groupServiceEntry = new GroupServiceList();
704 groupServiceEntry.setGroupName(serviceListName);
705 groupServiceEntry.setServiceList(nameInsert);
706 dbConnection.save(groupServiceEntry);
707 } else { //Insert JSON data serviceList table, protollist table, and portlist table
708 String type = svcGroupListobj.get("type").toString();
709 String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
710 String ports = svcGroupListobj.get("ports").toString();
713 * Create Queries to INSERT data into database table and execute
715 ServiceList serviceListEntry = new ServiceList();
716 serviceListEntry.setServiceName(serviceListName);
717 serviceListEntry.setServiceDescription(description);
718 serviceListEntry.setServiceType(type);
719 serviceListEntry.setServiceTransProtocol(transportProtocol);
720 serviceListEntry.setServiceAppProtocol("null");
721 serviceListEntry.setServicePorts(ports);
722 dbConnection.save(serviceListEntry);
724 ProtocolList protocolEntry = new ProtocolList();
725 protocolEntry.setProtocolName(transportProtocol);
726 protocolEntry.setDescription(transportProtocol);
727 dbConnection.save(protocolEntry);
729 PortList portListEntry = new PortList();
730 portListEntry.setPortName(ports);
731 portListEntry.setDescription(ports);
732 dbConnection.save(portListEntry);
738 * Inserting addressGroup data into the ADDRESSGROUP table
740 if (addressGroup != null) {
741 for(int i = 0; i < addressGroup.size(); i++) {
743 * Populate ArrayLists with values from the JSON
745 //create the JSON object from the JSON Array for each iteration through the for loop
746 JsonObject addressGroupObj = addressGroup.getJsonObject(i);
748 //create JSON array for members
749 JsonArray membersArray = addressGroupObj.getJsonArray("members");
750 String addressGroupName = addressGroupObj.get("name").toString();
752 String description = null;
753 if (addressGroupObj.containsKey("description")){
754 description = addressGroupObj.get("description").toString();
757 String prefixIP = null;
759 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
760 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
761 //String value = membersObj.get("value").toString();
762 type = membersObj.get("type").toString().replace("\"", "");
765 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
766 value = membersObj.get("name").toString();
767 } else if (type.equalsIgnoreCase("ANY")){
770 value = membersObj.get("value").toString();
774 value = value.replace("\"", "");
777 if (prefixIP != null) {
778 prefixIP = prefixIP.concat(",").concat(value);
783 String prefixList = "'"+prefixIP+"'";
785 Boolean isAddressGroup = type.contains("REFERENCE");
787 if (isAddressGroup) {
788 AddressGroup addressGroupEntry = new AddressGroup();
789 addressGroupEntry.setGroupName(addressGroupName);
790 addressGroupEntry.setDescription(description);
791 addressGroupEntry.setServiceList(prefixList);
792 dbConnection.save(addressGroupEntry);
794 PrefixList prefixListEntry = new PrefixList();
795 prefixListEntry.setPrefixListName(addressGroupName);
796 prefixListEntry.setDescription(description);
797 prefixListEntry.setPrefixListValue(prefixList);
798 dbConnection.save(prefixListEntry);
804 * Remove duplicate values from 'lookup' dictionary tables
807 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
808 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
809 dbConnection.updateQuery(protoDelete);
812 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
813 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
814 dbConnection.updateQuery(portListDelete);
817 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
818 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
819 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
820 dbConnection.updateQuery(prefixListDelete);
823 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
824 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
825 + "groupservicelist.serviceList = g1.serviceList; ";
826 dbConnection.updateQuery(groupServiceDelete);
827 }catch (Exception e) {
828 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
840 private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
841 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
842 JsonObject oldJson = null;
843 JsonObject newJson = null;
845 if (jsonBody != null || prevJsonBody != null) {
847 oldJson = stringToJson(prevJsonBody);
848 newJson = stringToJson(jsonBody);
850 //if no changes to the json then return true
851 if (oldJson != null && oldJson.equals(newJson)) {
855 JsonArray firewallRules = null;
856 JsonArray serviceGroup = null;
857 JsonArray addressGroup = null;
859 firewallRules = newJson.getJsonArray("firewallRuleList");
860 serviceGroup = newJson.getJsonArray("serviceGroups");
861 addressGroup = newJson.getJsonArray("addressGroups");
863 //insert data into tables
865 JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
867 for (int i = 0; i<jsonDiff.size(); i++) {
868 //String path = jsonDiff.get(i).asText();
869 String jsonpatch = jsonDiff.get(i).toString();
871 JsonObject patchObj = stringToJson(jsonpatch);
873 String path = patchObj.get("path").toString().replace('"', ' ').trim();
875 if (path.contains("firewallRuleList")) {
877 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
879 for(int ri = 0; ri < firewallRules.size(); ri++) {
881 * Populate ArrayLists with values from the JSON
883 //create the JSON object from the JSON Array for each iteration through the for loop
884 JsonObject ruleListobj = firewallRules.getJsonObject(ri);
886 //get values from JSON fields of firewallRulesList Array
887 String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
888 String action = ruleListobj.get("action").toString().replace('"', '\'');
889 String description = ruleListobj.get("description").toString().replace('"', '\'');
891 List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
892 if(result != null && !result.isEmpty()){
893 TermList termEntry = (TermList) result.get(0);
894 dbConnection.delete(termEntry);
897 //getting fromZone Array field from the firewallRulesList
898 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
899 String fromZoneString = null;
901 for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) {
902 String value = fromZoneArray.get(fromZoneIndex).toString();
903 value = value.replace("\"", "");
905 if (fromZoneString != null) {
906 fromZoneString = fromZoneString.concat(",").concat(value);
909 fromZoneString = value;
913 String fromZoneInsert = "'"+fromZoneString+"'";
915 //getting toZone Array field from the firewallRulesList
916 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
917 String toZoneString = null;
920 for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
921 String value = toZoneArray.get(toZoneIndex).toString();
922 value = value.replace("\"", "");
924 if (toZoneString != null) {
925 toZoneString = toZoneString.concat(",").concat(value);
928 toZoneString = value;
932 String toZoneInsert = "'"+toZoneString+"'";
933 //getting sourceList Array fields from the firewallRulesList
934 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
935 String srcListString = null;
936 for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) {
937 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
938 String type = srcListObj.get("type").toString().replace("\"", "");
941 if(type.equals("REFERENCE")||type.equals("GROUP")){
942 value = srcListObj.get("name").toString();
943 } else if (type.equalsIgnoreCase("ANY")){
946 value = srcListObj.get("value").toString();
950 value = value.replace("\"", "");
953 if (srcListString != null) {
954 srcListString = srcListString.concat(",").concat(value);
957 srcListString = value;
961 String srcListInsert = "'"+srcListString+"'";
963 //getting destinationList Array fields from the firewallRulesList
964 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
965 String destListString = null;
966 for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) {
967 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
968 String type = destListObj.get("type").toString().replace("\"", "");
971 if(type.equals("REFERENCE")||type.equals("GROUP")){
972 value = destListObj.get("name").toString();
973 } else if (type.equalsIgnoreCase("ANY")){
976 value = destListObj.get("value").toString();
980 value = value.replace("\"", "");
983 if (destListString != null) {
984 destListString = destListString.concat(",").concat(value);
986 destListString = value;
989 String destListInsert = "'"+destListString+"'";
991 //getting destServices Array fields from the firewallRulesList
992 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
993 String destPortListString = null;
994 for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
995 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
996 String type = destServicesObj.get("type").toString().replace("\"", "");
999 if(type.equals("REFERENCE")||type.equals("GROUP")){
1000 value = destServicesObj.get("name").toString();
1001 } else if (type.equalsIgnoreCase("ANY")){
1004 value = destServicesObj.get("value").toString();
1008 value = value.replace("\"", "");
1011 if (destPortListString != null) {
1012 destPortListString = destPortListString.concat(",").concat(value);
1014 destPortListString = value;
1017 String destPortListInsert = "'"+destPortListString+"'";
1020 * Create Queries to INSERT data into database tables and execute
1022 UserInfo userInfo = new UserInfo();
1023 userInfo.setUserLoginId("API");
1024 userInfo.setUserName("API");
1026 TermList termEntry = new TermList();
1027 termEntry.setTermName(ruleName);
1028 termEntry.setSrcIPList(srcListInsert);
1029 termEntry.setDestIPList(destListInsert);
1030 termEntry.setProtocolList("null");
1031 termEntry.setPortList("null");
1032 termEntry.setSrcPortList("null");
1033 termEntry.setDestPortList(destPortListInsert);
1034 termEntry.setAction(action);
1035 termEntry.setDescription(description);
1036 termEntry.setFromZones(fromZoneInsert);
1037 termEntry.setToZones(toZoneInsert);
1038 termEntry.setUserCreatedBy(userInfo);
1039 dbConnection.save(termEntry);
1041 List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action);
1042 if(actionResult == null || actionResult.isEmpty()){
1043 ActionList actionEntry = new ActionList();
1044 actionEntry.setActionName(action);
1045 actionEntry.setDescription(action);
1046 dbConnection.save(actionEntry);
1051 if (path.contains("serviceGroups")) {
1053 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
1055 for(int si = 0; si < serviceGroup.size(); si++) {
1057 * Populate ArrayLists with values from the JSON
1059 //create the JSON object from the JSON Array for each iteration through the for loop
1060 JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
1062 String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');
1064 String description = null;
1065 if (svcGroupListobj.containsKey("description")){
1066 description = svcGroupListobj.get("description").toString().replace('"', '\'');
1069 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
1071 Boolean isServiceGroup = false;
1072 if (membersArray!=null){
1073 String membersType = membersArray.getJsonObject(0).get("type").toString();
1074 if (membersType.contains("REFERENCE")) {
1075 isServiceGroup = true;
1079 //Insert values into GROUPSERVICELIST table if name begins with Group
1080 if (isServiceGroup) {
1081 List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName);
1082 if(result != null && !result.isEmpty()){
1083 GroupServiceList groupEntry = (GroupServiceList) result.get(0);
1084 dbConnection.delete(groupEntry);
1088 for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
1089 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1090 String type = membersObj.get("type").toString().replace("\"", "");
1092 String value = null;
1093 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1094 value = membersObj.get("name").toString();
1095 } else if (type.equalsIgnoreCase("ANY")){
1098 value = membersObj.get("value").toString();
1102 value = value.replace("\"", "");
1106 name = name.concat(",").concat(value);
1111 String nameInsert = "'"+name+"'";
1112 GroupServiceList groupServiceEntry = new GroupServiceList();
1113 groupServiceEntry.setGroupName(groupName);
1114 groupServiceEntry.setServiceList(nameInsert);
1115 dbConnection.save(groupServiceEntry);
1116 } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
1117 String type = svcGroupListobj.get("type").toString().replace('"', '\'');
1118 String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
1119 String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
1121 List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName);
1122 if(result != null && !result.isEmpty()){
1123 ServiceList serviceEntry = (ServiceList) result.get(0);
1124 dbConnection.delete(serviceEntry);
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);
1136 List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
1137 if(protocolResult == null || protocolResult.isEmpty()){
1138 ProtocolList protocolEntry = new ProtocolList();
1139 protocolEntry.setProtocolName(transportProtocol);
1140 protocolEntry.setDescription(transportProtocol);
1141 dbConnection.save(protocolEntry);
1144 List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports);
1145 if(portResult == null || portResult.isEmpty()){
1146 PortList portEntry = new PortList();
1147 portEntry.setPortName(ports);
1148 portEntry.setDescription(ports);
1149 dbConnection.save(portEntry);
1155 if (path.contains("addressGroups")) {
1157 * Inserting addressGroup data into the ADDRESSGROUP table
1159 for(int ai=0; ai < addressGroup.size() ; ai++) {
1162 * Populate ArrayLists with values from the JSON
1164 //create the JSON object from the JSON Array for each iteration through the for loop
1165 JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
1167 //create JSON array for members
1168 JsonArray membersArray = addressGroupObj.getJsonArray("members");
1169 String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
1171 String description = null;
1172 if (addressGroupObj.containsKey("description")){
1173 description = addressGroupObj.get("description").toString().replace('"', '\'');
1176 String prefixIP = null;
1178 for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) {
1179 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1180 type = membersObj.get("type").toString().replace("\"", "");
1182 String value = null;
1183 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1184 value = membersObj.get("name").toString();
1185 } else if (type.equalsIgnoreCase("ANY")){
1188 value = membersObj.get("value").toString();
1192 value = value.replace("\"", "");
1195 if (prefixIP != null) {
1196 prefixIP = prefixIP.concat(",").concat(value);
1202 String prefixList = "'"+prefixIP+"'";
1203 Boolean isAddressGroup = type.contains("REFERENCE");
1205 if (isAddressGroup) {
1206 List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
1207 if(result != null && !result.isEmpty()){
1208 AddressGroup addressGroupEntry = (AddressGroup) result.get(0);
1209 dbConnection.delete(addressGroupEntry);
1211 AddressGroup newAddressGroup = new AddressGroup();
1212 newAddressGroup.setGroupName(addressGroupName);
1213 newAddressGroup.setDescription(description);
1214 newAddressGroup.setServiceList(prefixList);
1215 dbConnection.save(newAddressGroup);
1217 List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
1218 if(result != null && !result.isEmpty()){
1219 PrefixList prefixListEntry = (PrefixList) result.get(0);
1220 dbConnection.delete(prefixListEntry);
1222 PrefixList newPrefixList = new PrefixList();
1223 newPrefixList.setPrefixListName(addressGroupName);
1224 newPrefixList.setDescription(description);
1225 newPrefixList.setPrefixListValue(prefixList);
1226 dbConnection.save(newPrefixList);
1233 * Remove duplicate values from 'lookup' dictionary tables
1235 //ProtocolList Table
1236 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
1237 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
1238 dbConnection.updateQuery(protoDelete);
1241 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
1242 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
1243 dbConnection.updateQuery(portListDelete);
1246 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
1247 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
1248 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
1249 dbConnection.updateQuery(prefixListDelete);
1252 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
1253 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
1254 + "groupservicelist.serviceList = g1.serviceList; ";
1255 dbConnection.updateQuery(groupServiceDelete);
1256 }catch (Exception e) {
1257 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1267 private JsonObject stringToJson(String jsonString) {
1268 //Read jsonBody to JsonObject
1269 StringReader in = new StringReader(jsonString);
1270 JsonReader jsonReader = Json.createReader(in);
1271 JsonObject json = jsonReader.readObject();
1276 private JsonNode createPatch(String json, String oldJson) {
1277 JsonNode oldJason = null;
1278 JsonNode updatedJason = null;
1281 oldJason = JsonLoader.fromString(oldJson);
1282 updatedJason = JsonLoader.fromString(json);
1283 } catch (IOException e) {
1284 LOGGER.error("Exception Occured"+e);
1286 return JsonDiff.asJson(oldJason, updatedJason);
1290 public Object getCorrectPolicyDataObject() {
1291 return policyAdapter.getPolicyData();