From bcf3a41615b8459291b820b0253e49bc052a87af Mon Sep 17 00:00:00 2001 From: Michael Asher <18621120+themichaelasher@users.noreply.github.com> Date: Wed, 21 Sep 2022 09:00:58 -0400 Subject: [PATCH 01/16] Add: Ignore/Truncate Conversion Comments --- SmartMove/SmartConnector/smartconnector.py | 37 ++++++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/SmartMove/SmartConnector/smartconnector.py b/SmartMove/SmartConnector/smartconnector.py index 57f7b41..5100230 100644 --- a/SmartMove/SmartConnector/smartconnector.py +++ b/SmartMove/SmartConnector/smartconnector.py @@ -1029,8 +1029,25 @@ def addAccessRules(client, userRules, userLayerName, skipCleanUpRule, mergedNetw } if userRule['Action'] == 3: payload["inline-layer"] = userRule['SubPolicyName'] - if userRule['ConversionComments'].strip() != "": - payload["custom-fields"] = {"field-1": userRule['ConversionComments']} + + # Due to the custom-fields.field-[1-3] having a limit of 254 Characters, this is used as a workaround + # Rule comments will stil be imported if they exist in userRule['Comments'] + # The default value is False, so custom-fields will still be utilized. + # + # If the Conversion Comments is > 250, then we should trim it. + # This matches the behavior in CheckPointObjects/CLIScriptBuilder.cs (limit there is 150) + # + if isIgnoreConversionComments != True: + if userRule['ConversionComments'].strip() != "": + if len(userRule['ConversionComments']) > 250: + lenConversionComments=len(userRule['ConversionComments']) + newConversionComment = (userRule['ConversionComments'][:250] +'...') + payload["custom-fields"] = {"field-1": newConversionComment} + printStatus(None, "WARN: Conversion Comment truncated due to length (" + str(lenConversionComment) +")") + else: + payload["custom-fields"] = {"field-1": userRule['ConversionComments']} + # + addedRule = addUserObjectToServer(client, "add-access-rule", payload, changeName=False) if addedRule is not None: printStatus(None, "REPORT: access rule is added") @@ -1230,7 +1247,8 @@ def processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, help="The name/uid of the domain you want to log into in an MDS environment.") args_parser.add_argument('--replace-from-global-first', default="false", help="The argument indicates that SmartConnector should use 'Global' objects at first, by default it uses 'Local' objects. [true, false]") - +args_parser.add_argument('--ignore-conversion-comments', default="false", + help="The argument indicates that SmartConnector should not add conversion comments into custom-fields [true, false]") args = args_parser.parse_args() file_name_log = "smartconnector" @@ -1267,11 +1285,23 @@ def processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, "smartconnector.py: error: argument --replace-from-global-first: invalid boolean value: '" + args.replace_from_global_first + "'") print("") args_parser.print_help() +elif args.ignore_conversion_comments.lower() != "true" and args.ignore_conversion_comments.lower() != "false": + print("") + printStatus(None, None, + "smartconnector.py: error: argument '--ignore-conversion-comments: invalid boolean value: '" + args.ignore_conversion_comments + "'") + print("") + args_parser.print_help() + else: if args.replace_from_global_first.lower() == "true": isReplaceFromGlobalFirst = True elif args.replace_from_global_first.lower() == "false": isReplaceFromGlobalFirst = False + if args.ignore_conversion_comments.lower() == "true": + isIgnoreConversionComments = True + else: + isIgnoreConversionComments = False + printStatus(None, "Input arguments:") printStatus(None, "root flag is set" if args.root else "root flag is not set") printStatus(None, "management: " + args.management) @@ -1284,6 +1314,7 @@ def processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, printStatus(None, "file: " + args.file) printStatus(None, "threshold: " + str(args.threshold)) printStatus(None, "replace-from-global-first: " + str(isReplaceFromGlobalFirst)) + printStatus(None, "ignore-conversion-comments: " + str(isIgnoreConversionComments)) printStatus(None, "===========================================") printStatus(None, "reading and parsing processes are started for JSON file: " + args.file) with open(args.file) as json_file: From 88e4cf97b65fd4de81716cec4be76cdb955dcb09 Mon Sep 17 00:00:00 2001 From: chkp-ofirs Date: Tue, 11 Oct 2022 21:15:08 +0300 Subject: [PATCH 02/16] Revert "SmartConnector: Override character limitation of custom-fields" --- SmartMove/SmartConnector/smartconnector.py | 37 ++-------------------- 1 file changed, 3 insertions(+), 34 deletions(-) diff --git a/SmartMove/SmartConnector/smartconnector.py b/SmartMove/SmartConnector/smartconnector.py index 5100230..57f7b41 100644 --- a/SmartMove/SmartConnector/smartconnector.py +++ b/SmartMove/SmartConnector/smartconnector.py @@ -1029,25 +1029,8 @@ def addAccessRules(client, userRules, userLayerName, skipCleanUpRule, mergedNetw } if userRule['Action'] == 3: payload["inline-layer"] = userRule['SubPolicyName'] - - # Due to the custom-fields.field-[1-3] having a limit of 254 Characters, this is used as a workaround - # Rule comments will stil be imported if they exist in userRule['Comments'] - # The default value is False, so custom-fields will still be utilized. - # - # If the Conversion Comments is > 250, then we should trim it. - # This matches the behavior in CheckPointObjects/CLIScriptBuilder.cs (limit there is 150) - # - if isIgnoreConversionComments != True: - if userRule['ConversionComments'].strip() != "": - if len(userRule['ConversionComments']) > 250: - lenConversionComments=len(userRule['ConversionComments']) - newConversionComment = (userRule['ConversionComments'][:250] +'...') - payload["custom-fields"] = {"field-1": newConversionComment} - printStatus(None, "WARN: Conversion Comment truncated due to length (" + str(lenConversionComment) +")") - else: - payload["custom-fields"] = {"field-1": userRule['ConversionComments']} - # - + if userRule['ConversionComments'].strip() != "": + payload["custom-fields"] = {"field-1": userRule['ConversionComments']} addedRule = addUserObjectToServer(client, "add-access-rule", payload, changeName=False) if addedRule is not None: printStatus(None, "REPORT: access rule is added") @@ -1247,8 +1230,7 @@ def processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, help="The name/uid of the domain you want to log into in an MDS environment.") args_parser.add_argument('--replace-from-global-first', default="false", help="The argument indicates that SmartConnector should use 'Global' objects at first, by default it uses 'Local' objects. [true, false]") -args_parser.add_argument('--ignore-conversion-comments', default="false", - help="The argument indicates that SmartConnector should not add conversion comments into custom-fields [true, false]") + args = args_parser.parse_args() file_name_log = "smartconnector" @@ -1285,23 +1267,11 @@ def processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, "smartconnector.py: error: argument --replace-from-global-first: invalid boolean value: '" + args.replace_from_global_first + "'") print("") args_parser.print_help() -elif args.ignore_conversion_comments.lower() != "true" and args.ignore_conversion_comments.lower() != "false": - print("") - printStatus(None, None, - "smartconnector.py: error: argument '--ignore-conversion-comments: invalid boolean value: '" + args.ignore_conversion_comments + "'") - print("") - args_parser.print_help() - else: if args.replace_from_global_first.lower() == "true": isReplaceFromGlobalFirst = True elif args.replace_from_global_first.lower() == "false": isReplaceFromGlobalFirst = False - if args.ignore_conversion_comments.lower() == "true": - isIgnoreConversionComments = True - else: - isIgnoreConversionComments = False - printStatus(None, "Input arguments:") printStatus(None, "root flag is set" if args.root else "root flag is not set") printStatus(None, "management: " + args.management) @@ -1314,7 +1284,6 @@ def processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, printStatus(None, "file: " + args.file) printStatus(None, "threshold: " + str(args.threshold)) printStatus(None, "replace-from-global-first: " + str(isReplaceFromGlobalFirst)) - printStatus(None, "ignore-conversion-comments: " + str(isIgnoreConversionComments)) printStatus(None, "===========================================") printStatus(None, "reading and parsing processes are started for JSON file: " + args.file) with open(args.file) as json_file: From 5808f781cb75e836bd4d0ba004c8ff087bac9c6c Mon Sep 17 00:00:00 2001 From: ofir shikolski Date: Tue, 18 Oct 2022 10:10:31 +0300 Subject: [PATCH 03/16] fixes whitespace dotnet format whitespace --no-restore --- CheckPointObjects/CheckPointObjects.cs | 6 +- .../CheckPointObjectsRepository.cs | 7 +- CheckPointObjects/RuleBaseOptimizer.cs | 13 +- CiscoMigration/CiscoAnalizStatistic.cs | 2 +- CiscoMigration/CiscoConverter.cs | 79 +++---- CiscoMigration/CiscoParser.cs | 8 +- CommonUtils/Helper.cs | 2 +- CommonUtils/JsonReport.cs | 11 +- FortinetMigration/FortiGateAnalizStatic.cs | 4 +- FortinetMigration/FortiGateConverter.cs | 35 +-- FortinetMigration/FortiGateParser.cs | 2 +- JuniperMigration/JuniperAnalizStatistic.cs | 2 +- JuniperMigration/JuniperConverter.cs | 90 ++++---- JuniperMigration/JuniperObjects.cs | 43 ++-- JuniperMigration/JuniperParser.cs | 17 +- MigrationBase/SupportedVendors.cs | 8 +- MigrationBase/VendorAnalizStatistic.cs | 2 +- MigrationBase/VendorConverter.cs | 18 +- MigrationBase/VendorParser.cs | 2 +- NetScreenMigration/ScreenOSCommands.cs | 68 +++--- NetScreenMigration/ScreenOSConverter.cs | 67 +++--- NetScreenMigration/ScreenOSKnownServices.cs | 4 +- NetScreenMigration/ScreenOSParser.cs | 10 +- NetScreenMigration/ScreenOSServiceObjects.cs | 12 +- PaloAltoMigration/PA_Config.cs | 2 +- PaloAltoMigration/PaloAltoConverter.cs | 209 +++++++++--------- PaloAltoMigration/PanoramaConverter.cs | 150 ++++++------- PaloAltoMigration/PanoramaParser.cs | 40 ++-- PaloAltoMigration/Panorama_Config.cs | 54 ++--- SmartMove/AboutWindow.xaml.cs | 4 +- SmartMove/AnalyzeWindow.xaml.cs | 4 +- SmartMove/App.xaml.cs | 2 +- SmartMove/CommandLine.cs | 16 +- SmartMove/DisclaimerWindow.xaml.cs | 6 +- SmartMove/MainWindow.xaml.cs | 53 ++--- SmartMove/MessageWindow.xaml.cs | 8 +- SmartMove/Program.cs | 39 ++-- SmartMove/Properties/AssemblyInfo.cs | 8 +- .../TripleClickSelectsAllTextBehavior.cs | 4 +- 39 files changed, 565 insertions(+), 546 deletions(-) diff --git a/CheckPointObjects/CheckPointObjects.cs b/CheckPointObjects/CheckPointObjects.cs index 6983563..f07b5ef 100644 --- a/CheckPointObjects/CheckPointObjects.cs +++ b/CheckPointObjects/CheckPointObjects.cs @@ -491,7 +491,7 @@ public class CheckPoint_OtherService : CheckPointObject public string IpProtocol { get; set; } public CheckPoint_OtherService() : base() { } - public CheckPoint_OtherService (string name, string ipprotocol, string comments, List tags) : base() + public CheckPoint_OtherService(string name, string ipprotocol, string comments, List tags) : base() { Name = name; IpProtocol = ipprotocol; @@ -517,7 +517,7 @@ public class CheckPoint_ServiceGroup : CheckPointObject { public List Members = new List(); public int MembersPublishIndex { get; set; } - public int MembersMaxPublishSize { get; set; } + public int MembersMaxPublishSize { get; set; } public CheckPoint_ServiceGroup() : base() { @@ -538,7 +538,7 @@ public override string ToCLIScriptInstruction() int index = ((MembersPublishIndex + MembersMaxPublishSize) > Members.Count) ? Members.Count : MembersPublishIndex + MembersMaxPublishSize; return (MembersPublishIndex == 0 ? "create " : "update ") + "service group [" + Name + "]: " + index + "/" + Members.Count + " members"; } - + } public class CheckPoint_ApplicationGroup : CheckPointObject diff --git a/CheckPointObjects/CheckPointObjectsRepository.cs b/CheckPointObjects/CheckPointObjectsRepository.cs index a94bbb6..ea89a0d 100644 --- a/CheckPointObjects/CheckPointObjectsRepository.cs +++ b/CheckPointObjects/CheckPointObjectsRepository.cs @@ -32,8 +32,8 @@ public class CheckPointObjectsRepository private class ObjectInfo { - public CheckPointObject Object { get; private set; } - public bool IsPredefined { get; private set; } + public CheckPointObject Object { get; private set; } + public bool IsPredefined { get; private set; } public ObjectInfo(CheckPointObject cpObject, bool isPredefined) { @@ -157,7 +157,8 @@ public bool HasObject(string objectName) return (!string.IsNullOrEmpty(objectName) && _repository.ContainsKey(objectName)); } - public bool IsPredefinedOrKnownService(string name) { + public bool IsPredefinedOrKnownService(string name) + { return HasObject(name) || IsKnownService(name); } diff --git a/CheckPointObjects/RuleBaseOptimizer.cs b/CheckPointObjects/RuleBaseOptimizer.cs index 48e9367..21d3d0a 100644 --- a/CheckPointObjects/RuleBaseOptimizer.cs +++ b/CheckPointObjects/RuleBaseOptimizer.cs @@ -196,7 +196,7 @@ private static bool IsRuleSimilarToRule(CheckPoint_Rule rule1, CheckPoint_Rule r return false; } - if ((rule1.Time.Count != rule2.Time.Count) || + if ((rule1.Time.Count != rule2.Time.Count) || (rule1.Time.Count > 0 && rule2.Time.Count > 0 && rule1.Time[0].Name != rule2.Time[0].Name)) { return false; @@ -238,8 +238,9 @@ private static string OptimizeConverstionComments(string commentToProcess) //if there is nothing to merge return empty comment if (comments_parts.Count == 0) return ""; - - if (comments_parts.Count > 0) { + + if (comments_parts.Count > 0) + { if (regex.IsMatch(comments_parts[0])) foreach (string part in comments_parts) @@ -275,9 +276,9 @@ private static string OptimizeConverstionComments(string commentToProcess) commentBuilder += ", " + comments_parts[i]; } - } - else - return commentToProcess.Trim(); + } + else + return commentToProcess.Trim(); } return commentBuilder == "Matched rule(s)" ? "" : commentBuilder; diff --git a/CiscoMigration/CiscoAnalizStatistic.cs b/CiscoMigration/CiscoAnalizStatistic.cs index 7bbea91..53b123e 100644 --- a/CiscoMigration/CiscoAnalizStatistic.cs +++ b/CiscoMigration/CiscoAnalizStatistic.cs @@ -48,7 +48,7 @@ public override void CalculateNetworks(List _cpNetworks, } foreach (var item in _cpHosts) { - if (_cpHosts.Where(nt => nt.IpAddress == item.IpAddress ).Count() > 1) { _duplicateServicesObjectsCount++; } + if (_cpHosts.Where(nt => nt.IpAddress == item.IpAddress).Count() > 1) { _duplicateServicesObjectsCount++; } } foreach (var item in _cpRanges) { diff --git a/CiscoMigration/CiscoConverter.cs b/CiscoMigration/CiscoConverter.cs index 4d8e766..20bcdb5 100644 --- a/CiscoMigration/CiscoConverter.cs +++ b/CiscoMigration/CiscoConverter.cs @@ -1140,7 +1140,7 @@ private void BuildListOfUsedObjects(bool convertNat) { PopulateUsedNetObjectsFromRules(layer.Rules); } - + //NAT if (convertNat) { @@ -1157,7 +1157,7 @@ private void BuildListOfUsedObjects(bool convertNat) private void PopulateUsedNetObjectsFromNatRules() { - foreach(CheckPoint_NAT_Rule rule in _cpNatRules) + foreach (CheckPoint_NAT_Rule rule in _cpNatRules) { //Orig-Destination if (rule.Destination != null) @@ -1188,7 +1188,7 @@ private void PopulateUsedNetObjectsFromNatRules() _usedNetObjects[rule.Source.SafeName()] = rule.Source; } } - + //Translated-Destination if (rule.TranslatedDestination != null) { @@ -1232,13 +1232,13 @@ private void PopulateUsedNetObjectsFromRules(List rules) else { if (!dest.Name.Contains("Err_in_")) - _usedNetObjects[ dest.SafeName()] = dest; + _usedNetObjects[dest.SafeName()] = dest; } } foreach (var src in rule.Source) { - if (src.Name.StartsWith("bsr-sep-02") || src.Name.StartsWith("bsr-02.bbs")) + if (src.Name.StartsWith("bsr-sep-02") || src.Name.StartsWith("bsr-02.bbs")) { int i = 1; i += 1; @@ -1483,7 +1483,7 @@ private void CollectOnlyUsedObjects() switch (typeName) { case "CheckPoint_Host": - foreach(var host in _cpHosts) + foreach (var host in _cpHosts) { if (_usedObjects[typeName].Contains(host.Name)) newHostList.Add(host); @@ -1781,7 +1781,7 @@ private void Add_NetworkGroups() CheckObjectNameValidity(cpHost, ciscoGroup); AddCheckPointObject(cpHost); } - } + } } if (ciscoGroup.GroupType == Cisco_GroupObject.Group_Type.Network && !isHost) @@ -1848,18 +1848,18 @@ private void Add_InterfacesAndRoutes() foreach (Cisco_Interface.Subnet subnet in ciscoInterface.Topology) { - - // Note, that a subnet can be a host in Cisco, but we want to always convert to network in CP!!! - string networkName = (new CiscoNetwork(ciscoInterface.Id, subnet.Network, subnet.Netmask)).AutoGeneratedNetworkName(); - if (networkName.Contains(AutoGeneratedNameWithError)) - { - ciscoInterface.ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ciscoInterface.ConversionIncidentMessage = "Unrecognized topology details."; + // Note, that a subnet can be a host in Cisco, but we want to always convert to network in CP!!! + string networkName = (new CiscoNetwork(ciscoInterface.Id, subnet.Network, subnet.Netmask)).AutoGeneratedNetworkName(); + if (networkName.Contains(AutoGeneratedNameWithError)) + { + ciscoInterface.ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ciscoInterface.ConversionIncidentMessage = "Unrecognized topology details."; - ciscoCommandIdWithIncident = ciscoInterface.Id; - } + + ciscoCommandIdWithIncident = ciscoInterface.Id; + } if (subnet.Netmask == "255.255.255.255") { @@ -1886,7 +1886,8 @@ private void Add_InterfacesAndRoutes() cpNetworkError.Netmask = subnet.Netmask; AddCheckPointObject(cpNetworkError); //continue; - } else + } + else { var cpNetwork = new CheckPoint_Network(); @@ -1899,7 +1900,7 @@ private void Add_InterfacesAndRoutes() cpNetworkGroup.Members.Add(cpNetwork.Name); } - + } ApplyConversionIncidentOnCheckPointObject(cpNetworkGroup, ciscoInterface); AddCheckPointObject(cpNetworkGroup); @@ -2800,7 +2801,7 @@ private void Add_ParentLayer(CheckPoint_Package package) if (addParentRule) { var cpRule = new CheckPoint_Rule(); - + cpRule.Source.Add(cpZone); if (cpZone.Name.Equals("Any")) { @@ -2940,7 +2941,7 @@ private void Add_Layers_And_Rules(CheckPoint_Package package) NewCiscoAnalizStatistic._disabledServicesRulesCount++; cpRule.Enabled = false; } - if(!cpRule.Track.Equals(TrackTypes.Log)) + if (!cpRule.Track.Equals(TrackTypes.Log)) { NewCiscoAnalizStatistic._nonServicesLoggingServicesRulesCount++; } @@ -3073,7 +3074,7 @@ private void Add_Global_Rules(CheckPoint_Package package) NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnyServiceCount++; NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnySourceCount++; NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnyCount++; - if(cpSubRule4GlobalLayer.Time.Count > 0 && cpSubRule4GlobalLayer.Time.First().Name.Equals("Any")) + if (cpSubRule4GlobalLayer.Time.Count > 0 && cpSubRule4GlobalLayer.Time.First().Name.Equals("Any")) { NewCiscoAnalizStatistic._timesServicesRulesCount++; } @@ -3438,7 +3439,7 @@ private CheckPoint_Rule Acl_To_CPRule(Cisco_AccessList ciscoAcl, string layerNam "Error creating a rule, missing information for Cisco destination service", "Service details: " + ciscoAcl.DestinationProperties.Protocol + " " + ciscoAcl.DestinationProperties.TcpUdpPortOperator + " " + ciscoAcl.DestinationProperties.TcpUdpPortValue + "."); cpRule.Service.Add(cpObject); - if(cpObject.Name.Equals("Any")) + if (cpObject.Name.Equals("Any")) { NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnyServiceCount++; if (any_fl) @@ -3717,7 +3718,7 @@ private void Add_AclServices_To_CPRule(Cisco_AccessList ciscoAcl, Cisco_GroupObj if (cpObject.Name.Equals("Any")) { NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnyServiceCount++; - NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnyCount++; + NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnyCount++; } // This may happen, for example, if: @@ -4628,7 +4629,7 @@ private void Add_NAT_Rules() { cpNatRule.Source = _cpObjects.GetObject(CheckPointObject.Any); NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnySourceCount++; - if(any_fl) + if (any_fl) { NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnyCount++; any_fl = false; @@ -4878,7 +4879,7 @@ private void Add_NAT_Rules() else { cpNatMirrorRule.Source = cpNatRule.TranslatedDestination ?? cpNatRule.Destination; - if(cpNatMirrorRule.Source.Name.Equals("Any") && !cpNatRule.Source.Name.Equals("Any")) + if (cpNatMirrorRule.Source.Name.Equals("Any") && !cpNatRule.Source.Name.Equals("Any")) { NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnySourceCount++; if (any_fl) @@ -5066,7 +5067,7 @@ private void MatchNATRulesIntoFirewallPolicy() { CheckPoint_Package cpPackage = _cpPackages[0]; int index = 0; - + List newRules = new List(); List threads = new List(); @@ -5255,7 +5256,7 @@ void SubMatchNATRulesIntoFirewallPolicy() if (!ruleIsAlreadyAdded) { //subPolicy.Rules.Insert(ruleNumber, newRule); - newRules.Add( new CheckPoint_Rule_With_SubPoliciesIndex(SubPoliciesIndex: SubPoliciesIndex, CheckPoint_Rule: newRule)); + newRules.Add(new CheckPoint_Rule_With_SubPoliciesIndex(SubPoliciesIndex: SubPoliciesIndex, CheckPoint_Rule: newRule)); } if (newRule.ConversionIncidentType != ConversionIncidentType.None) @@ -5277,7 +5278,7 @@ void SubMatchNATRulesIntoFirewallPolicy() { foreach (Thread t in threads) { - if (t.IsAlive) + if (t.IsAlive) t.Join(); } } @@ -5296,7 +5297,7 @@ void SubMatchNATRulesIntoFirewallPolicy() { for (int ruleNumber2 = 0; ruleNumber2 < newRules.Count; ruleNumber2++) { - if ( newRules[ruleNumber].CheckPoint_Rule.CompareTo(newRules[ruleNumber2].CheckPoint_Rule) && ruleNumber != ruleNumber2 && newRules[ruleNumber].SubPoliciesIndex == newRules[ruleNumber2].SubPoliciesIndex) + if (newRules[ruleNumber].CheckPoint_Rule.CompareTo(newRules[ruleNumber2].CheckPoint_Rule) && ruleNumber != ruleNumber2 && newRules[ruleNumber].SubPoliciesIndex == newRules[ruleNumber2].SubPoliciesIndex) { newRules.Remove(newRules[ruleNumber2]); @@ -5637,7 +5638,7 @@ private bool IsFirewallRuleMatchedByNATRule(CheckPoint_Zone parentLayerRuleZone, return true; } - if (fwRule.Service.Count == 0) {} + if (fwRule.Service.Count == 0) { } else if (fwRule.Service.Count == 1 && fwRule.Service[0].Name == CheckPointObject.Any) { // There is only one service in FW rule and it is "any", no matter what NAT rule service is... @@ -6180,23 +6181,23 @@ public void ExportManagmentReport(bool optimazed) int so_count = 0; int se_count = 0; int de_count = 0; - foreach(var layer in NewCiscoAnalizStatistic._Package.SubPolicies) + foreach (var layer in NewCiscoAnalizStatistic._Package.SubPolicies) { - foreach(var policy in layer.Rules) + foreach (var policy in layer.Rules) { bool any_fl = true; if (!policy.Enabled) { dis += 1; } - if(policy.Comments == null || policy.Comments == "") + if (policy.Comments == null || policy.Comments == "") { NewCiscoAnalizStatistic._uncommentedServicesRulesCount++; } - if(policy.Destination.Count > 0 && policy.Destination.First().Name.Equals("Any")) + if (policy.Destination.Count > 0 && policy.Destination.First().Name.Equals("Any")) { de_count++; - if(any_fl) + if (any_fl) { all++; any_fl = false; @@ -6225,7 +6226,7 @@ public void ExportManagmentReport(bool optimazed) } } } - foreach(var policy in NewCiscoAnalizStatistic._Package.ParentLayer.Rules) + foreach (var policy in NewCiscoAnalizStatistic._Package.ParentLayer.Rules) { bool any_fl = true; if (!policy.Enabled) @@ -6279,7 +6280,7 @@ public void ExportManagmentReport(bool optimazed) if (_cpPackages.Count > 0) { this.OptimizationPotential = RulesInConvertedPackage() > 0 ? ((RulesInConvertedPackage() - RulesInConvertedOptimizedPackage()) * 100 / (float)RulesInConvertedPackage()) : 0; - + ExportManagmentReport(); } @@ -6984,7 +6985,7 @@ public int WarningsInConvertedPackage() { return _warningsList.Count; } - + public int ErrorsInConvertedPackage() { return _errorsList.Count; @@ -7104,7 +7105,7 @@ public void CalculateCorrectAll(List _cpNetworks, _unrulesServicesutilizingServicesAnyDestinationCount = _rulesServicesutilizingServicesAnyDestinationCount; _unrulesServicesutilizingServicesAnyServiceCount = _rulesServicesutilizingServicesAnyServiceCount; _untimesServicesRulesCount = _timesServicesRulesCount; - _totalNetworkObjectsCount = _cpNetworks.Count + _cpHosts.Count + _cpNetworkGroups.Count + _cpRanges.Count; + _totalNetworkObjectsCount = _cpNetworks.Count + _cpHosts.Count + _cpNetworkGroups.Count + _cpRanges.Count; //DUPLICATE CALCULATION foreach (var item in _cpNetworks) diff --git a/CiscoMigration/CiscoParser.cs b/CiscoMigration/CiscoParser.cs index 5b17172..bfcff87 100644 --- a/CiscoMigration/CiscoParser.cs +++ b/CiscoMigration/CiscoParser.cs @@ -147,7 +147,7 @@ private void chengeLines(List newLines, int index, string ip) inserIndex -= 1; } newLines.Insert(inserIndex, "object network " + ip); - newLines.Insert(inserIndex+1, " host " + ip); + newLines.Insert(inserIndex + 1, " host " + ip); } } @@ -171,12 +171,12 @@ private void ParseCommands(string filename) int prevIndentationLevel = 0; int lineId = 0; - + foreach (string line in lines) { lineId++; - - + + // Check for an empty line or line with just spaces. if (line.Trim().Length == 0) diff --git a/CommonUtils/Helper.cs b/CommonUtils/Helper.cs index fcd570c..0eabe95 100644 --- a/CommonUtils/Helper.cs +++ b/CommonUtils/Helper.cs @@ -12,7 +12,7 @@ public static List RemoveDuplicates(List originalList) { HashSet list = new HashSet(); - foreach(string str in originalList) + foreach (string str in originalList) { list.Add(str); } diff --git a/CommonUtils/JsonReport.cs b/CommonUtils/JsonReport.cs index 50f44e2..1908167 100644 --- a/CommonUtils/JsonReport.cs +++ b/CommonUtils/JsonReport.cs @@ -14,17 +14,17 @@ public class JsonReport { [DataMember] public string msg { get; set; } - + [DataMember(EmitDefaultValue = false)] public string warning { get; set; } - + [DataMember(EmitDefaultValue = false)] public string error { get; set; } - public JsonReport() {} - public JsonReport (string msg, string err = null, string warning = null) : this() + public JsonReport() { } + public JsonReport(string msg, string err = null, string warning = null) : this() { this.msg = msg; if (err != null) @@ -55,7 +55,8 @@ public class TotalJsonReport [DataMember(Name = "Conversion errors")] public int errors { get; set; } - public TotalJsonReport() { + public TotalJsonReport() + { errors = 0; warnings = 0; } diff --git a/FortinetMigration/FortiGateAnalizStatic.cs b/FortinetMigration/FortiGateAnalizStatic.cs index adf5aa3..7cad572 100644 --- a/FortinetMigration/FortiGateAnalizStatic.cs +++ b/FortinetMigration/FortiGateAnalizStatic.cs @@ -83,11 +83,11 @@ private void CalculateCorrectNetwork() { vs.RemoveAll(vv => item.Service != null ? (vv == item.Service.Name) : false || item.Source != null ? (vv == item.Source.Name) : false || item.Destination != null ? (vv == item.Destination.Name) : false); } - foreach(var package in _cpPackages) + foreach (var package in _cpPackages) { foreach (var rule in package.ParentLayer.Rules) { - foreach(var dest in rule.Destination) + foreach (var dest in rule.Destination) { if (typeof(CheckPoint_Network) == dest.GetType()) networks.RemoveAll(nn => nn.Subnet == ((CheckPoint_Network)dest).Subnet); diff --git a/FortinetMigration/FortiGateConverter.cs b/FortinetMigration/FortiGateConverter.cs index 7a079b8..e885f5f 100644 --- a/FortinetMigration/FortiGateConverter.cs +++ b/FortinetMigration/FortiGateConverter.cs @@ -36,9 +36,9 @@ public class FortiGateConverter : VendorConverter private List _errorsList = new List(); //storing conversion errors for config or each VDOM private List _warningsList = new List(); //storing conversion warnings for config or each VDOM - + private HashSet _skippedNames = new HashSet(); //if objects was skipped by error of validation here need to be placed his name - + private Dictionary> _localMapperFgCp = new Dictionary>(); //storing map of FG names to CheckPoint objects private Dictionary> _interfacesMapperFgCp = new Dictionary>(); //storing information about interfaces @@ -186,7 +186,7 @@ public void ExportManagmentReport(bool optimazed) } else { - + int optimazed_count = 0; if (_cpPackages.Count > 1) @@ -254,7 +254,7 @@ public void ExportManagmentReport(bool optimazed) { NewFortigateAnalizStatistic._uncommentedServicesRulesCount++; } - if(policy.Enabled == false) + if (policy.Enabled == false) { NewFortigateAnalizStatistic._disabledServicesRulesCount++; } @@ -330,11 +330,11 @@ public void ExportManagmentReport(bool optimazed) NewFortigateAnalizStatistic._totalServicesRulesOptCount = optimazed_count; } - this.OptimizationPotential = RulesInConvertedPackage() > 0 ? ((RulesInConvertedPackage() - RulesInConvertedOptimizedPackage()) * 100 / (float)RulesInConvertedPackage()) : 0; - NewFortigateAnalizStatistic.CalculateCorrectAll(_cpNetworks, _cpNetworkGroups, _cpHosts, _cpRanges, _cpTcpServices, _cpUdpServices, _cpSctpServices, _cpIcmpServices, _cpDceRpcServices, _cpOtherServices, _cpServiceGroups); - ExportManagmentReport(); - OptimizationPotential = -1; - TotalRules += NewFortigateAnalizStatistic._totalServicesRulesCount; + this.OptimizationPotential = RulesInConvertedPackage() > 0 ? ((RulesInConvertedPackage() - RulesInConvertedOptimizedPackage()) * 100 / (float)RulesInConvertedPackage()) : 0; + NewFortigateAnalizStatistic.CalculateCorrectAll(_cpNetworks, _cpNetworkGroups, _cpHosts, _cpRanges, _cpTcpServices, _cpUdpServices, _cpSctpServices, _cpIcmpServices, _cpDceRpcServices, _cpOtherServices, _cpServiceGroups); + ExportManagmentReport(); + OptimizationPotential = -1; + TotalRules += NewFortigateAnalizStatistic._totalServicesRulesCount; } } @@ -1424,7 +1424,7 @@ public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List } } - if(_cpPackages.Count > 0) + if (_cpPackages.Count > 0) { Add_Optimized_Package(); foreach (var sub_policy in _cpPackages[1].SubPolicies) @@ -1509,7 +1509,7 @@ public override float Analyze() if (_vDomNames.Count > 0) // create HTML files which contain links to each report { - CreateCatalogExportManagment(); + CreateCatalogExportManagment(); } VendorHtmlFile = _vendorFilePath; @@ -3484,7 +3484,8 @@ private void Add_Optimized_Package() public void Add_Package(List fgCommandsList, bool convertNat, string commentPhraze) { - if (IsConsoleRunning) { + if (IsConsoleRunning) + { Console.WriteLine(commentPhraze); Progress.SetProgress(70); Thread.Sleep(1000); @@ -3751,7 +3752,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman { string fgScheduleRule = fgCommand_Set.Value.Trim('"'); - if(!fgScheduleRule.Equals("always")) + if (!fgScheduleRule.Equals("always")) { NewFortigateAnalizStatistic._timesServicesRulesCount++; } @@ -4001,7 +4002,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman realRulesList.Add(cpRule); NewFortigateAnalizStatistic._totalServicesRulesCount++; - if(in_service) NewFortigateAnalizStatistic._rulesServicesutilizingServicesAnyCount++; + if (in_service) NewFortigateAnalizStatistic._rulesServicesutilizingServicesAnyCount++; _rulesInConvertedPackage += 1; if (cpRuleUG != null) @@ -4116,7 +4117,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman } package.ParentLayer.Rules.AddRange(newRootRulesList); - + foreach (string key in extraZonesMap.Keys) { if (key.Contains("any")) @@ -5660,7 +5661,7 @@ public class FgInterface public class FgStaticRoute { public FgStaticRoute() { } - public FgStaticRoute (string name, string network, string mask, string gateway, string device) : this() + public FgStaticRoute(string name, string network, string mask, string gateway, string device) : this() { Name = string.IsNullOrEmpty(name) ? string.Empty : name; Network = string.IsNullOrEmpty(network) ? string.Empty : network; @@ -5788,7 +5789,7 @@ public void CalculateCorrectAll(List _cpNetworks, //DUPLICATE CALCULATION foreach (var item in _cpNetworks) { - if (_cpNetworks.Where(nt => nt.Netmask == item.Netmask & nt.Subnet == nt.Subnet).Count() > 1) { _duplicateNetworkObjectsCount++; } + if (_cpNetworks.Where(nt => nt.Netmask == item.Netmask & nt.Subnet == nt.Subnet).Count() > 1) { _duplicateNetworkObjectsCount++; } } foreach (var item in _cpHosts) { diff --git a/FortinetMigration/FortiGateParser.cs b/FortinetMigration/FortiGateParser.cs index 72ce645..130f62c 100644 --- a/FortinetMigration/FortiGateParser.cs +++ b/FortinetMigration/FortiGateParser.cs @@ -83,7 +83,7 @@ private void ParseCommands(string filename) // Check for weird stuff if (line.StartsWith("#")) { - if(line.StartsWith("#config-version=") && line.Contains(":")) + if (line.StartsWith("#config-version=") && line.Contains(":")) { ParseVersion(line); } diff --git a/JuniperMigration/JuniperAnalizStatistic.cs b/JuniperMigration/JuniperAnalizStatistic.cs index 4ebc526..89bdebb 100644 --- a/JuniperMigration/JuniperAnalizStatistic.cs +++ b/JuniperMigration/JuniperAnalizStatistic.cs @@ -113,7 +113,7 @@ public override void CalculateRules(List _cpPackages, _optimizationServicesPotentialCount = _disabledServicesRulesCount + _unnamedServicesRulesCount + _timesServicesRulesCount + - _nonServicesLoggingServicesRulesCount; + _nonServicesLoggingServicesRulesCount; } diff --git a/JuniperMigration/JuniperConverter.cs b/JuniperMigration/JuniperConverter.cs index 0d5f40d..76b6aa4 100644 --- a/JuniperMigration/JuniperConverter.cs +++ b/JuniperMigration/JuniperConverter.cs @@ -159,7 +159,7 @@ public enum RulePriority public bool IsStaticMirrorRule { get; set; } public List SourceZonesOrInterfaces = new List(); } - + #endregion #region Private Members @@ -1710,13 +1710,13 @@ private void Add_ServiceObjects() AddCheckPointObject(serviceGroup); } } - private void Add_Schedulers() + private void Add_Schedulers() { List cpTimeRangesNamesUniq = new List(); foreach (Juniper_Scheduler scheduler in _juniperParser.Filter("_Scheduler")) { List timesList = new List();//will store time-objects for separate days with different hours-ranges - + int postfixIndex = 1;//postfix of time-object in case Juniper scheduler is split to several objects if (scheduler.StartStopDates.Count == 0) @@ -1725,13 +1725,14 @@ private void Add_Schedulers() cpTime.Comments = "Old Time Object name: " + scheduler.Name; cpTime.StartNow = true; cpTime.EndNever = true; - cpTime.Name = checkTimeNameLength(scheduler.Name, cpTimeRangesNamesUniq); - + cpTime.Name = checkTimeNameLength(scheduler.Name, cpTimeRangesNamesUniq); + Add_TimeObject(scheduler, cpTime, timesList, cpTimeRangesNamesUniq); foreach (CheckPoint_Time time in timesList) AddCheckPointObject(time); } - else { + else + { foreach (string sdate in scheduler.StartStopDates) //create separate time-object for each start-date { CheckPoint_Time cpTime = new CheckPoint_Time(); @@ -1739,7 +1740,7 @@ private void Add_Schedulers() //2020-09-06.01:01;2020-09-08.12:30 if (scheduler.StartStopDates.Count == 1) { - cpTime.Name = checkTimeNameLength(scheduler.Name, cpTimeRangesNamesUniq); + cpTime.Name = checkTimeNameLength(scheduler.Name, cpTimeRangesNamesUniq); } else { @@ -1751,8 +1752,8 @@ private void Add_Schedulers() while (cpTimeRangesNamesUniq.Contains(cpTime.Name)) { cpTime.Name = scheduler.Name.Substring(0, 8) + "_" + postfixIndex++; - } - } + } + } } cpTime.StartNow = false; DateTime date = DateTime.ParseExact(sdate.Substring(0, sdate.IndexOf(";")), "yyyy-MM-dd.HH:mm", CultureInfo.InvariantCulture); @@ -1763,13 +1764,13 @@ private void Add_Schedulers() date = DateTime.ParseExact(sdate.Substring(sdate.IndexOf(";") + 1), "yyyy-MM-dd.HH:mm", CultureInfo.InvariantCulture); cpTime.EndDate = date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture).Trim(); cpTime.EndTime = date.ToString("HH:mm").Trim(); - + Add_TimeObject(scheduler, cpTime, timesList, cpTimeRangesNamesUniq); foreach (CheckPoint_Time time in timesList) AddCheckPointObject(time); - } - } + } + } } } @@ -1816,7 +1817,7 @@ private List Add_TimeObject(Juniper_Scheduler scheduler, CheckP cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Daily; processHoursRanges(scheduler.patternDictionary[day], cpTime); - + timesList.Add(cpTime); cpTimeRangesNamesUniq.Add(cpTime.Name); } @@ -1825,16 +1826,16 @@ private List Add_TimeObject(Juniper_Scheduler scheduler, CheckP cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Weekly; if (scheduler.patternDictionary[day][0].Equals("all-day")) - { + { cpTime.RecurrenceWeekdays.Add((CheckPoint_Time.Weekdays)daysList.IndexOf(day)); - + timesList.Add(cpTime); cpTimeRangesNamesUniq.Add(cpTime.Name); } else if (scheduler.patternDictionary[day][0].Equals("exclude")) { if (!daysAreAddedToPattern && dailyIsConfigured) - { + { if (!cpTime.RecurrenceWeekdays.Contains(CheckPoint_Time.Weekdays.Sun)) cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Sun); if (!cpTime.RecurrenceWeekdays.Contains(CheckPoint_Time.Weekdays.Mon)) @@ -1877,7 +1878,7 @@ private List Add_TimeObject(Juniper_Scheduler scheduler, CheckP { processHoursRanges(scheduler.patternDictionary[day], cpTimeAdd); } - + timesList.Add(cpTimeAdd); cpTimeRangesNamesUniq.Add(cpTimeAdd.Name); } @@ -1891,7 +1892,7 @@ private List Add_TimeObject(Juniper_Scheduler scheduler, CheckP cpTimeRangesNamesUniq.Add(cpTime.Name); } - return timesList; + return timesList; } /// @@ -1903,12 +1904,12 @@ private void processHoursRanges(List timeRanges, CheckPoint_Time cpTime) { if (timeRange.IndexOf(";") != -1) { - string startTime = timeRange.Substring(0, timeRange.IndexOf(";")); + string startTime = timeRange.Substring(0, timeRange.IndexOf(";")); string stopTime = timeRange.Substring(timeRange.IndexOf(";") + 1); TimeSpan timeCheck0; if (startTime.Length > 6) timeCheck0 = TimeSpan.ParseExact(startTime, "hh\\:mm\\:ss", CultureInfo.InvariantCulture); - else timeCheck0 = TimeSpan.ParseExact(startTime, "hh\\:mm", CultureInfo.InvariantCulture); + else timeCheck0 = TimeSpan.ParseExact(startTime, "hh\\:mm", CultureInfo.InvariantCulture); TimeSpan timeCheck1; if (stopTime.Length > 6) timeCheck1 = TimeSpan.ParseExact(stopTime, "hh\\:mm\\:ss", CultureInfo.InvariantCulture); else timeCheck1 = TimeSpan.ParseExact(stopTime, "hh\\:mm", CultureInfo.InvariantCulture); @@ -1917,18 +1918,19 @@ private void processHoursRanges(List timeRanges, CheckPoint_Time cpTime) { if (timeRanges.IndexOf(timeRange) == 0) { - cpTime.HoursRangesEnabled_1 = true; - cpTime.HoursRangesFrom_1 = timeCheck0.ToString(@"hh\:mm").Trim(); + cpTime.HoursRangesEnabled_1 = true; + cpTime.HoursRangesFrom_1 = timeCheck0.ToString(@"hh\:mm").Trim(); cpTime.HoursRangesTo_1 = timeCheck1.ToString(@"hh\:mm").Trim(); - } else + } + else { - cpTime.HoursRangesEnabled_2 = true; - cpTime.HoursRangesFrom_2 = timeCheck0.ToString(@"hh\:mm").Trim(); + cpTime.HoursRangesEnabled_2 = true; + cpTime.HoursRangesFrom_2 = timeCheck0.ToString(@"hh\:mm").Trim(); cpTime.HoursRangesTo_2 = timeCheck1.ToString(@"hh\:mm").Trim(); - } - } + } + } } - } + } } private CheckPoint_Package Add_Package(bool isPreExecution = false) @@ -2339,17 +2341,17 @@ private CheckPoint_Rule Juniper_To_CPRule(Juniper_PolicyRule juniperRule, string cpRule.Destination.Add(cpObject); } - + //add scheduler foreach (var scheduler in juniperRule.Scheduler) - { + { cpObject = GetCheckPointObjectOrCreateDummy(scheduler, "Time", juniperRule, "Not applying time-range objects.", "Appropriate time object should be added manually."); - cpRule.Time.Add(cpObject); - + cpRule.Time.Add(cpObject); + } // Avoid general "icmp-proto" service duplicates @@ -2362,7 +2364,7 @@ private CheckPoint_Rule Juniper_To_CPRule(Juniper_PolicyRule juniperRule, string juniperRule, "Error creating a rule, missing information for application Juniper object", "Application object details: " + application + "."); - + if (cpObject.Name == "icmp-proto") { if (hasGeneralIcmpService) @@ -4033,7 +4035,7 @@ private void MatchNATRulesIntoFirewallPolicy() { continue; } - try + try { var parentLayerRuleZone = (CheckPoint_Zone)cpParentRule.Source[0]; @@ -4047,14 +4049,15 @@ private void MatchNATRulesIntoFirewallPolicy() { continue; } - } catch (Exception ex) + } + catch (Exception ex) { if (ex.Message == "Unable to cast object of type 'CheckPointObjects.CheckPoint_NetworkGroup' to type 'CheckPointObjects.CheckPoint_Zone'.") continue; else throw ex; } - + // Get into the relevant sub-policy foreach (CheckPoint_Layer subPolicy in cpPackage.SubPolicies) @@ -4193,7 +4196,7 @@ private bool IsFirewallRuleMatchedByNATRule(CheckPoint_NAT_Rule natRule, CheckPo return true; } - if (fwRule.Service.Count == 0){} + if (fwRule.Service.Count == 0) { } else if (fwRule.Service.Count == 1 && fwRule.Service[0].Name == CheckPointObject.Any) { // There is only one service in FW rule and it is "any", no matter what NAT rule service is... @@ -4276,7 +4279,7 @@ private bool DoesJuniperApplicationMatchCheckpointPredefinedService(Juniper_Appl _juniper2CheckpointServiceDuplicates.Add(application.Name, serviceName); } #pragma warning disable CS0168 // The variable 'e' is declared but never used - catch (Exception e) {} + catch (Exception e) { } #pragma warning restore CS0168 // The variable 'e' is declared but never used application.ConversionIncidentType = ConversionIncidentType.Informative; @@ -4707,7 +4710,7 @@ private CheckPointObject GetCheckPointObjectOrCreateDummy(string cpObjectName, s cpDummyObject = new CheckPoint_ServiceGroup { Name = "_Err_in_service-line_" + juniperObject.LineNumber }; break; case "Time": - cpDummyObject = new CheckPoint_Time { Name = cpObjectName}; + cpDummyObject = new CheckPoint_Time { Name = cpObjectName }; break; } @@ -4723,7 +4726,8 @@ private CheckPointObject GetCheckPointObjectOrCreateDummy(string cpObjectName, s { errorDescription = string.Format("wildcard expression is not supported"); _conversionIncidents.Add(new ConversionIncident(juniperObject.LineNumber, "Error creating a parent layer rule", errorDescription, juniperObject.ConversionIncidentType)); - } else + } + else { errorDescription = string.Format("{0} Using dummy object: {1}.", errorDescription, cpDummyObject.Name); _conversionIncidents.Add(new ConversionIncident(juniperObject.LineNumber, errorTitle, errorDescription, juniperObject.ConversionIncidentType)); @@ -4871,7 +4875,7 @@ public override Dictionary Convert(bool convertNat) Thread.Sleep(1000); } RaiseConversionProgress(30, "Converting rules ..."); - Add_Package(); + Add_Package(); if (_cpPackages.Count > 0) { @@ -4974,7 +4978,7 @@ public override Dictionary Convert(bool convertNat) // Resolve the conversion categories/lines count to report to the user. ConversionIncidentCategoriesCount = _conversionIncidents.GroupBy(error => error.Title).Count(); ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); - + if (!_isOverMaxLengthPackageName) { CreateSmartConnector(true, false); @@ -5147,7 +5151,7 @@ public void ExportManagmentReport(bool optimazed) foreach (var policy in layer.Rules) { bool any_fl = true; - if(policy.Time.Count > 0) + if (policy.Time.Count > 0) { time_count++; } diff --git a/JuniperMigration/JuniperObjects.cs b/JuniperMigration/JuniperObjects.cs index 6ad5220..0119c2c 100644 --- a/JuniperMigration/JuniperObjects.cs +++ b/JuniperMigration/JuniperObjects.cs @@ -83,7 +83,7 @@ public class Subnet { public string IpAddress { get; set; } public string Netmask { get; set; } - + public Subnet(string ipAddress, string netmask) { IpAddress = ipAddress; @@ -693,31 +693,31 @@ public override void Parse(XElement objectNode, string zoneName) } } } - + public class Juniper_Scheduler : JuniperObject - { + { public List StartStopDates = new List(); - public Dictionary> patternDictionary = new Dictionary>(); - + public Dictionary> patternDictionary = new Dictionary>(); + public override void Parse(XElement objectNode, string zoneName) { - base.Parse(objectNode, zoneName); + base.Parse(objectNode, zoneName); var startDates = objectNode.Elements("start-date").ToList(); - + if (startDates.Count > 0) - { + { List startStop = new List(); string startStopDateString; foreach (var startDate in startDates) { - startStopDateString = startDate.Element("start-date").Value + ";" + startDate.Element("stop-date").Value; + startStopDateString = startDate.Element("start-date").Value + ";" + startDate.Element("stop-date").Value; StartStopDates.Add(startStopDateString); } } - - List days = new List { "daily", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" }; + + List days = new List { "daily", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" }; foreach (string dayKey in days) { @@ -726,12 +726,12 @@ public override void Parse(XElement objectNode, string zoneName) if (day != null) { if (day.Element("all-day") != null) - { - daysValue.Add("all-day"); + { + daysValue.Add("all-day"); } else if (day.Element("exclude") != null) - { - daysValue.Add("exclude"); + { + daysValue.Add("exclude"); } else if (day.Elements("start-time").ToList() != null) { @@ -741,12 +741,12 @@ public override void Parse(XElement objectNode, string zoneName) { startStopTimeString = startTime.Element("start-time-value").Value + ";" + startTime.Element("stop-time").Value; startStopTime.Add(startStopTimeString); - } - daysValue.AddRange(startStopTime); + } + daysValue.AddRange(startStopTime); } patternDictionary.Add(dayKey, daysValue); } - } + } } } @@ -784,14 +784,15 @@ public override void Parse(XElement objectNode, string zoneName) ConversionIncidentMessage = "Missing action information for policy rule object."; return; } - + //add scheduler var schedulerNode = objectNode.Elements("scheduler-name"); if (schedulerNode != null) { - foreach (var scheduler in schedulerNode) { - Scheduler.Add(scheduler.Value); + foreach (var scheduler in schedulerNode) + { + Scheduler.Add(scheduler.Value); } } diff --git a/JuniperMigration/JuniperParser.cs b/JuniperMigration/JuniperParser.cs index 46b71d8..7d63e24 100644 --- a/JuniperMigration/JuniperParser.cs +++ b/JuniperMigration/JuniperParser.cs @@ -41,7 +41,7 @@ public class JuniperParser : VendorParser private readonly List _juniperObjects = new List(); private readonly List _juniperGlobalPolicyRules = new List(); private readonly Dictionary> _addressNamesOverZonesLookup = new Dictionary>(StringComparer.InvariantCultureIgnoreCase); - + #endregion #region Public Methods @@ -57,7 +57,7 @@ public override void Parse(string filename) ParseInterfaces(configNode); ParseRoutes(configNode); ParseApplicationsAndGroups(configNode); - parseSchedulers(configNode); + parseSchedulers(configNode); ParsePolicy(configNode); ParsePolicyFromGroups(configNode); ParseNat(configNode); @@ -94,7 +94,7 @@ public bool IsNetworkObjectContainedInMultipleZones(string name) List addressZones; return (_addressNamesOverZonesLookup.TryGetValue(name, out addressZones) && addressZones.Count > 1); } - + #endregion #region Private Methods @@ -158,7 +158,8 @@ protected override void ParseVersion(object versionProvider) if (versionNode != null && versionNode.Value.Length > 0) { VendorVersion = Regex.Match(versionNode.Value, @"\d+(\.\d+)?").Value; - } else + } + else { if (configNode.Parent.FirstAttribute.Value.Contains("xml.juniper.net")) { @@ -354,7 +355,7 @@ private void ParseApplication(XElement application) foreach (var term in terms) { - juniperObject = new Juniper_Application { LineNumber = ((IXmlLineInfo) term).LineNumber }; + juniperObject = new Juniper_Application { LineNumber = ((IXmlLineInfo)term).LineNumber }; ((Juniper_Application)juniperObject).IsJunosDefault = termApplicationObject.Name.StartsWith("junos-"); // must come before parsing!!! ((Juniper_Application)juniperObject).ParseFromTerm(term, true); _juniperObjects.Add(juniperObject); @@ -394,14 +395,14 @@ private void ParseApplication(XElement application) _juniperObjects.Add(juniperObject); } } - + private void parseSchedulers(XElement configNode) { var schedulers = configNode.XPathSelectElements("./schedulers/scheduler"); foreach (var scheduler in schedulers) { - JuniperObject juniperScheduler = new Juniper_Scheduler(); - + JuniperObject juniperScheduler = new Juniper_Scheduler(); + juniperScheduler.Parse(scheduler, null); _juniperObjects.Add(juniperScheduler); } diff --git a/MigrationBase/SupportedVendors.cs b/MigrationBase/SupportedVendors.cs index 8932125..a8b3cba 100644 --- a/MigrationBase/SupportedVendors.cs +++ b/MigrationBase/SupportedVendors.cs @@ -43,13 +43,13 @@ public class SupportedVendors public const string PaloAltoPanoramaConfigurationFileLabel = "PaloAlto Panorama configuration files archive:"; public const string PaloAltoPanoramaProduct = "PaloAlto Panorama to Check Point Migration Tool"; public const string PaloAltoPanoramaProductDescription = "This tool supports migration of PaloAlto Panorama 7.x \nand above configuration files."; - + #endregion #region Private Members private readonly List _vendors = new List { Vendor.CiscoASA, Vendor.JuniperJunosOS, Vendor.JuniperScreenOS, Vendor.FortiGate, Vendor.PaloAlto }; - + #endregion #region Properties @@ -60,7 +60,7 @@ public List Vendors } public Vendor SelectedVendor { get; set; } - + #endregion } @@ -68,7 +68,7 @@ public List Vendors public enum Vendor { [Description("Cisco ASA")] - CiscoASA, + CiscoASA, [Description("FirePower")] FirePower, [Description("Juniper JunosOS SRX")] diff --git a/MigrationBase/VendorAnalizStatistic.cs b/MigrationBase/VendorAnalizStatistic.cs index 38893b9..e7a141c 100644 --- a/MigrationBase/VendorAnalizStatistic.cs +++ b/MigrationBase/VendorAnalizStatistic.cs @@ -35,7 +35,7 @@ public abstract class VendorAnalizStatistic public int TotalNetworkObjectsPercent { get { return 100; } } public float UnusedNetworkObjectsPercent { get { return _totalNetworkObjectsCount > 0 ? ((float)_unusedNetworkObjectsCount / (float)_totalNetworkObjectsCount) * 100 : 0; } } - public float DuplicateNetworkObjectsPercent { get { return _totalNetworkObjectsCount > 0 ? ((float)_duplicateNetworkObjectsCount / (float)_totalNetworkObjectsCount) * 100 : 0; } } + public float DuplicateNetworkObjectsPercent { get { return _totalNetworkObjectsCount > 0 ? ((float)_duplicateNetworkObjectsCount / (float)_totalNetworkObjectsCount) * 100 : 0; } } public float NestedNetworkGroupsPercent { get { return _totalNetworkObjectsCount > 0 ? ((float)_nestedNetworkGroupsCount / (float)_totalNetworkObjectsCount) * 100 : 0; } } public float TotalServicesObjectsPercent { get { return 100; } } diff --git a/MigrationBase/VendorConverter.cs b/MigrationBase/VendorConverter.cs index 6cebcf6..d21bcac 100644 --- a/MigrationBase/VendorConverter.cs +++ b/MigrationBase/VendorConverter.cs @@ -129,11 +129,12 @@ public abstract class VendorConverter public string ErrorsHtmlFile { get; set; } public int ConversionIncidentCategoriesCount { get; set; } public int ConversionIncidentsCommandsCount { get; set; } - public bool IsConsoleRunning { - get - { - return _calledFromConsole; - } + public bool IsConsoleRunning + { + get + { + return _calledFromConsole; + } set { _calledFromConsole = value; @@ -1596,7 +1597,7 @@ protected void CreateObjectsHtml() for (int i = 0; i < obj.Members.Count; i += groupsMaxBulkSize) { file.WriteLine("
"); - + obj.MembersPublishIndex = i; file.WriteLine(obj.ToCLIScript()); @@ -2174,7 +2175,8 @@ public void CreateSmartConnector(bool isNeedGenOpt = false, bool isCurrentOptimi i += 250000; File.AppendAllText(cpObjectsJsonPath + cpObjectsJsonFN, JsonConvert.SerializeObject(dest, Formatting.Indented)); } - } else File.WriteAllText(cpObjectsJsonPath + cpObjectsJsonFN, JsonConvert.SerializeObject(cpJsonObjects, Formatting.Indented)); + } + else File.WriteAllText(cpObjectsJsonPath + cpObjectsJsonFN, JsonConvert.SerializeObject(cpJsonObjects, Formatting.Indented)); string smartConnectorArchiveName = "smartconnector_" + _vendorFileName; string smartConnectorArchivePath = _targetFolder + Path.DirectorySeparatorChar + smartConnectorArchiveName; @@ -2387,7 +2389,7 @@ private void CreateZip(string compressorsDirPath, string[] pySmartConnectorFNs, if (isOptNeeded) { - if (!File.Exists(cpObjectsJsonPath + optimizedNameJson)) + if (!File.Exists(cpObjectsJsonPath + optimizedNameJson)) return; } diff --git a/MigrationBase/VendorParser.cs b/MigrationBase/VendorParser.cs index 7f760a8..2924f30 100644 --- a/MigrationBase/VendorParser.cs +++ b/MigrationBase/VendorParser.cs @@ -27,7 +27,7 @@ public abstract class VendorParser #region Private Members protected string VendorVersion = ""; - + #endregion #region Properties diff --git a/NetScreenMigration/ScreenOSCommands.cs b/NetScreenMigration/ScreenOSCommands.cs index 6f87430..60d240a 100644 --- a/NetScreenMigration/ScreenOSCommands.cs +++ b/NetScreenMigration/ScreenOSCommands.cs @@ -63,7 +63,7 @@ public string Text List tempArrayList = trimmedText.Split(delimiterChars).ToList(); // Gather strings with spaces between quotes - for (int i = 0; i < tempArrayList.Count;++i) + for (int i = 0; i < tempArrayList.Count; ++i) { if (tempArrayList[i].First() == '\"' && tempArrayList[i].Last() != '\"') { @@ -146,7 +146,7 @@ public virtual void Parse(ScreenOSCommand command) NotAnInterestingCommand = true; } } - + public int GetNumOfParams() { if (_words == null) @@ -237,14 +237,14 @@ public static bool IsInQuotation(string str) } } - public class ScreenOSCommand_Address: ScreenOSCommand + public class ScreenOSCommand_Address : ScreenOSCommand { public enum AddressTypeEnum { NA, Host, Network, Domain }; private string _zone = ""; private string _objectName = ""; private string _mask = ""; - + public AddressTypeEnum AddressType { get; set; } public string IpAddress { get; set; } public string Domain { get; set; } @@ -308,7 +308,7 @@ public ScreenOSCommand_Address() public override void Parse(ScreenOSCommand command) { base.Parse(command); - + // Check if base parse marked the command as interesting if (NotAnInterestingCommand) { @@ -342,7 +342,7 @@ public override void Parse(ScreenOSCommand command) ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("ScreenOS address object with complex wildcard mask {0} is not supported. Using subnet 1.1.1.0/255.255.255.0", commandParam); } - else if(string.IsNullOrEmpty(commandParam) || IsInQuotation(commandParam)) + else if (string.IsNullOrEmpty(commandParam) || IsInQuotation(commandParam)) { Domain = command.GetParam(4); AddressType = AddressTypeEnum.Domain; @@ -358,7 +358,7 @@ public override void Parse(ScreenOSCommand command) if (IsInQuotation(commandParam)) { Comment = commandParam; - } + } } } @@ -396,7 +396,7 @@ public ScreenOSCommand_GroupAddress() public override void Parse(ScreenOSCommand command) { base.Parse(command); - + // Check if base parse marked the command as interesting if (NotAnInterestingCommand) { @@ -432,7 +432,7 @@ public enum TimeOutUnitsEnum { Minutes, TenSeconds }; private readonly int _maxTimeout = 2160; private string _serviceName = ""; - + public int TimeOut { get; set; } public TimeOutUnitsEnum TimeOutUnits { get; set; } public bool IsSessionCacheEnabled { get; set; } @@ -465,7 +465,7 @@ public ScreenOSCommand_Service() public override void Parse(ScreenOSCommand command) { base.Parse(command); - + // Check if base parse marked the command as interesting if (NotAnInterestingCommand) { @@ -529,10 +529,10 @@ public override void Parse(ScreenOSCommand command) if (commandString == "session-cache") { - ConversionIncidentMessage = commandString ; + ConversionIncidentMessage = commandString; IsSessionCacheEnabled = true; commandString = command.GetParam(++index); - + } if (commandString == "timeout") @@ -598,7 +598,7 @@ public string ServiceObjectName get { return _serviceObjectName.Trim('"'); } set { _serviceObjectName = value; } } - + public ScreenOSCommand_GroupService() { KnownCommand = true; @@ -674,7 +674,7 @@ public override void Parse(ScreenOSCommand command) ObjectName = command.GetParam(2); IpAddressFirst = command.GetParam(3); IpAddressLast = command.GetParam(4); - + if (!NetworkUtils.IsValidIpv4(IpAddressFirst) || !NetworkUtils.IsValidIpv4(IpAddressLast) || NetworkUtils.Ip2Number(IpAddressLast) < NetworkUtils.Ip2Number(IpAddressFirst)) @@ -690,8 +690,8 @@ public class ScreenOSCommand_Zone : ScreenOSCommand private string _zoneName = ""; public static string[] PredefinedZones = { "Trust", "Untrust", "DMZ" }; - public static string[] SpecialPredefinedZones = { "MGT" , "Null" , "Untrust-Tun", "V1-Null", "V1-Trust", "V1-Untrust" , "V1-DMZ" }; - public static string[] UnsupportedPredefinedZones = { "HA", "VLAN"}; + public static string[] SpecialPredefinedZones = { "MGT", "Null", "Untrust-Tun", "V1-Null", "V1-Trust", "V1-Untrust", "V1-DMZ" }; + public static string[] UnsupportedPredefinedZones = { "HA", "VLAN" }; public static string Global = "Global"; public bool IsPredefinedZones { get; set; } @@ -731,7 +731,7 @@ public override void Parse(ScreenOSCommand command) string commandParam = command.GetParam(2); if (IsInQuotation(commandParam)) { - if(PredefinedZones.Contains(commandParam.Trim('"'))) + if (PredefinedZones.Contains(commandParam.Trim('"'))) { IsPredefinedZones = true; } @@ -758,7 +758,7 @@ public override void Parse(ScreenOSCommand command) } } else if (commandParam == "id") - { + { // New definition of zone int zoneId = 0; if (int.TryParse(command.GetParam(3), out zoneId)) @@ -814,7 +814,7 @@ public enum InterfaceObjectTypeEnum { NA, Ip, Zone, Nat, Dip, Mip, Vip }; private string _zone = ""; - public string InterfaceName { get; set; } + public string InterfaceName { get; set; } public string IP { get; set; } public string Mask { get; set; } public bool IsSecondery { get; set; } @@ -874,7 +874,7 @@ public override void Parse(ScreenOSCommand command) case "tag": InterfaceObjectType = InterfaceObjectTypeEnum.Zone; - index+=3; + index += 3; break; case "nat": @@ -955,9 +955,9 @@ public bool CheckIfInterfaceIsGateway(string gateway) } if (InterfaceObjectType == InterfaceObjectTypeEnum.Ip && - NetworkUtils.GetNetwork(IP,Mask) == NetworkUtils.GetNetwork(gateway, Mask)) + NetworkUtils.GetNetwork(IP, Mask) == NetworkUtils.GetNetwork(gateway, Mask)) { - return true; + return true; } // Check inside children @@ -985,8 +985,8 @@ public class ScreenOSCommand_Route : ScreenOSCommand public string Interface { get; set; } public string Gateway { get; set; } public string Description { get; set; } - public int Metric { get; set; } - public bool IsPermanent { get; set; } + public int Metric { get; set; } + public bool IsPermanent { get; set; } public bool DefaultRoute { @@ -1070,7 +1070,7 @@ public override void Parse(ScreenOSCommand command) public class ScreenOSCommand_Policy : ScreenOSCommand { - public enum ActoinEnum { Na, Permit, Reject, Deny}; + public enum ActoinEnum { Na, Permit, Reject, Deny }; public enum PolicyNatTypeEnum { Na, Policy, Vip, Mip, Dip, PolicyBaseDest, PolicyBaseSrcDest }; public int PolicyId { get; set; } @@ -1267,7 +1267,7 @@ public override void Parse(ScreenOSCommand command) } public static PolicyNatTypeEnum GetDestNatType(string destObjName) - { + { if (destObjName.Trim('"') == "Any" || destObjName.Trim('"').Length < 4) { return PolicyNatTypeEnum.Policy; @@ -1343,7 +1343,7 @@ private PolicyNatTypeEnum ParseNatPart(ScreenOSCommand command, ref int baseInde } } - public class ScreenOsCommand_InterfceNatDIP: ScreenOSCommand + public class ScreenOsCommand_InterfceNatDIP : ScreenOSCommand { private readonly int _baseIndex = 3; private bool _isPATEnabled; @@ -1384,18 +1384,18 @@ public ScreenOsCommand_InterfceNatDIP() public override void Parse(ScreenOSCommand command) { int paramIndex = command.GetParamPosition("dip"); - + if (paramIndex < _baseIndex) { NotAnInterestingCommand = true; return; } - + if (paramIndex != _baseIndex) { ConversionIncidentType = ConversionIncidentType.Informative; List notSupportedParams = command.GetParams(3, paramIndex - 3); - ConversionIncidentMessage = string.Join(" ", notSupportedParams.ToArray()) + ", " ; + ConversionIncidentMessage = string.Join(" ", notSupportedParams.ToArray()) + ", "; } // Get Dip Id @@ -1466,7 +1466,7 @@ public ScreenOsCommand_GroupNatDIP() public override void Parse(ScreenOSCommand command) { - int paramIndex = _baseIndex; + int paramIndex = _baseIndex; // Get group Dip Id string commandParam = command.GetParam(paramIndex); @@ -1475,7 +1475,7 @@ public override void Parse(ScreenOSCommand command) { GroupDipId = tempInt; } - else + else { NotAnInterestingCommand = true; return; @@ -1569,7 +1569,7 @@ public override void Parse(ScreenOSCommand command) else { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "ScreenOS interface object with MIP instruction, option " + commandParam + " is not supported. Ignoring command"; + ConversionIncidentMessage = "ScreenOS interface object with MIP instruction, option " + commandParam + " is not supported. Ignoring command"; return; } @@ -1616,7 +1616,7 @@ public VipInfo() public string Vip { get; set; } public bool ShuoldUseInterfcaeIp { get; set; } - public VipInfo VipData { get; set; } + public VipInfo VipData { get; set; } public ScreenOsCommand_InterfceNatVIP() { diff --git a/NetScreenMigration/ScreenOSConverter.cs b/NetScreenMigration/ScreenOSConverter.cs index 3486621..5b8a8fa 100644 --- a/NetScreenMigration/ScreenOSConverter.cs +++ b/NetScreenMigration/ScreenOSConverter.cs @@ -689,11 +689,12 @@ private List PolicySimplifiedList #pragma warning disable CS0108 // 'ScreenOSConverter._outputFormat' hides inherited member 'VendorConverter._outputFormat'. Use the new keyword if hiding was intended. private string _outputFormat { get; set; } #pragma warning restore CS0108 // 'ScreenOSConverter._outputFormat' hides inherited member 'VendorConverter._outputFormat'. Use the new keyword if hiding was intended. - private string OutputFormat { - get - { - return _outputFormat; - } + private string OutputFormat + { + get + { + return _outputFormat; + } set { _outputFormat = value; @@ -1777,7 +1778,7 @@ private CheckPointObject GetCheckPointServiceObjByName(string serviceName) return null; } } - + string objName = ScreenOS2CheckPointServicesNameDic[serviceName]; return _cpObjects.GetObject(objName); } @@ -1904,7 +1905,7 @@ private CheckPointObject GetSrcObjectFromPolicyForNAT(PolicyCommandSimplifier po foreach (string src in policy.SrcAddr) { - srcGroup.Members.Add(GetSrcObjectByNameFromPolicy(src, policy,true).Name); + srcGroup.Members.Add(GetSrcObjectByNameFromPolicy(src, policy, true).Name); } AddCheckPointObject(srcGroup); @@ -1971,7 +1972,7 @@ private CheckPointObject GetDstObjectFromPolicyForNAT(PolicyCommandSimplifier po foreach (string dst in policy.DstAddr) { - dstGroup.Members.Add(GetDstObjectByNameFromPolicy(dst, policy,true).Name); + dstGroup.Members.Add(GetDstObjectByNameFromPolicy(dst, policy, true).Name); } AddCheckPointObject(dstGroup); @@ -1980,7 +1981,7 @@ private CheckPointObject GetDstObjectFromPolicyForNAT(PolicyCommandSimplifier po } else { - dstOrig = GetDstObjectByNameFromPolicy(policy.DstAddr.First(), policy,true); + dstOrig = GetDstObjectByNameFromPolicy(policy.DstAddr.First(), policy, true); } return dstOrig; @@ -2300,7 +2301,7 @@ private bool IsZoneAvailable(string zoneName, ScreenOSCommand command) CheckPointObject cpZone = _cpObjects.GetObject(zoneName); if (zoneName != ScreenOSCommand_Zone.Global && cpZone == null) { - if(ScreenOSCommand_Zone.SpecialPredefinedZones.Contains(zoneName)) + if (ScreenOSCommand_Zone.SpecialPredefinedZones.Contains(zoneName)) { /* Create predefined special zone*/ cpZone = new CheckPoint_Zone(); @@ -2384,7 +2385,7 @@ private void Add_AddressAndGroupAddress() cpNetwork.ConvertedCommandId = address.Id; cpNetwork.Comments = address.Comment; ApplyConversionIncidentOnCheckPointObject(cpNetwork, address); - inMultipleZones = IsNetworkObjectContainedInMultipleZones(cpNetwork, address); + inMultipleZones = IsNetworkObjectContainedInMultipleZones(cpNetwork, address); if (!inMultipleZones) { CheckObjectNameValidity(cpNetwork, address, false); @@ -2496,7 +2497,7 @@ private void Add_InterfacesAndRoutes() { continue; } - + /* Create check point Network group for interface */ CheckPoint_NetworkGroup netGroup = new CheckPoint_NetworkGroup(); netGroup.Name = ObjectNameGenerator.InterfaceName(ifc.InterfaceObjName); @@ -2561,7 +2562,7 @@ private void Add_InterfacesAndRoutes() } } - ApplyConversionIncidentOnCheckPointObject(netGroup,ifc); + ApplyConversionIncidentOnCheckPointObject(netGroup, ifc); CheckObjectNameValidity(netGroup, ifc); AddCheckPointObject(netGroup); } @@ -3203,7 +3204,7 @@ private void MarkNatRulesNotIntersting() } private void Add_Mip_Nat() - { + { foreach (ScreenOSCommand_Policy natPolicy in ScreenOSPolicyCommands) { if (natPolicy.PolicyNatType == ScreenOSCommand_Policy.PolicyNatTypeEnum.Mip @@ -3492,8 +3493,8 @@ private void Add_Dip_Nat() List cpDipTranslatedObj; List isPATEnabled; List isEnabled; - string comment =""; - + string comment = ""; + if (!Prepare_ObjectsForDipNat(simpleDipPolicy, out cpDipOriginalObj, out cpDipTranslatedObj, out isEnabled, out isPATEnabled, out comment)) { continue; @@ -3533,7 +3534,7 @@ private void Add_PolicyBasedDestNat() CheckPointObject destIpTranslated = null; CheckPointObject destPortTranslated = null; - if (!Prepare_ObjectsForPolicyBasedDestNat( simplePolicy, out destIpTranslated, out destPortTranslated)) + if (!Prepare_ObjectsForPolicyBasedDestNat(simplePolicy, out destIpTranslated, out destPortTranslated)) { continue; } @@ -3697,13 +3698,13 @@ private void Add_InterfaceBasedLegacyNat() foreach (string ifcGroup in zoneTrustNetGroup.Members) { CheckPointObject ifcGroupObj = _cpObjects.GetObject(ifcGroup); - if(ifcGroupObj.Tag == "NAT") + if (ifcGroupObj.Tag == "NAT") { interfacesWithNAT.Add(ifcGroupObj); } } - /* If no interface with NAT attached to Trust zone, exit function*/ + /* If no interface with NAT attached to Trust zone, exit function*/ if (interfacesWithNAT.Count == 0) { return; @@ -3714,7 +3715,7 @@ private void Add_InterfaceBasedLegacyNat() { srcObj = interfacesWithNAT.First(); } - else if(zoneTrustNetGroup.Members.Count == interfacesWithNAT.Count) + else if (zoneTrustNetGroup.Members.Count == interfacesWithNAT.Count) { srcObj = zoneTrustNetGroup; } @@ -3801,7 +3802,7 @@ private void Add_InterfaceBasedLegacyNat() } } - private bool Prepare_ObjectsForPolicyBasedDestNat(PolicyCommandSimplifier simplePolicy, out CheckPointObject destIpTranslated,out CheckPointObject destPortTranslated) + private bool Prepare_ObjectsForPolicyBasedDestNat(PolicyCommandSimplifier simplePolicy, out CheckPointObject destIpTranslated, out CheckPointObject destPortTranslated) { destIpTranslated = null; destPortTranslated = null; @@ -3939,7 +3940,7 @@ private bool Prepare_ObjectsForDipNat(PolicyCommandSimplifier simplePolicy, out cpDipOriginalObj.Add(cpDipOriginalObjTemp); isEnabled.Add(false); isPATEnabled.Add(true); - + interfaceWithHostObject++; } } @@ -3950,7 +3951,7 @@ private bool Prepare_ObjectsForDipNat(PolicyCommandSimplifier simplePolicy, out comments = "ScreenOS NAT policy object does not contain any intefaces with hosts."; } else if (interfaceWithHostObject > 1) - { + { string errorTitle = string.Format("ScreenOS NAT policy object does not contain dip-id. NAT rules will be created as much as the number of attached interfaces to destination zone with host IP. NAT rules will be in a disabled mode"); string errorDescription = string.Format("Policy DIP object details: {0}.", natPolicy.Text); _conversionIncidents.Add(new ConversionIncident(natPolicy.Id, errorTitle, errorDescription, ConversionIncidentType.ManualActionRequired)); @@ -3961,7 +3962,7 @@ private bool Prepare_ObjectsForDipNat(PolicyCommandSimplifier simplePolicy, out comments = "ScreenOS NAT policy object does not contain dip-id. One NAT rule will be created according to attached interface to destination zone with host IP."; if (isEnabled.Count > 0) isEnabled[isEnabled.IndexOf(isEnabled.Last())] = simplePolicy.IsEnabled; - } + } } /* Create Objects for Dip*/ else if (GetDipObjByDipId(dipId, out ifc)) @@ -4067,14 +4068,14 @@ private void Add_NatPolicy2RegularPolicy() /* Layer not found, create new layer*/ if (!isFound) - { + { /* Find first global in parent layer*/ int firstGlobal = 0; foreach (CheckPoint_Rule layer in _cpPackages[0].ParentLayer.Rules) { if (layer.Tag == "global") { - break; + break; } firstGlobal++; } @@ -4103,7 +4104,7 @@ private void Add_NatPolicy2RegularPolicy() cpNewRule.Source.Add(cpSrcObject); cpNewRule.Destination.Add(cpDstObject); cpNewRule.Action = CheckPoint_Rule.ActionType.SubPolicy; - cpNewRule.SubPolicyName = ObjectNameGenerator.SubPolicyByZonesName(cpSrcObject.Name,cpDstObject.Name); + cpNewRule.SubPolicyName = ObjectNameGenerator.SubPolicyByZonesName(cpSrcObject.Name, cpDstObject.Name); cpNewRule.Layer = _cpPackages[0].NameOfAccessLayer; cpNewRule.Tag = "inter"; _cpPackages[0].ParentLayer.Rules.Insert(firstGlobal, cpNewRule); @@ -4113,14 +4114,14 @@ private void Add_NatPolicy2RegularPolicy() cpLayer.Name = cpRule.Layer; cpLayer.Rules.Add(cpRule); /* Copy global and clean up rules to new layer*/ - for (int index = firstGlobal + 1; index < _cpPackages[0].ParentLayer.Rules.Count;++index) + for (int index = firstGlobal + 1; index < _cpPackages[0].ParentLayer.Rules.Count; ++index) { cpLayer.Rules.Add(_cpPackages[0].ParentLayer.Rules[index].Clone()); cpLayer.Rules.Last().Layer = cpRule.Layer; } cpLayer.Rules.Last().Name = "Sub-Policy Cleanup rule"; - _cpPackages[0].SubPolicies.Insert(firstGlobal,cpLayer); + _cpPackages[0].SubPolicies.Insert(firstGlobal, cpLayer); validatePackage(_cpPackages[0]); } } @@ -4263,10 +4264,10 @@ public override Dictionary Convert(bool convertNat = false) } RaiseConversionProgress(20, "Converting objects ..."); _cpObjects.Initialize(); // must be first!!! - + foreach (CheckPointObject cpObject in _cpObjects.GetPredefinedObjects()) { - _objectNameGenerator.AddAppearanceCount(cpObject.Name,true); + _objectNameGenerator.AddAppearanceCount(cpObject.Name, true); } UploadPredefinedServices(); @@ -4762,7 +4763,7 @@ public override void ExportConfigurationAsHtml() foreach (ScreenOSCommand command in ScreenOSAllCommands) { string lineStyle = ""; - string indentation = ""; + string indentation = ""; if (!command.KnownCommand) { @@ -5121,7 +5122,7 @@ public override void ExportPolicyPackagesAsHtml() { sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); } - sbCurRuleNumberColumnTag.Append(""); + sbCurRuleNumberColumnTag.Append(""); file.WriteLine(sbCurRuleNumberColumnTag.ToString()); file.WriteLine(" " + ruleEntry.Value.Name + ""); diff --git a/NetScreenMigration/ScreenOSKnownServices.cs b/NetScreenMigration/ScreenOSKnownServices.cs index 76b736c..5734338 100644 --- a/NetScreenMigration/ScreenOSKnownServices.cs +++ b/NetScreenMigration/ScreenOSKnownServices.cs @@ -173,7 +173,7 @@ public static bool IsKnownPredefinedServiceNameInGroup(string serviceName) { foreach (KeyValuePair> pair in _screenOSPredefinedServicesGroup) { - if (pair.Value.Contains (serviceName)) + if (pair.Value.Contains(serviceName)) { return true; } @@ -187,7 +187,7 @@ public static bool IsKnownPredefinedServiceGroupName(string serviceGroupName) } /* ScreenOS Predefined service groups map to CP groups*/ - public static bool IsKnownPredefinedServiceGroupInCp(string screenOsGroupName,out string cpGroupName) + public static bool IsKnownPredefinedServiceGroupInCp(string screenOsGroupName, out string cpGroupName) { cpGroupName = ""; if (_screenOSPredefinedServicesGroupToCpGroup.ContainsKey(screenOsGroupName)) diff --git a/NetScreenMigration/ScreenOSParser.cs b/NetScreenMigration/ScreenOSParser.cs index f03835c..5b2e0ec 100644 --- a/NetScreenMigration/ScreenOSParser.cs +++ b/NetScreenMigration/ScreenOSParser.cs @@ -165,7 +165,7 @@ private ScreenOSCommand FindCommand(ScreenOSCommand command) if (relevantCommands.Contains(command.ObjectWord)) { - if(command.ObjectWord == "vsys-id") + if (command.ObjectWord == "vsys-id") { _numOfVsysInConfiguration++; } @@ -205,7 +205,7 @@ private void ParseInterfacesTopology() continue; } - if ((!string.IsNullOrEmpty(ifc.InterfaceName) && route.Interface == ifc.InterfaceObjName) + if ((!string.IsNullOrEmpty(ifc.InterfaceName) && route.Interface == ifc.InterfaceObjName) || ifc.CheckIfInterfaceIsGateway(route.Network)) { ifc.Topology.Add(new ScreenOSCommand_Interface.Subnet(route.Network, route.Mask, route)); @@ -249,7 +249,7 @@ private void HandleDuplicatedAddressName() else { _addressNamesOverZonesLookup.Add(addressName, new List { zoneName }); - } + } } } @@ -329,7 +329,7 @@ public static IList AggregateCommands(this IEnumerable AggregateService(this IEnumerable AggregateGroupService(this IEnumerable source, ScreenOSCommand_GroupService groupServiceObj) { - IEnumerable> groups = source.GroupBy( i => i.GroupName ); + IEnumerable> groups = source.GroupBy(i => i.GroupName); return groups.FirstOrDefault(g => g.Key.Equals(groupServiceObj.GroupName)).ToList(); } diff --git a/NetScreenMigration/ScreenOSServiceObjects.cs b/NetScreenMigration/ScreenOSServiceObjects.cs index 80c587a..46b0aa3 100644 --- a/NetScreenMigration/ScreenOSServiceObjects.cs +++ b/NetScreenMigration/ScreenOSServiceObjects.cs @@ -209,7 +209,7 @@ public string DstPort } public override int Parse(ScreenOSCommand command, int baseParamIndex) - { + { base.Parse(command, baseParamIndex); /* Get Ip protocol id if exist*/ @@ -246,7 +246,7 @@ public class ServiceProtocolObject_Udp : ServiceProtocolObject_Ip public override int Parse(ScreenOSCommand command, int baseParamIndex) { - int index = base.Parse(command, baseParamIndex); + int index = base.Parse(command, baseParamIndex); ProtocolType = ProtocolTypeEnum.Udp; if (SrcPort != "any") @@ -323,7 +323,7 @@ public override int Parse(ScreenOSCommand command, int baseParamIndex) { IcmpType = byte.Parse(command.GetParam(baseParamIndex + 1)); } - + /* Code*/ if (command.GetParam(baseParamIndex + 2) == "code") { @@ -376,7 +376,7 @@ public override int Parse(ScreenOSCommand command, int baseParamIndex) return baseParamIndex + 2; } - public override string ToCheckPointPortInfo(){ return Name().ToUpper() + "_" + Uuid;} + public override string ToCheckPointPortInfo() { return Name().ToUpper() + "_" + Uuid; } } public class ServiceProtocolObject_SunRPC : ServiceProtocolObject @@ -408,7 +408,7 @@ public string Program } set { - string []programValue = value.Split('-'); + string[] programValue = value.Split('-'); ProgramStart = programValue[0]; if (programValue.Length == 1) { @@ -445,7 +445,7 @@ public override int Parse(ScreenOSCommand command, int baseParamIndex) ProgramEnd = _maxProgram.ToString(); } - if(ProgramStart != ProgramEnd) + if (ProgramStart != ProgramEnd) { ConversionIncidentMessage = "ScreenOS SUN-RPC service object with program range is not supported in Check Point. Using only first program number in range"; } diff --git a/PaloAltoMigration/PA_Config.cs b/PaloAltoMigration/PA_Config.cs index 6bf5f34..ddb11af 100644 --- a/PaloAltoMigration/PA_Config.cs +++ b/PaloAltoMigration/PA_Config.cs @@ -428,7 +428,7 @@ public class PA_NatRuleEntry : PA_EntryExt public PA_DestinationTranslation DestinationTranslation { get; set; } [XmlElement("dynamic-destination-translation")] - public PA_DynamicDestinationTranslation DynamicDestinationTranslation { get;set;} + public PA_DynamicDestinationTranslation DynamicDestinationTranslation { get; set; } [XmlElement("disabled")] public string Disabled { get; set; } diff --git a/PaloAltoMigration/PaloAltoConverter.cs b/PaloAltoMigration/PaloAltoConverter.cs index ab75742..c80e008 100644 --- a/PaloAltoMigration/PaloAltoConverter.cs +++ b/PaloAltoMigration/PaloAltoConverter.cs @@ -270,7 +270,7 @@ protected string RuleItemsList2Html_pa(List ruleItems, List" + subRule.Name + ""); file.WriteLine(" " + RuleItemsList2Html(subRule.Source, subRule.SourceNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + ""); file.WriteLine(" " + RuleItemsList2Html(subRule.Destination, subRule.DestinationNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + ""); -/* */ file.WriteLine(" " + RuleItemsList2Html_pa(subRule.Service, subRuleAppsList, false, CheckPointObject.Any, ref ruleConversionIncidentType) + ""); + /* */ + file.WriteLine(" " + RuleItemsList2Html_pa(subRule.Service, subRuleAppsList, false, CheckPointObject.Any, ref ruleConversionIncidentType) + ""); file.WriteLine(" " + subRule.Action.ToString() + ""); file.WriteLine(" " + RuleItemsList2Html(subRule.Time, false, CheckPointObject.Any, ref ruleConversionIncidentType) + ""); file.WriteLine(" " + subRule.Track.ToString() + ""); @@ -984,7 +985,7 @@ public override float Analyze() } RaiseConversionProgress(70, "Optimizing Firewall rulebase ..."); - + if (IsConsoleRunning) { Progress.SetProgress(100); @@ -1094,7 +1095,7 @@ public void AnalyzePaVsysEntry(string targetFolderNew, string targetFileNameNew, //if non-optimized convert method is used then all objects are added - NewPaloAnalizStatistic._Package = Add_Optimized_Package(); + NewPaloAnalizStatistic._Package = Add_Optimized_Package(); ExportManagmentReport(true); @@ -1432,16 +1433,16 @@ public override Dictionary Convert(bool convertNat) } if (paConfig.Devices != null) { - if(paConfig.Devices.DevicesEntry != null && paConfig.Devices.DevicesEntry.Name.Equals(LOCAL_DEVICE_ENTRY_NAME)) //we parse PA config from PA + if (paConfig.Devices.DevicesEntry != null && paConfig.Devices.DevicesEntry.Name.Equals(LOCAL_DEVICE_ENTRY_NAME)) //we parse PA config from PA { - if(paConfig.Devices.DevicesEntry.Vsys != null && - paConfig.Devices.DevicesEntry.Vsys.VsysEntries != null && + if (paConfig.Devices.DevicesEntry.Vsys != null && + paConfig.Devices.DevicesEntry.Vsys.VsysEntries != null && paConfig.Devices.DevicesEntry.Vsys.VsysEntries.Count > 0) { if (paConfig.Devices.DevicesEntry.Vsys.VsysEntries.Count == 1) { ConvertPaVsysEntry(targetFolderMain, targetFileNameMain, paConfig.Devices.DevicesEntry.Vsys.VsysEntries[0], - s_TagEntries, + s_TagEntries, s_cpAddressesDict, s_cpNetGroupsDict, s_cpServicesDict, @@ -1460,7 +1461,7 @@ public override Dictionary Convert(bool convertNat) string targetFolderVsys = targetFolderMain + "\\" + paVsysName; System.IO.Directory.CreateDirectory(targetFolderVsys); ConvertPaVsysEntry(targetFolderVsys, paVsysName, paVsysEntry, - s_TagEntries, + s_TagEntries, s_cpAddressesDict, s_cpNetGroupsDict, s_cpServicesDict, @@ -1528,13 +1529,13 @@ public override Dictionary Convert(bool convertNat) } public void ConvertPaVsysEntry(string targetFolderNew, string targetFileNameNew, PA_VsysEntry paVsysEntry, - List s_TagEntries, + List s_TagEntries, Dictionary s_cpAddressesDict, Dictionary s_cpNetGroupsDict, Dictionary s_cpServicesDict, Dictionary s_paServicesTypesDict, Dictionary s_cpServicesGroupsDict, - List s_paAppFiltersList, + List s_paAppFiltersList, Dictionary s_cpAppGroupsDict, Dictionary> s_cpSchedulesDict) { @@ -1580,8 +1581,8 @@ public void ConvertPaVsysEntry(string targetFolderNew, string targetFileNameNew, List paAppFiltersList = GetPAApplicationsFilters(paVsysEntry, s_paAppFiltersList); - Dictionary cpAppGroupsDict = - ConvertApplicationsGroups(new List(paVsysEntry.ApplicationGroupsEntries), appsMatchList, s_cpAppGroupsDict, paAppFiltersList, cpServicesGroupsDict); + Dictionary cpAppGroupsDict = + ConvertApplicationsGroups(new List(paVsysEntry.ApplicationGroupsEntries), appsMatchList, s_cpAppGroupsDict, paAppFiltersList, cpServicesGroupsDict); Dictionary> cpSchedulesDict = null; if (s_cpSchedulesDict != null) @@ -1747,12 +1748,12 @@ public string InspectObjectName(string objName, string objType) } objNameNew = GetSafeName(objName); - if(!objNameNew.Equals(objName)) + if (!objNameNew.Equals(objName)) { _warningsList.Add(objName + " " + objType.Trim() + " was renamed to " + objNameNew); objName = objNameNew; } - + if (!_objectsNamesSet.Add(objName.ToLower())) { objNameNew = objName + "_" + _numPostfix++; @@ -1799,9 +1800,9 @@ public Dictionary ConvertAddresses(PA_Objects paObject else cpAddressesDict = new Dictionary(); - if(paObjects.AddressEntries != null) + if (paObjects.AddressEntries != null) { - foreach(PA_AddressEntry paAddressEntry in paObjects.AddressEntries) + foreach (PA_AddressEntry paAddressEntry in paObjects.AddressEntries) { if (!string.IsNullOrWhiteSpace(paAddressEntry.IpNetmask)) { @@ -1873,7 +1874,7 @@ public Dictionary ConvertAddresses(PA_Objects paObject } else { - cpDomain = (CheckPoint_Domain) (new List(cpAddressesDict.Values))[index]; + cpDomain = (CheckPoint_Domain)(new List(cpAddressesDict.Values))[index]; } cpAddressesDict[paAddressEntry.Name] = cpDomain; } @@ -1890,7 +1891,7 @@ public Dictionary ConvertAddressesGroups(PA_Obj Dictionary cpAddressesGroupsDict = null; if (s_cpNetGroupsDict != null) cpAddressesGroupsDict = new Dictionary(s_cpNetGroupsDict); - else + else cpAddressesGroupsDict = new Dictionary(); @@ -1913,7 +1914,7 @@ public Dictionary ConvertAddressesGroups(PA_Obj Dictionary> tagsToMembersDict = GetDictTagsToNames(paObjects, s_TagEntries, cpAddressesList, cpNetGrpList); - if(paObjects.AddressGroupEntries != null) + if (paObjects.AddressGroupEntries != null) { foreach (PA_AddressGroupEntry paAddressGroupEntry in paObjects.AddressGroupEntries) { @@ -1926,11 +1927,11 @@ public Dictionary ConvertAddressesGroups(PA_Obj { cpNetGroup.Members = paAddressGroupEntry.StaticMembers; } - else if(paAddressGroupEntry.Dynamic != null && !string.IsNullOrWhiteSpace(paAddressGroupEntry.Dynamic.Filter)) + else if (paAddressGroupEntry.Dynamic != null && !string.IsNullOrWhiteSpace(paAddressGroupEntry.Dynamic.Filter)) { string adjustedFilter = paAddressGroupEntry.Dynamic.Filter.Trim('\'').Trim('"').Trim(); - if(tagsToMembersDict.ContainsKey(adjustedFilter)) + if (tagsToMembersDict.ContainsKey(adjustedFilter)) { cpNetGroup.Members = tagsToMembersDict[adjustedFilter]; } @@ -1941,7 +1942,7 @@ public Dictionary ConvertAddressesGroups(PA_Obj } } - if(cpNetGroup != null) + if (cpNetGroup != null) { cpAddressesGroupsDict[paAddressGroupEntry.Name] = cpNetGroup; } @@ -1951,7 +1952,7 @@ public Dictionary ConvertAddressesGroups(PA_Obj return cpAddressesGroupsDict; } - public Dictionary> GetDictTagsToNames(PA_Objects paObjects, List s_TagEntries, + public Dictionary> GetDictTagsToNames(PA_Objects paObjects, List s_TagEntries, List cpAddressesList, List cpNetGrpList) { Dictionary> tagsToNamesDict = new Dictionary>(); @@ -1997,12 +1998,12 @@ public Dictionary> GetDictTagsToNames(PA_Objects paObjects, return tagsToNamesDict; } - public Dictionary ConvertAddressesGroupsWithInspection(PA_Objects paVsysEntry, + public Dictionary ConvertAddressesGroupsWithInspection(PA_Objects paVsysEntry, Dictionary cpAddressesDict, - Dictionary s_cpNetGroupsDict, + Dictionary s_cpNetGroupsDict, List s_TagEntries) { - Dictionary cpNetGroupsList = + Dictionary cpNetGroupsList = ConvertAddressesGroups(paVsysEntry, s_TagEntries, (new List(cpAddressesDict.Values)), s_cpNetGroupsDict); Dictionary cpNetGroupsResult = InspectAddressGroups(cpAddressesDict, cpNetGroupsList, null); @@ -2010,7 +2011,7 @@ public Dictionary ConvertAddressesGroupsWithIns return cpNetGroupsResult; } - public Dictionary InspectAddressGroups(Dictionary cpAddressesNamesDict, + public Dictionary InspectAddressGroups(Dictionary cpAddressesNamesDict, Dictionary cpNetGroupsCheck, Dictionary cpNetGroupsTemp) { @@ -2086,7 +2087,7 @@ public List ConvertSchedules(PA_Objects paObjects) { for (int i = 0; i < paScheduleEntry.Type.Recurring.MembersDaily.Count; i += 3) { - List timesList = + List timesList = paScheduleEntry.Type.Recurring.MembersDaily.GetRange(i, Math.Min(3, paScheduleEntry.Type.Recurring.MembersDaily.Count - i)); CheckPoint_Time cpTime = new CheckPoint_Time(); @@ -2328,7 +2329,7 @@ public CheckPoint_Time InspectCpScheduleName(CheckPoint_Time cpTime) cpTimeName = cpTimeName.Substring(0, 5) + "_t" + _timeCutterCounter++; } - if(!_timesNamesSet.Add(cpTimeName)) + if (!_timesNamesSet.Add(cpTimeName)) { cpTimeName = cpTimeName.Substring(0, 5) + "_t" + _timeCutterCounter++; } @@ -2375,7 +2376,7 @@ public Dictionary GetServicesTypes(PA_Objects paObjects, Diction return paServicesTypesDict; } - public Dictionary ConvertServices(PA_Objects paObjects, Dictionary s_cpServicesDict) + public Dictionary ConvertServices(PA_Objects paObjects, Dictionary s_cpServicesDict) { Dictionary cpServicesDict = null; if (s_cpServicesDict != null) @@ -2385,7 +2386,7 @@ public Dictionary ConvertServices(PA_Objects paObjects GetPredefinedServices().ForEach(x => cpServicesDict[x.Name] = InspectService(x)); - if(paObjects.ServiceEntries != null) + if (paObjects.ServiceEntries != null) { foreach (PA_ServiceEntry paServiceEntry in paObjects.ServiceEntries) { @@ -2394,7 +2395,7 @@ public Dictionary ConvertServices(PA_Objects paObjects if (paServiceEntry.Protocol.ServiceTcp != null && paServiceEntry.Protocol.ServiceTcp.Port != null) { string srvName = paServiceEntry.Name; - if(!char.IsLetter(paServiceEntry.Name[0])) + if (!char.IsLetter(paServiceEntry.Name[0])) { srvName = SERVICE_TYPE_TCP + "_" + paServiceEntry.Name; _warningsList.Add(paServiceEntry.Name + " service (TCP) was renamed to " + srvName); @@ -2402,7 +2403,7 @@ public Dictionary ConvertServices(PA_Objects paObjects string[] ports = paServiceEntry.Protocol.ServiceTcp.Port.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); string[] sourcePorts = new string[] { "" }; - if(paServiceEntry.Protocol.ServiceTcp.SourcePort != null) + if (paServiceEntry.Protocol.ServiceTcp.SourcePort != null) { sourcePorts = paServiceEntry.Protocol.ServiceTcp.SourcePort.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); } @@ -2578,7 +2579,7 @@ public CheckPointObject InspectService(CheckPointObject cpService) cpServiceRet = cpUdpService; } } - else if(cpService.GetType() == typeof(CheckPoint_ServiceGroup)) + else if (cpService.GetType() == typeof(CheckPoint_ServiceGroup)) { cpServiceRet = cpService; } @@ -2598,9 +2599,9 @@ public Dictionary ConvertServicesGroups(PA_Obje else cpServicesGroupsDict = new Dictionary(); - if(paObjects.ServiceGroupEntries != null) + if (paObjects.ServiceGroupEntries != null) { - foreach(PA_ServiceGroupEntry paServiceGroupEntry in paObjects.ServiceGroupEntries) + foreach (PA_ServiceGroupEntry paServiceGroupEntry in paObjects.ServiceGroupEntries) { CheckPoint_ServiceGroup cpServiceGroup = new CheckPoint_ServiceGroup(); cpServiceGroup.Name = InspectObjectName(paServiceGroupEntry.Name, CP_OBJECT_TYPE_NAME_SERVICE_GROUP); @@ -2626,11 +2627,11 @@ public Dictionary ConvertServicesGroupsWithInsp return cpServicesGroupsResult; } - public void InspectServicesGroups(Dictionary cpServicesDict, - Dictionary cpServicesGroupsCheck, + public void InspectServicesGroups(Dictionary cpServicesDict, + Dictionary cpServicesGroupsCheck, Dictionary cpServicesGroupsResult) { - while(cpServicesGroupsCheck.Count > 0) + while (cpServicesGroupsCheck.Count > 0) { string paSrvGroupName = new List(cpServicesGroupsCheck.Keys)[0]; CheckPoint_ServiceGroup cpSrvGroupCheck = cpServicesGroupsCheck[paSrvGroupName]; @@ -2641,7 +2642,7 @@ public void InspectServicesGroups(Dictionary cpService } } - public bool InspectServicesGroup(string paSrvGroupName, + public bool InspectServicesGroup(string paSrvGroupName, CheckPoint_ServiceGroup cpServicesGroup, Dictionary cpServicesDict, Dictionary cpServicesGroupsCheck, @@ -2664,14 +2665,14 @@ public bool InspectServicesGroup(string paSrvGroupName, } //group member is Services Group and converted already - if(cpServicesGroupsResult.ContainsKey(member)) + if (cpServicesGroupsResult.ContainsKey(member)) { cpServicesGroupNew.Members.Add(cpServicesGroupsResult[member].Name); continue; } //group member is Services Group and not converted yet - if(cpServicesGroupsCheck.ContainsKey(member)) + if (cpServicesGroupsCheck.ContainsKey(member)) { CheckPoint_ServiceGroup cpSrvGroupNew = cpServicesGroupsCheck[member]; cpServicesGroupsCheck.Remove(member); @@ -2751,7 +2752,7 @@ public Dictionary ConvertApplicationsGroups foreach (string matchedValue in matchedValues) { if (!matchedValue.Trim().Equals("")) - { + { cpServiceGroup.Members.Add(matchedValue.Trim()); } } @@ -2803,9 +2804,9 @@ public List GetPAApplicationsFilters(PA_Objects paObjects, List else paAppFiltersList = new List(); - if(paObjects.ApplicationFiltersEntries != null) + if (paObjects.ApplicationFiltersEntries != null) { - foreach(PA_ApplicationFilterEntry paAppFilterEntry in paObjects.ApplicationFiltersEntries) + foreach (PA_ApplicationFilterEntry paAppFilterEntry in paObjects.ApplicationFiltersEntries) { paAppFiltersList.Add(paAppFilterEntry.Name); } @@ -2822,11 +2823,11 @@ public void ConvertSecurityPolicy(PA_VsysEntry paVsysEntry, Dictionary cpZonesDict, Dictionary cpAddressesDict, Dictionary cpNetGroupsDict, - Dictionary cpServicesDict, + Dictionary cpServicesDict, Dictionary cpServicesGroupsDict, List appsMatchList, Dictionary cpAppGroupsDict, - List paAppFiltersList, + List paAppFiltersList, Dictionary> cpSchedulesDict, Dictionary cpAccessRolesDict) { @@ -2924,9 +2925,9 @@ public void ConvertSecurityPolicy(PA_VsysEntry paVsysEntry, if (isPolicyPlain && !paSecurityRuleEntry.FromList.Contains(PA_ANY_VALUE) && !(ConvertUserConf && paSecurityRuleEntry.SourceUserList != null && !paSecurityRuleEntry.SourceUserList.Contains(PA_ANY_VALUE))) { - paSecurityRuleEntry.FromList.ForEach(fromObj => + paSecurityRuleEntry.FromList.ForEach(fromObj => { - if(cpZonesDict.ContainsKey(fromObj)) + if (cpZonesDict.ContainsKey(fromObj)) { CheckPoint_Zone cpZone = cpZonesDict[fromObj]; cpRuleSourceList.Add(cpZone); @@ -3153,7 +3154,7 @@ public void ConvertSecurityPolicy(PA_VsysEntry paVsysEntry, } } - if(paSecurityRuleEntry.SourceList != null && !paSecurityRuleEntry.SourceList.Contains(PA_ANY_VALUE)) + if (paSecurityRuleEntry.SourceList != null && !paSecurityRuleEntry.SourceList.Contains(PA_ANY_VALUE)) { cpRuleSourceList.ForEach(x => cpAccessRole.Networks.Add(x.Name)); cpRuleSourceList.Clear(); @@ -3200,8 +3201,8 @@ public void ConvertSecurityPolicy(PA_VsysEntry paVsysEntry, cpRuleNegateDestination, cpAddressesDict, cpNetGroupsDict, - cpServicesDict, - cpServicesGroupsDict, + cpServicesDict, + cpServicesGroupsDict, cpAccessRolesList, cpAppGroupsDict); cpRule.Layer = cpPackage.ParentLayer.Name; @@ -3307,7 +3308,7 @@ public void ConvertSecurityPolicy(PA_VsysEntry paVsysEntry, } } - cpPackage.ParentLayer.Rules.ForEach(x => + cpPackage.ParentLayer.Rules.ForEach(x => { if (cpGroupRuleAppFiltering.ContainsKey(x.Name) && cpGroupRuleAppFiltering[x.Name]) x.ConversionComments = "Applications and URL filtering is enabled for layer."; @@ -3339,7 +3340,7 @@ public void ConvertSecurityPolicy(PA_VsysEntry paVsysEntry, AddCheckPointObject(cpPackage); } - private CheckPoint_RuleWithApplication CreateCpRule(PA_SecurityRuleEntry paSecurityRuleEntry, + private CheckPoint_RuleWithApplication CreateCpRule(PA_SecurityRuleEntry paSecurityRuleEntry, List cpRuleSourceList, List cpRuleDestinationList, List cpRuleServiceList, @@ -3352,8 +3353,8 @@ private CheckPoint_RuleWithApplication CreateCpRule(PA_SecurityRuleEntry paSecur bool cpRuleNegateDestination, Dictionary cpAddressesDict, Dictionary cpNetGroupsDict, - Dictionary cpServicesDict, - Dictionary cpSrvGroupsDict, + Dictionary cpServicesDict, + Dictionary cpSrvGroupsDict, List cpAccessRolesList, Dictionary cpAppGroupsDict) { @@ -3397,7 +3398,7 @@ private CheckPoint_RuleWithApplication CreateCpRule(PA_SecurityRuleEntry paSecur }); cpRule.Service.ForEach(x => { - if(x.GetType() == typeof(CheckPoint_ServiceGroup)) + if (x.GetType() == typeof(CheckPoint_ServiceGroup)) { AddCpServiceGroup((CheckPoint_ServiceGroup)x, cpServicesDict, cpSrvGroupsDict); } @@ -3416,7 +3417,7 @@ private CheckPoint_RuleWithApplication CreateCpRule(PA_SecurityRuleEntry paSecur } cpRule.Application.ForEach(x => { - if(x.GetType() == typeof(CheckPoint_ApplicationGroup)) + if (x.GetType() == typeof(CheckPoint_ApplicationGroup)) { AddCpApplicationGroup((CheckPoint_ApplicationGroup)x, cpAppGroupsDict); } @@ -3445,7 +3446,7 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, if (paVsysEntry.Rulebase != null && paVsysEntry.Rulebase.Nat != null && paVsysEntry.Rulebase.Nat.RulesList != null) { - foreach(PA_NatRuleEntry paNatRuleEntry in paVsysEntry.Rulebase.Nat.RulesList) + foreach (PA_NatRuleEntry paNatRuleEntry in paVsysEntry.Rulebase.Nat.RulesList) { List cpSourceTranslationList = new List(); bool isSourceTranslationExists = true; @@ -3462,15 +3463,15 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, #region converting source translation to list; checking if NAT Rule Method should be Static if (paNatRuleEntry.SourceTranslation != null) { - if(paNatRuleEntry.SourceTranslation.StaticIp != null) + if (paNatRuleEntry.SourceTranslation.StaticIp != null) { - if(!string.IsNullOrWhiteSpace(paNatRuleEntry.SourceTranslation.StaticIp.TranslatedAddress)) + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.SourceTranslation.StaticIp.TranslatedAddress)) { - if(cpAddressesDict.ContainsKey(paNatRuleEntry.SourceTranslation.StaticIp.TranslatedAddress)) + if (cpAddressesDict.ContainsKey(paNatRuleEntry.SourceTranslation.StaticIp.TranslatedAddress)) { cpSourceTranslationList.Add(cpAddressesDict[paNatRuleEntry.SourceTranslation.StaticIp.TranslatedAddress]); isNatRuleStatic = true; - if(!string.IsNullOrWhiteSpace(paNatRuleEntry.SourceTranslation.StaticIp.IsBiDirectional) + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.SourceTranslation.StaticIp.IsBiDirectional) && paNatRuleEntry.SourceTranslation.StaticIp.IsBiDirectional.ToLower().Equals("yes")) { isNatRuleBiDirectional = true; @@ -3478,26 +3479,26 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, } } } - else if(paNatRuleEntry.SourceTranslation.DynamicIp != null) + else if (paNatRuleEntry.SourceTranslation.DynamicIp != null) { - if(paNatRuleEntry.SourceTranslation.DynamicIp.TranslatedAddresses != null) + if (paNatRuleEntry.SourceTranslation.DynamicIp.TranslatedAddresses != null) { - foreach(string translatedAddress in paNatRuleEntry.SourceTranslation.DynamicIp.TranslatedAddresses) + foreach (string translatedAddress in paNatRuleEntry.SourceTranslation.DynamicIp.TranslatedAddresses) { if (cpAddressesDict.ContainsKey(translatedAddress)) { cpSourceTranslationList.Add(cpAddressesDict[translatedAddress]); } - else if(cpNetGroupsDict.ContainsKey(translatedAddress)) + else if (cpNetGroupsDict.ContainsKey(translatedAddress)) { cpSourceTranslationList.Add(cpNetGroupsDict[translatedAddress]); } } } } - else if(paNatRuleEntry.SourceTranslation.DynamicIpAndPort != null) + else if (paNatRuleEntry.SourceTranslation.DynamicIpAndPort != null) { - if(paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses != null && + if (paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses != null && paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses.Count > 0) { foreach (string translatedAddress in paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses) @@ -3525,7 +3526,7 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, cpHostNew.Name = "Host_" + ipAddress; cpHostNew.IpAddress = ipAddress; - cpAddressesDict[translatedAddress] = cpHostNew; + cpAddressesDict[translatedAddress] = cpHostNew; cpSourceTranslationList.Add(cpHostNew); _warningsList.Add(cpHostNew.Name + " host object is created for NAT rule."); } @@ -3540,7 +3541,7 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, cpNetworkNew.Name = "Net_" + ipAddress; cpNetworkNew.Subnet = ipAddress; cpNetworkNew.Netmask = ipNetwork.Netmask.ToString(); - cpAddressesDict[translatedAddress] = cpNetworkNew; + cpAddressesDict[translatedAddress] = cpNetworkNew; cpSourceTranslationList.Add(cpNetworkNew); _warningsList.Add(cpNetworkNew.Name + " network object is created for NAT rule."); } @@ -3548,12 +3549,12 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, } } } - else if(paNatRuleEntry.SourceTranslation.DynamicIpAndPort.InterfaceAddress != null) + else if (paNatRuleEntry.SourceTranslation.DynamicIpAndPort.InterfaceAddress != null) { string intfAddrIP = paNatRuleEntry.SourceTranslation.DynamicIpAndPort.InterfaceAddress.Ip; - if(!string.IsNullOrWhiteSpace(intfAddrIP)) + if (!string.IsNullOrWhiteSpace(intfAddrIP)) { - if(cpAddressesDict.ContainsKey(intfAddrIP)) + if (cpAddressesDict.ContainsKey(intfAddrIP)) { cpSourceTranslationList.Add(cpAddressesDict[intfAddrIP]); } @@ -3580,7 +3581,7 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, } } - if(cpSourceTranslationList.Count == 0) + if (cpSourceTranslationList.Count == 0) { isSourceTranslationExists = false; // createing Dummy Object because we need to have at least 1 element in cpSourceTranslationList for creating NAT rule @@ -3588,7 +3589,7 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, } #endregion - if(paNatRuleEntry.DestinationTranslation == null) + if (paNatRuleEntry.DestinationTranslation == null) { isDestinationTranslationNone = true; } @@ -3753,7 +3754,7 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, if (isSourceTranslationExists) { cpNatRule.TranslatedSource = cpSourceTranslation; - if(isNatRuleStatic) + if (isNatRuleStatic) { cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Static; } @@ -3926,22 +3927,22 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, cpNatRule.TranslatedDestination = cpNetGroupsDict[paNatRuleEntry.DynamicDestinationTranslation.TranslatedAddress]; } - if(!string.IsNullOrWhiteSpace(paNatRuleEntry.DynamicDestinationTranslation.TranslatedPort)) + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.DynamicDestinationTranslation.TranslatedPort)) { - if(!string.IsNullOrWhiteSpace(paNatRuleEntry.Service)) + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.Service)) { if (cpServicesDict.ContainsKey(paNatRuleEntry.Service)) { CheckPointObject cpService = cpServicesDict[paNatRuleEntry.Service]; - if(cpService.GetType() == typeof(CheckPoint_TcpService)) + if (cpService.GetType() == typeof(CheckPoint_TcpService)) { cpNatRule.TranslatedService = CreateNatServiceTcpFromDynDest(paNatRuleEntry); } - else if(cpService.GetType() == typeof(CheckPoint_UdpService)) + else if (cpService.GetType() == typeof(CheckPoint_UdpService)) { cpNatRule.TranslatedService = CreateNatServiceUdpFromDynDest(paNatRuleEntry); } - else if(cpService.GetType() == typeof(CheckPoint_PredifinedObject) && paServicesTypesDict.ContainsKey(paNatRuleEntry.Service)) + else if (cpService.GetType() == typeof(CheckPoint_PredifinedObject) && paServicesTypesDict.ContainsKey(paNatRuleEntry.Service)) { string servicesType = paServicesTypesDict[paNatRuleEntry.Service]; if (servicesType.Trim().ToUpper().Equals("TCP")) @@ -4022,12 +4023,12 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, if (messagesE.Count == 0) { - if(!(cpNatRule.Source is CheckPoint_Domain) && + if (!(cpNatRule.Source is CheckPoint_Domain) && !(cpNatRule.Destination is CheckPoint_Domain) && !(cpNatRule.TranslatedSource is CheckPoint_Domain) && !(cpNatRule.TranslatedDestination is CheckPoint_Domain)) { - if(isNatRuleBiDirectional && isDestinationTranslationNone) + if (isNatRuleBiDirectional && isDestinationTranslationNone) { //TRANS DEST == NONE // orig source <- orig destin @@ -4149,9 +4150,9 @@ public CheckPointObject CreateNatServiceUdpFromDynDest(PA_NatRuleEntry paNatRule } public void GetServicesTypesFromServicesGroup( - CheckPoint_ServiceGroup cpSrvGroup, - List cpServicesGroups, - List cpServices, + CheckPoint_ServiceGroup cpSrvGroup, + List cpServicesGroups, + List cpServices, out bool isTcpSrv, out bool isUdpSrv) { isTcpSrv = false; @@ -4160,7 +4161,7 @@ public void GetServicesTypesFromServicesGroup( foreach (string cpSrvMember in cpSrvGroup.Members) { CheckPointObject cpSrv = cpServices.Find(x => x.Name.Equals(cpSrvMember)); - if(cpSrv != null) + if (cpSrv != null) { if (cpSrv.GetType() == typeof(CheckPoint_TcpService)) isTcpSrv = true; @@ -4171,7 +4172,7 @@ public void GetServicesTypesFromServicesGroup( } CheckPoint_ServiceGroup cpSrvGrp = cpServicesGroups.Find(x => x.Name.Equals(cpSrvMember)); - if(cpSrvGrp != null) + if (cpSrvGrp != null) { GetServicesTypesFromServicesGroup(cpSrvGrp, cpServicesGroups, cpServices, out isTcpSrv, out isUdpSrv); } @@ -4179,9 +4180,9 @@ public void GetServicesTypesFromServicesGroup( } public void GetServicesGroupsFromServiceGroup( - CheckPoint_ServiceGroup cpSrvGroup, - List cpServicesGroups, - List cpServices, + CheckPoint_ServiceGroup cpSrvGroup, + List cpServicesGroups, + List cpServices, List cpSrvGrpMembersTcp, List cpSrvGrpMembersUdp) { @@ -4201,11 +4202,11 @@ public void GetServicesGroupsFromServiceGroup( else if (cpSrv.GetType() == typeof(CheckPoint_PredifinedObject) && cpPredefServicesTypes.ContainsKey(cpSrv.Name)) { string srvType = cpPredefServicesTypes[cpSrv.Name].ToLower(); - if(srvType.Equals(SERVICE_TYPE_TCP.ToLower())) + if (srvType.Equals(SERVICE_TYPE_TCP.ToLower())) { cpSrvGrpMembersTcp.Add(cpSrv); } - else if(srvType.Equals(SERVICE_TYPE_UDP.ToLower())) + else if (srvType.Equals(SERVICE_TYPE_UDP.ToLower())) { cpSrvGrpMembersUdp.Add(cpSrv); } @@ -4225,12 +4226,12 @@ public void GetServicesGroupsFromServiceGroup( #region Utility methods - public void AddCpApplicationGroup(CheckPoint_ApplicationGroup cpAppGrp, + public void AddCpApplicationGroup(CheckPoint_ApplicationGroup cpAppGrp, Dictionary cpAppGroupsDict) { - foreach(string member in cpAppGrp.Members) + foreach (string member in cpAppGrp.Members) { - if(cpAppGroupsDict.ContainsKey(member)) + if (cpAppGroupsDict.ContainsKey(member)) { AddCpApplicationGroup(cpAppGroupsDict[member], cpAppGroupsDict); } @@ -4238,17 +4239,17 @@ public void AddCpApplicationGroup(CheckPoint_ApplicationGroup cpAppGrp, AddCheckPointObject(cpAppGrp); } - public void AddCpNetworkGroup(CheckPoint_NetworkGroup cpNetGroup, - Dictionary cpAddressesDict, + public void AddCpNetworkGroup(CheckPoint_NetworkGroup cpNetGroup, + Dictionary cpAddressesDict, Dictionary cpNetGroupsDict) { - foreach(string member in cpNetGroup.Members) + foreach (string member in cpNetGroup.Members) { - if(cpAddressesDict.ContainsKey(member)) + if (cpAddressesDict.ContainsKey(member)) { AddCheckPointObject(cpAddressesDict[member]); } - else if(cpNetGroupsDict.ContainsKey(member)) + else if (cpNetGroupsDict.ContainsKey(member)) { AddCpNetworkGroup(cpNetGroupsDict[member], cpAddressesDict, cpNetGroupsDict); AddCheckPointObject(cpNetGroupsDict[member]); @@ -4282,7 +4283,7 @@ public void AddCpServiceGroup(CheckPoint_ServiceGroup cpSrvGroup, } } if (!infiniteRecursion) - AddCpServiceGroup(cpSrvGroupsDict[member], cpServicesDict, cpSrvGroupsDict); + AddCpServiceGroup(cpSrvGroupsDict[member], cpServicesDict, cpSrvGroupsDict); AddCheckPointObject(cpSrvGroupsDict[member]); } } diff --git a/PaloAltoMigration/PanoramaConverter.cs b/PaloAltoMigration/PanoramaConverter.cs index d94c12d..2990776 100644 --- a/PaloAltoMigration/PanoramaConverter.cs +++ b/PaloAltoMigration/PanoramaConverter.cs @@ -1062,7 +1062,7 @@ public Dictionary> getZones(Panorama_Config paConfig) List templatesList = new List(); foreach (string template in paTemplateStackEntry.StackTemplatesMembers) { - templatesList.Add(template); + templatesList.Add(template); } foreach (PA_DevicesTemplateStackEntry device in paTemplateStackEntry.DevicesEntries) { @@ -1470,7 +1470,7 @@ Dictionary _devicesUIDDict } public override Dictionary Convert(bool convertNat) - { + { string targetFileNameMain = _vendorFileName; string targetFolderMain = _targetFolder; @@ -1489,7 +1489,7 @@ public override Dictionary Convert(bool convertNat) Dictionary _devicesUIDDict = GetDevicesUIDdict(_paParser._ArchiveName); if (paConfig != null) - { + { List s_TagEntries = new List(); Dictionary s_cpAddressesDict = null; Dictionary s_cpNetGroupsDict = null; @@ -1500,7 +1500,7 @@ public override Dictionary Convert(bool convertNat) Dictionary s_cpAppGroupsDict = null; Dictionary> s_cpSchedulesDict = null; PA_PreRulebase s_preRulebase = null; - PA_PostRulebase s_postRulebase = null; + PA_PostRulebase s_postRulebase = null; if (paConfig.Shared != null) { @@ -1536,7 +1536,7 @@ public override Dictionary Convert(bool convertNat) }); s_preRulebase = paConfig.Shared.PreRulebase; - s_postRulebase = paConfig.Shared.PostRulebase; + s_postRulebase = paConfig.Shared.PostRulebase; } if (paConfig.Devices != null) { @@ -1601,7 +1601,7 @@ public override Dictionary Convert(bool convertNat) foreach (CheckPoint_NetworkGroup FWGroup in FWGroup_List) { if (s_cpNetGroupsDict != null) - { + { if (!s_cpNetGroupsDict.ContainsKey(FWGroup.Name)) s_cpNetGroupsDict.Add(FWGroup.Name, FWGroup); } @@ -1703,11 +1703,11 @@ public List getPanoramaDeviceGroup(PA_DeviceGroupEntry string deviceName = null; if (_devicesUIDDict.ContainsKey(deviceEntry.Name)) { - deviceName = _devicesUIDDict[deviceEntry.Name]; + deviceName = _devicesUIDDict[deviceEntry.Name]; } FWGroup = new CheckPoint_NetworkGroup(); - FWGroup.Name = "FW_" + deviceName; + FWGroup.Name = "FW_" + deviceName; FWGroup.IsPanoramaDeviceGroup = true; foreach (PA_TagEntry tagEntry in tags) { @@ -1773,7 +1773,7 @@ Dictionary _devicesUIDDict Dictionary cpAddressesDict = ConvertAddresses(paDeviceGroupEntry, s_cpAddressesDict); - Dictionary cpNetGroupsDict = ConvertAddressesGroupsWithInspection(paDeviceGroupEntry, cpAddressesDict, s_cpNetGroupsDict, s_TagEntries); + Dictionary cpNetGroupsDict = ConvertAddressesGroupsWithInspection(paDeviceGroupEntry, cpAddressesDict, s_cpNetGroupsDict, s_TagEntries); Dictionary cpServicesDict = ConvertServices(paDeviceGroupEntry, s_cpServicesDict); @@ -1845,7 +1845,7 @@ Dictionary _devicesUIDDict AddCheckPointObject(x); } }); - + (new List(cpServicesGroupsDict.Values)).ForEach(x => AddCheckPointObject(x)); (new List(cpAppGroupsDict.Values)).ForEach(x => AddCheckPointObject(x)); (new List>(cpSchedulesDict.Values)).ForEach(x => x.ForEach(y => AddCheckPointObject(y))); @@ -1879,7 +1879,7 @@ Dictionary _devicesUIDDict _warningsConvertedPackage += _warningsList.Count; _errorsConvertedPackage += _errorsList.Count; - if(CreateManagnetReport) ExportManagmentReport(); + if (CreateManagnetReport) ExportManagmentReport(); if (!_isOverMaxLengthPackageName) { @@ -2009,7 +2009,7 @@ public Dictionary ConvertZones(List zoneE #region Convert Addresses and Addresses Groups public Dictionary ConvertAddresses(PA_Objects paObjects, Dictionary s_cpAddressesDict) - { + { Dictionary cpAddressesDict = null; if (s_cpAddressesDict != null) cpAddressesDict = new Dictionary(s_cpAddressesDict); @@ -2082,16 +2082,16 @@ public Dictionary ConvertAddresses(PA_Objects paObject CheckPoint_Domain cpDomain = null; if (index == -1) { - cpDomain = new CheckPoint_Domain(); - cpDomain.Name = "." + paAddressEntry.Fqdn; + cpDomain = new CheckPoint_Domain(); + cpDomain.Name = "." + paAddressEntry.Fqdn; cpDomain.Comments = paAddressEntry.Description; - cpDomain.Tags = paAddressEntry.TagMembers; + cpDomain.Tags = paAddressEntry.TagMembers; } else { cpDomain = (CheckPoint_Domain)(new List(cpAddressesDict.Values))[index]; } - cpAddressesDict[paAddressEntry.Name] = cpDomain; + cpAddressesDict[paAddressEntry.Name] = cpDomain; } } } @@ -2123,7 +2123,7 @@ Dictionary s_cpNetGroupsDict cpNetGroup.Name = paAddressGroupEntry.Name; cpNetGroup.Comments = paAddressGroupEntry.Description; cpNetGroup.Tags = paAddressGroupEntry.TagMembers; - cpNetGrpList.Add(cpNetGroup); + cpNetGrpList.Add(cpNetGroup); } } @@ -2134,9 +2134,9 @@ Dictionary s_cpNetGroupsDict foreach (PA_AddressGroupEntry paAddressGroupEntry in paObjects.AddressGroupEntries) { CheckPoint_NetworkGroup cpNetGroup = new CheckPoint_NetworkGroup(); - + cpNetGroup.Name = InspectObjectName(GetSafeName(paAddressGroupEntry.Name), CP_OBJECT_TYPE_NAME_ADDRESS_GROUP); - + cpNetGroup.Comments = paAddressGroupEntry.Description; cpNetGroup.Tags = paAddressGroupEntry.TagMembers; @@ -2203,9 +2203,9 @@ public Dictionary> GetDictTagsToNames(PA_Objects paObjects, if (cpNetGrpList != null) { foreach (CheckPoint_NetworkGroup cpAddressGroupEntry in cpNetGrpList) - { + { if (cpAddressGroupEntry.Tags.Contains(paTagEntry.Name)) - { + { namesList.Add(cpAddressGroupEntry.Name); } } @@ -2242,7 +2242,7 @@ List s_TagEntries public Dictionary InspectAddressGroups(Dictionary cpAddressesNamesDict, Dictionary cpNetGroupsCheck, Dictionary cpNetGroupsTemp) - { + { Dictionary cpNetGroupsResult = null; if (cpNetGroupsTemp != null) { @@ -2263,13 +2263,13 @@ public Dictionary InspectAddressGroups(Dictiona cpNetGroupResult.Name = cpNetGroupCheck.Name; cpNetGroupResult.Comments = cpNetGroupCheck.Comments; cpNetGroupResult.Tags = cpNetGroupCheck.Tags; - cpNetGroupResult.IsPanoramaDeviceGroup = cpNetGroupCheck.IsPanoramaDeviceGroup; + cpNetGroupResult.IsPanoramaDeviceGroup = cpNetGroupCheck.IsPanoramaDeviceGroup; foreach (string member in cpNetGroupCheck.Members) - { + { if (cpAddressesNamesDict.ContainsKey(member)) //group member is in Addresses - { + { cpNetGroupResult.Members.Add(cpAddressesNamesDict[member].Name); } else if (cpNetGroupsResult.ContainsKey(member)) //group member is converted and added to Addresses Groups @@ -2286,12 +2286,12 @@ public Dictionary InspectAddressGroups(Dictiona } else { - _warningsList.Add(cpNetGroupCheck.Name + " address group contains non-existing member: " + member); + _warningsList.Add(cpNetGroupCheck.Name + " address group contains non-existing member: " + member); } } else { - _warningsList.Add(cpNetGroupCheck.Name + " address group contains non-existing member: " + member); + _warningsList.Add(cpNetGroupCheck.Name + " address group contains non-existing member: " + member); } } @@ -2609,21 +2609,21 @@ public Dictionary GetServicesTypes(PA_Objects paObjects, Diction } public Dictionary ConvertServices(PA_Objects paObjects, Dictionary s_cpServicesDict) - { + { Dictionary cpServicesDict = null; if (s_cpServicesDict != null) cpServicesDict = new Dictionary(s_cpServicesDict); else cpServicesDict = new Dictionary(); - + Dictionary cpInspectedServicesDict = new Dictionary(); foreach (string service in cpServicesDict.Keys) { - cpInspectedServicesDict[service] = InspectService(cpServicesDict[service]); + cpInspectedServicesDict[service] = InspectService(cpServicesDict[service]); } cpServicesDict = cpInspectedServicesDict; - + GetPredefinedServices().ForEach(x => cpServicesDict[x.Name] = InspectService(x)); if (paObjects.ServiceEntries != null) @@ -2635,7 +2635,7 @@ public Dictionary ConvertServices(PA_Objects paObjects if (paServiceEntry.Protocol.ServiceTcp != null && paServiceEntry.Protocol.ServiceTcp.Port != null) { string srvName = paServiceEntry.Name; - + if (!char.IsLetter(paServiceEntry.Name[0])) { srvName = SERVICE_TYPE_TCP + "_" + paServiceEntry.Name; @@ -2682,7 +2682,7 @@ public Dictionary ConvertServices(PA_Objects paObjects else { CheckPoint_TcpService cpTcpService = new CheckPoint_TcpService(); - + cpTcpService.Name = InspectObjectName(srvName, CP_OBJECT_TYPE_NAME_SERVICE_TCP); cpTcpService.Comments = paServiceEntry.Description; @@ -2760,7 +2760,7 @@ public Dictionary ConvertServices(PA_Objects paObjects } public List GetPredefinedServices() - { + { List predefinedServices = new List(); CheckPoint_ServiceGroup cpServiceGroupHttp = new CheckPoint_ServiceGroup(); @@ -2775,7 +2775,7 @@ public List GetPredefinedServices() cpServiceHttps.Port = "443"; predefinedServices.Add(cpServiceHttps); - + return predefinedServices; } @@ -3102,7 +3102,7 @@ Dictionary _devicesUIDDict if (paDeviceGroupEntry.PreRulebase != null && paDeviceGroupEntry.PreRulebase.Security != null && paDeviceGroupEntry.PreRulebase.Security.RulesList != null) { foreach (PA_SecurityRuleEntry paSecurityRuleEntry in paDeviceGroupEntry.PreRulebase.Security.RulesList) - { + { isPolicyPlain = !isPolicyPlain && (paSecurityRuleEntry.FromList.Contains(PA_ANY_VALUE) || paSecurityRuleEntry.ToList.Contains(PA_ANY_VALUE)) ? true : isPolicyPlain; paRules.Add(paSecurityRuleEntry); @@ -3110,9 +3110,9 @@ Dictionary _devicesUIDDict } if (paDeviceGroupEntry.PostRulebase != null && paDeviceGroupEntry.PostRulebase.Security != null && paDeviceGroupEntry.PostRulebase.Security.RulesList != null) - { + { foreach (PA_SecurityRuleEntry paSecurityRuleEntry in paDeviceGroupEntry.PostRulebase.Security.RulesList) - { + { isPolicyPlain = !isPolicyPlain && (paSecurityRuleEntry.FromList.Contains(PA_ANY_VALUE) || paSecurityRuleEntry.ToList.Contains(PA_ANY_VALUE)) ? true : isPolicyPlain; paRules.Add(paSecurityRuleEntry); @@ -3121,9 +3121,9 @@ Dictionary _devicesUIDDict //add post-rules from shared section to the device group rules if (s_postRulebase != null && s_postRulebase.Security != null && s_postRulebase.Security.RulesList != null) - { + { foreach (PA_SecurityRuleEntry paSecurityRuleEntry in s_postRulebase.Security.RulesList) - { + { isPolicyPlain = !isPolicyPlain && (paSecurityRuleEntry.FromList.Contains(PA_ANY_VALUE) || paSecurityRuleEntry.ToList.Contains(PA_ANY_VALUE)) ? true : isPolicyPlain; paRules.Add(paSecurityRuleEntry); @@ -3309,11 +3309,11 @@ Dictionary _devicesUIDDict if (!(paSecurityRuleEntry.ServiceList.Contains(PA_APPLICATION_DEFAULT) || paSecurityRuleEntry.ServiceList.Contains(PA_ANY_VALUE))) { foreach (string paServiceName in paSecurityRuleEntry.ServiceList) - { + { CheckPointObject cpServiceObj = null; if (cpServicesDict.ContainsKey(paServiceName)) { - + cpServiceObj = cpServicesDict[paServiceName]; } else if (cpServicesGroupsDict.ContainsKey(paServiceName)) @@ -3499,17 +3499,17 @@ Dictionary _devicesUIDDict cpAppGroupsDict, //devicesGroupList, cpTargetDeviceUIDList - ); + ); if (cpRule.IsCleanupRule()) - { + { continue; } if (cpRule.IsAllowAnyRule()) { cpRule.Enabled = false; - } - + } + cpRule.Layer = cpPackage.ParentLayer.Name; cpPackage.ParentLayer.Rules.Add(cpRule); @@ -3519,7 +3519,7 @@ Dictionary _devicesUIDDict { cpPackage.ParentLayer.ApplicationsAndUrlFiltering = true; } - + string ruleCmd = cpRule.ToCLIScript(); } else @@ -3674,7 +3674,7 @@ public List AddSecurityRuleTarget(List devicesG { devices.Add(group.Name); } - + bool cpRuleNegateTarget = false; if (paSecurityRuleEntry.Target != null) { @@ -3688,10 +3688,10 @@ public List AddSecurityRuleTarget(List devicesG { if (_devicesUIDDict.ContainsKey(entry.Name)) { - deviceName = _devicesUIDDict[entry.Name]; + deviceName = _devicesUIDDict[entry.Name]; } - cpTargetDeviceUIDList.Add("FW_" + deviceName); + cpTargetDeviceUIDList.Add("FW_" + deviceName); } else { //negate option set to "yes" @@ -3701,15 +3701,15 @@ public List AddSecurityRuleTarget(List devicesG { if (_devicesUIDDict.ContainsKey(device)) { - deviceName = _devicesUIDDict[device]; + deviceName = _devicesUIDDict[device]; } - cpTargetDeviceUIDList.Add(deviceName); + cpTargetDeviceUIDList.Add(deviceName); } } } } - } + } return cpTargetDeviceUIDList; } @@ -3724,7 +3724,7 @@ public List AddNatRuleTarget(List devicesGroupL { devices.Add(group.Name); } - + bool cpRuleNegateTarget = false; if (paNatRuleEntry.Target != null) { @@ -3738,9 +3738,9 @@ public List AddNatRuleTarget(List devicesGroupL { if (_devicesUIDDict.ContainsKey(entry.Name)) { - deviceName = _devicesUIDDict[entry.Name]; + deviceName = _devicesUIDDict[entry.Name]; } - cpTargetDeviceUIDList.Add("FW_" + deviceName); + cpTargetDeviceUIDList.Add("FW_" + deviceName); } else { //negate option set to "yes" @@ -3750,7 +3750,7 @@ public List AddNatRuleTarget(List devicesGroupL { if (_devicesUIDDict.ContainsKey(device)) { - deviceName = _devicesUIDDict[device]; + deviceName = _devicesUIDDict[device]; } cpTargetDeviceUIDList.Add(deviceName); @@ -3759,7 +3759,7 @@ public List AddNatRuleTarget(List devicesGroupL } } - } + } return cpTargetDeviceUIDList; } @@ -3779,7 +3779,7 @@ private CheckPoint_RuleWithApplication CreateCpRule(PA_SecurityRuleEntry paSecur Dictionary cpServicesDict, Dictionary cpSrvGroupsDict, List cpAccessRolesList, - Dictionary cpAppGroupsDict, + Dictionary cpAppGroupsDict, List cpTargetDeviceUIDList ) { @@ -3789,7 +3789,7 @@ List cpTargetDeviceUIDList cpRule.Tags = paSecurityRuleEntry.TagMembers; cpRule.Source.AddRange(cpRuleSourceList); cpRule.Destination.AddRange(cpRuleDestinationList); - cpRule.Service.AddRange(cpRuleServiceList); + cpRule.Service.AddRange(cpRuleServiceList); cpRule.Application.AddRange(cpRuleApplilcationList); cpRule.Action = cpRuleActionType; cpRule.Time.AddRange(cpRuleTimeList); @@ -3798,11 +3798,11 @@ List cpTargetDeviceUIDList if (cpTargetDeviceUIDList != null && cpTargetDeviceUIDList.Count() > 0) { cpRule.Target.AddRange(cpTargetDeviceUIDList); - } + } cpRule.SourceNegated = cpRuleNegateSource; cpRule.DestinationNegated = cpRuleNegateDestination; cpRule.ConversionComments = "Matched rule: " + paSecurityRuleEntry.Name; - + cpRule.Source.ForEach(x => { @@ -3925,9 +3925,9 @@ public void ConvertNatPolicy(PA_DeviceGroupEntry paDeviceGroupEntry, { if (paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses != null && paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses.Count > 0) - { + { foreach (string translatedAddress in paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses) - { + { if (cpAddressesDict.ContainsKey(translatedAddress)) { cpSourceTranslationList.Add(cpAddressesDict[translatedAddress]); @@ -3950,7 +3950,7 @@ public void ConvertNatPolicy(PA_DeviceGroupEntry paDeviceGroupEntry, CheckPoint_Host cpHostNew = new CheckPoint_Host(); cpHostNew.Name = "Host_" + ipAddress; cpHostNew.IpAddress = ipAddress; - cpAddressesDict[translatedAddress] = cpHostNew; + cpAddressesDict[translatedAddress] = cpHostNew; cpSourceTranslationList.Add(cpHostNew); _warningsList.Add(cpHostNew.Name + " host object is created for NAT rule."); } @@ -3964,13 +3964,13 @@ public void ConvertNatPolicy(PA_DeviceGroupEntry paDeviceGroupEntry, cpNetworkNew.Name = "Net_" + ipAddress; cpNetworkNew.Subnet = ipAddress; cpNetworkNew.Netmask = ipNetwork.Netmask.ToString(); - cpAddressesDict[translatedAddress] = cpNetworkNew; + cpAddressesDict[translatedAddress] = cpNetworkNew; cpSourceTranslationList.Add(cpNetworkNew); _warningsList.Add(cpNetworkNew.Name + " network object is created for NAT rule."); } } } - + } } else if (paNatRuleEntry.SourceTranslation.DynamicIpAndPort.InterfaceAddress != null) @@ -4724,31 +4724,31 @@ protected override string GetVendorName() return Vendor.PaloAlto.ToString(); } #endregion - + public Dictionary GetDevicesUIDdict(string filename) { Dictionary devicesUIDDict = new Dictionary(); - + string outConfigsFolder = filename; string[] configsFolder = Directory.GetDirectories(outConfigsFolder);//get uncompressed folder name string[] configFilesArray = Directory.GetFiles(configsFolder[0]); - + string configName; string deviceName; string deviceUID; - + foreach (string confFile in configFilesArray) { - + if (confFile.IndexOf("\\") != -1 && confFile.IndexOf(".xml") != -1) { configName = confFile.Substring(confFile.LastIndexOf("\\") + 1); configName = configName.Substring(0, configName.IndexOf(".xml")); - + if (configName.IndexOf("_") != -1) { - deviceName = configName.Substring(0, configName.LastIndexOf("_")); - deviceUID = configName.Substring(configName.LastIndexOf("_") + 1); + deviceName = configName.Substring(0, configName.LastIndexOf("_")); + deviceUID = configName.Substring(configName.LastIndexOf("_") + 1); devicesUIDDict.Add(deviceUID, deviceName); } } diff --git a/PaloAltoMigration/PanoramaParser.cs b/PaloAltoMigration/PanoramaParser.cs index 2e3d681..a4fdba9 100644 --- a/PaloAltoMigration/PanoramaParser.cs +++ b/PaloAltoMigration/PanoramaParser.cs @@ -21,24 +21,24 @@ public string _ArchiveName public Panorama_Config Config { get; set; } public override void Export(string filename) - { + { } public override void Parse(string filename) { } - + public void ParseWithTargetFolder(string filename, string targetFolder) { if (!targetFolder.EndsWith("\\")) targetFolder += "\\"; - UncompressArchive(filename,targetFolder); - + UncompressArchive(filename, targetFolder); + string outConfigsFolder = targetFolder + "configs"; _ArchiveName = outConfigsFolder; string panoramaConfig = GetPanoramaConfFile(outConfigsFolder); - + XmlSerializer serializer = new XmlSerializer(typeof(Panorama_Config)); using (FileStream fileStream = new FileStream(panoramaConfig, FileMode.Open)) @@ -55,8 +55,8 @@ protected override void ParseVersion(object versionProvider) } public string GetPanoramaConfFile(string outConfigsFolder) - { - string panoramaConfig = null; + { + string panoramaConfig = null; string[] configsFolder = Directory.GetDirectories(outConfigsFolder);//get uncompressed folder name string[] configFilesArray = Directory.GetFiles(configsFolder[0]);//get list of panorama and firewalls config files @@ -90,19 +90,19 @@ public bool DetectPanoramaConfFile(string fileName) ///
public bool CheckPaloAltoConfiguartion(String filename) { - bool is_panorama = false; + bool is_panorama = false; List archiveExt = new List { ".tgz" }; string extension = Path.GetExtension(filename); - + if (archiveExt.Contains(extension)) { is_panorama = true; } else { - Console.WriteLine("Configs archive must be in .tgz format!"); - } + Console.WriteLine("Configs archive must be in .tgz format!"); + } return is_panorama; } @@ -110,23 +110,23 @@ public void UncompressArchive(string archiveName, string targetFolder) { string compressorsDirPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "compressors"; string archiveCopyName = targetFolder + archiveName.Substring(archiveName.LastIndexOf("\\") + 1); - archiveCopyName = archiveCopyName.Substring(0, archiveCopyName.IndexOf(".tgz")) + "_copy" + ".tgz"; - File.Copy(archiveName, archiveCopyName, true); + archiveCopyName = archiveCopyName.Substring(0, archiveCopyName.IndexOf(".tgz")) + "_copy" + ".tgz"; + File.Copy(archiveName, archiveCopyName, true); #region uncompress .TGZ archive ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; Process uncompressProc = null; - startInfo.FileName = Path.Combine(compressorsDirPath, "gzip.exe"); + startInfo.FileName = Path.Combine(compressorsDirPath, "gzip.exe"); startInfo.WorkingDirectory = archiveCopyName.Substring(0, archiveCopyName.LastIndexOf("\\")); startInfo.Arguments = "-d" + " \"" + archiveCopyName + "\""; startInfo.RedirectStandardOutput = true; uncompressProc = Process.Start(startInfo); - startInfo.RedirectStandardError = true; + startInfo.RedirectStandardError = true; string output = uncompressProc.StandardOutput.ReadToEnd(); - uncompressProc.WaitForExit(); + uncompressProc.WaitForExit(); #endregion #region uncompress .TAR archive @@ -139,12 +139,12 @@ public void UncompressArchive(string archiveName, string targetFolder) startInfo.CreateNoWindow = true; string tarArchiveName = archiveCopyName.Substring(0, archiveCopyName.LastIndexOf(".tgz")) + ".tar"; - + startInfo.FileName = Path.Combine(compressorsDirPath, "gtar.exe"); - + string outConfigsFolder = tarArchiveName.Substring(0, tarArchiveName.LastIndexOf("\\")) + "\\configs"; Directory.CreateDirectory(outConfigsFolder); - startInfo.WorkingDirectory = outConfigsFolder; + startInfo.WorkingDirectory = outConfigsFolder; startInfo.Arguments = "-xvf \"" + tarArchiveName + "\" --force-local"; startInfo.RedirectStandardOutput = true; uncompressTarProc = Process.Start(startInfo); @@ -154,7 +154,7 @@ public void UncompressArchive(string archiveName, string targetFolder) uncompressTarProc.WaitForExit(); if (File.Exists(tarArchiveName)) - File.Delete(tarArchiveName); + File.Delete(tarArchiveName); #endregion } } diff --git a/PaloAltoMigration/Panorama_Config.cs b/PaloAltoMigration/Panorama_Config.cs index 91d211f..1897a9f 100644 --- a/PaloAltoMigration/Panorama_Config.cs +++ b/PaloAltoMigration/Panorama_Config.cs @@ -90,25 +90,25 @@ public class PA_TemplateStackEntry : PA_Entry { [XmlArray("templates")] [XmlArrayItem("member")] - public List StackTemplatesMembers{ get; set; } - + public List StackTemplatesMembers { get; set; } + [XmlArray("devices")] [XmlArrayItem("entry")] public List DevicesEntries { get; set; } } -/* - public class PA_StackTemplates: PA_Entry - { - [XmlElement("member")] - public List StackTemplateMembers { get; set; } - } -*/ - public class PA_DevicesTemplateStackMemberEntry: PA_Entry + /* + public class PA_StackTemplates: PA_Entry + { + [XmlElement("member")] + public List StackTemplateMembers { get; set; } + } + */ + public class PA_DevicesTemplateStackMemberEntry : PA_Entry { } - public class PA_DevicesTemplateStackEntry : PA_Entry + public class PA_DevicesTemplateStackEntry : PA_Entry { } @@ -118,15 +118,15 @@ public class PA_TemplateEntry : PA_Entry { [XmlElement("config")] public PA_TemplateConfig Config { get; set; } - + } public class PA_TemplateConfig : PA_Entry { - [XmlElement("devices")] + [XmlElement("devices")] public PA_DevicesTemplateEntry TemplateDevices { get; set; } - } + } public class PA_DevicesTemplateEntry : PA_Entry { @@ -142,7 +142,7 @@ public class PA_DevicesTemplateDevicesEntry : PA_Entry [XmlArray("vsys")] [XmlArrayItem("entry")] public List VsysEntries { get; set; } - } + } public class PA_DeviceGroupEntry : PA_Objects { @@ -163,7 +163,7 @@ public class PA_PostRulebase } public class PA_DevicesGroupDevicesEntry : PA_Entry // devices serial numbers - { + { } @@ -253,9 +253,9 @@ public class PA_VsysEntry : PA_Objects [XmlArray("zone")] [XmlArrayItem("entry")] public List ZoneEntries { get; set; } -/* - [XmlElement("rulebase")] - public PA_Rulebase Rulebase { get; set; }*/ + /* + [XmlElement("rulebase")] + public PA_Rulebase Rulebase { get; set; }*/ } public class PA_TagEntry : PA_Entry { /* the class is empty as we need to know only 'name' attribute of Tag entry */ } @@ -518,18 +518,18 @@ public class PA_Target : PA_Entry public List DevicesEntry { get; set; } } - public class PA_TargetDeviceEntry : PA_Entry{} + public class PA_TargetDeviceEntry : PA_Entry { } -#endregion + #endregion #region NAT XML tags binding (NAT rules) public class PA_Nat - { - [XmlArray("rules")] - [XmlArrayItem("entry")] - public List RulesList { get; set; } - } + { + [XmlArray("rules")] + [XmlArrayItem("entry")] + public List RulesList { get; set; } + } public class PA_NatRuleEntry : PA_EntryExt { @@ -551,7 +551,7 @@ public class PA_NatRuleEntry : PA_EntryExt public PA_DestinationTranslation DestinationTranslation { get; set; } [XmlElement("dynamic-destination-translation")] - public PA_DynamicDestinationTranslation DynamicDestinationTranslation { get;set;} + public PA_DynamicDestinationTranslation DynamicDestinationTranslation { get; set; } [XmlElement("disabled")] public string Disabled { get; set; } diff --git a/SmartMove/AboutWindow.xaml.cs b/SmartMove/AboutWindow.xaml.cs index 7ef8e87..6a67b75 100644 --- a/SmartMove/AboutWindow.xaml.cs +++ b/SmartMove/AboutWindow.xaml.cs @@ -106,7 +106,7 @@ public string AssemblyVersion public static readonly DependencyProperty AssemblyVersionProperty = DependencyProperty.Register("AssemblyVersion", typeof(string), typeof(AboutWindow), new PropertyMetadata(null)); - + #endregion #region AssemblyCopyright @@ -185,7 +185,7 @@ private void Link_OnClick(object sender, MouseButtonEventArgs e) Process.Start(psi); } } - + #endregion } } diff --git a/SmartMove/AnalyzeWindow.xaml.cs b/SmartMove/AnalyzeWindow.xaml.cs index 7dbbb9a..e083d3c 100644 --- a/SmartMove/AnalyzeWindow.xaml.cs +++ b/SmartMove/AnalyzeWindow.xaml.cs @@ -154,7 +154,7 @@ private async void Analyze_OnClickAsync(object sender, RoutedEventArgs e) if (!File.Exists(compressorZip) || !File.Exists(compressorGtar) || !File.Exists(compressorGzip)) { SMDebugger.PrintToDebug(TargetFolderPath.Text + "\\", "The system cannot find the required files. "); - MainWindow.ShowMessage(null, MessageTypes.Error, "these instructions", "https://github.com/CheckPointSW/SmartMove#smart-connector-and-paloalto-panorama-instructions", + MainWindow.ShowMessage(null, MessageTypes.Error, "these instructions", "https://github.com/CheckPointSW/SmartMove#smart-connector-and-paloalto-panorama-instructions", null, null, String.Format("{1}{0}{2}", Environment.NewLine, "The system cannot find the required files. ", "Please follow")); return; } @@ -330,7 +330,7 @@ private async void Analyze_OnClickAsync(object sender, RoutedEventArgs e) OutputPanel.Visibility = Visibility.Collapsed; if (ex is InvalidDataException && ex.Message != null && ex.Message.Contains("Policy exceeds the maximum number")) { - MainWindow.ShowMessage(null, MessageTypes.Error, "ps@checkpoint.com", "mailto:ps@checkpoint.com", null, null, + MainWindow.ShowMessage(null, MessageTypes.Error, "ps@checkpoint.com", "mailto:ps@checkpoint.com", null, null, String.Format("{1}{0}{2}{0}{3}", Environment.NewLine, "SmartAnalyze is unable to analyze the provided policy.", "Reason: Policy exceeds the maximum number of supported policy layers.", "To assure the smooth conversion of your data, it is recommended to contact Check Point Professional Services by sending an e-mail to")); diff --git a/SmartMove/App.xaml.cs b/SmartMove/App.xaml.cs index f25c263..6cb1e87 100644 --- a/SmartMove/App.xaml.cs +++ b/SmartMove/App.xaml.cs @@ -28,6 +28,6 @@ public App() { InitializeComponent(); } - + } } diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index d110877..dd9d38f 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -319,7 +319,7 @@ public CommandLine Parse(string[] args) _successCommands = false; Console.WriteLine("Value for option -d is not specified! ", MessageTypes.Error); } - else if(args[i] != args.Last() && !args[i + 1].StartsWith("-")) + else if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) this.domain = args[i + 1]; else { @@ -368,7 +368,7 @@ public CommandLine Parse(string[] args) this.ldapAccountUnit = args[i + 1]; this.ConvertUserConfiguration = true; } - else + else { this.ConvertUserConfiguration = true; //Console.WriteLine("Value for option -u is not specified! ", MessageTypes.Error); @@ -405,7 +405,7 @@ public CommandLine Parse(string[] args) _successCommands = false; Console.WriteLine("Value for option -f is not specified! ", MessageTypes.Error); } - else if(new List() { "text", "json" }.Contains(args[i + 1].ToLower())) + else if (new List() { "text", "json" }.Contains(args[i + 1].ToLower())) FormatOutput = args[i + 1]; else { @@ -454,10 +454,10 @@ public CommandLine Parse(string[] args) break; } case "-a": - case "--analyzer": + case "--analyzer": { this.isAnalyze = true; - break; + break; } } } @@ -789,7 +789,7 @@ public void DoAnalyze(CommandLine commandLine) vendorConverter = converter; break; case "FirePower": - CiscoConverter fpConverter = new CiscoConverter() + CiscoConverter fpConverter = new CiscoConverter() { isUsingForFirePower = true }; @@ -1003,7 +1003,7 @@ public void DoMigration(CommandLine commandLine) if (commandLine.Vendor.Equals("Panorama")) { - + PanoramaParser panParser = (PanoramaParser)vendorParser; panParser.ParseWithTargetFolder(ciscoFile, Path.GetFullPath(TargetFolder)); } @@ -1093,7 +1093,7 @@ public void DoMigration(CommandLine commandLine) case "JuniperSSG": break; - + case "FirePower": if (string.IsNullOrEmpty(vendorParser.Version)) { diff --git a/SmartMove/DisclaimerWindow.xaml.cs b/SmartMove/DisclaimerWindow.xaml.cs index 3bad7fc..d07625e 100644 --- a/SmartMove/DisclaimerWindow.xaml.cs +++ b/SmartMove/DisclaimerWindow.xaml.cs @@ -32,7 +32,7 @@ public partial class DisclaimerWindow : Window #region Constants private const string DisclaimerFileName = "SmartMove Tool Legal.rtf"; - + #endregion #region Construction @@ -42,7 +42,7 @@ public DisclaimerWindow() InitializeComponent(); Loaded += OnLoaded; } - + #endregion #region Event Handlers @@ -87,7 +87,7 @@ private void HeaderPanel_OnMouseDown(object sender, MouseButtonEventArgs e) DragMove(); } } - + #endregion } } diff --git a/SmartMove/MainWindow.xaml.cs b/SmartMove/MainWindow.xaml.cs index 1a2075f..6964126 100644 --- a/SmartMove/MainWindow.xaml.cs +++ b/SmartMove/MainWindow.xaml.cs @@ -60,7 +60,7 @@ public partial class MainWindow : Window private readonly SupportedVendors _supportedVendors = new SupportedVendors(); private static bool canCloseWindow = true; - + #endregion #region Construction @@ -94,7 +94,7 @@ public Vendor SelectedVendor get { return _supportedVendors.SelectedVendor; } set { _supportedVendors.SelectedVendor = value; } } - + #endregion #region ConfigurationFileLabel @@ -210,7 +210,7 @@ public string ConvertedPolicyRulesCount public static readonly DependencyProperty ConvertedPolicyRulesCountProperty = DependencyProperty.Register("ConvertedPolicyRulesCount", typeof(string), typeof(MainWindow), new PropertyMetadata(null)); - + #endregion #region ConvertedOptimizedPolicyRulesCount @@ -223,7 +223,7 @@ public string ConvertedOptimizedPolicyRulesCount public static readonly DependencyProperty ConvertedOptimizedPolicyRulesCountProperty = DependencyProperty.Register("ConvertedOptimizedPolicyRulesCount", typeof(string), typeof(MainWindow), new PropertyMetadata(null)); - + #endregion #region ConvertedNATPolicyRulesCount @@ -270,7 +270,7 @@ public string ConfigurationFileLinesCount public static string SKText { get; private set; } public static string SKLinkText { get; private set; } public static object SKLinkAddress { get; private set; } - + #endregion #endregion @@ -511,8 +511,9 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) vendorParser = new CiscoParser(); break; case Vendor.FirePower: - vendorParser = new CiscoParser() { - isUsingForFirePower = true + vendorParser = new CiscoParser() + { + isUsingForFirePower = true }; break; case Vendor.JuniperJunosOS: @@ -535,7 +536,7 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) if (!File.Exists(compressorZip) || !File.Exists(compressorGtar) || !File.Exists(compressorGzip)) { SMDebugger.PrintToDebug(TargetFolderPath.Text + "\\", "The system cannot find the required files. "); - ShowMessage(null, MessageTypes.Error, "these instructions", "https://github.com/CheckPointSW/SmartMove#smart-connector-and-paloalto-panorama-instructions", null, null, + ShowMessage(null, MessageTypes.Error, "these instructions", "https://github.com/CheckPointSW/SmartMove#smart-connector-and-paloalto-panorama-instructions", null, null, string.Format("{1}{0}{2}", Environment.NewLine, "The system cannot find the required files. ", "Please follow")); return; @@ -545,7 +546,7 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) default: throw new InvalidDataException("Unexpected!!!"); } - + Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; EnableDisableControls(false); ProgressPanel.Visibility = Visibility.Visible; @@ -553,7 +554,7 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) OutputPanel.Visibility = Visibility.Visible; UpdateProgress(10, "Parsing configuration file ..."); - + string vendorFileName = Path.GetFileNameWithoutExtension(ConfigFilePath.Text); string toolVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); string targetFolder = TargetFolderPath.Text + "\\"; @@ -563,11 +564,11 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) try { string ciscoFile = ConfigFilePath.Text; - switch (_supportedVendors.SelectedVendor) + switch (_supportedVendors.SelectedVendor) { case Vendor.PaloAltoPanorama: - PanoramaParser panParser = (PanoramaParser)vendorParser; - await Task.Run(() => panParser.ParseWithTargetFolder(ciscoFile,targetFolder)); + PanoramaParser panParser = (PanoramaParser)vendorParser; + await Task.Run(() => panParser.ParseWithTargetFolder(ciscoFile, targetFolder)); break; default: await Task.Run(() => vendorParser.Parse(ciscoFile)); @@ -581,7 +582,7 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) EnableDisableControls(true); OutputPanel.Visibility = Visibility.Collapsed; SMDebugger.PrintToDebug(TargetFolderPath.Text + "\\", ex.Message + "\n" + ex.StackTrace); - ShowMessage("Could not convert configuration file.", "Message:\nModule:\nClass:\nMethod:", string.Format("{0}\n{1}\n{2}\n{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + ShowMessage("Could not convert configuration file.", "Message:\nModule:\nClass:\nMethod:", string.Format("{0}\n{1}\n{2}\n{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); return; } @@ -649,7 +650,7 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) ShowMessage("Unspecified FortiGate version.\nCannot find FortiGate version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Error); return; } - else if(vendorParser.MajorVersion < 5) + else if (vendorParser.MajorVersion < 5) { EnableWindow(); SMDebugger.PrintToDebug(TargetFolderPath.Text + "\\", "Unsupported FortiGate version (" + vendorParser.Version + ").\nThis tool supports FortiGate 5.x and above configuration files.\nThe configuration may not parse correctly."); @@ -703,7 +704,8 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) vendorConverter = ciscoConverter; break; case Vendor.FirePower: - vendorConverter = new CiscoConverter() { + vendorConverter = new CiscoConverter() + { isUsingForFirePower = true, SkipUnusedObjects = SkipUnusedObjectsConversion }; @@ -734,7 +736,7 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) vendorConverter = paConverter; break; case Vendor.PaloAltoPanorama: - PanoramaConverter panoramaConverter = new PanoramaConverter(); + PanoramaConverter panoramaConverter = new PanoramaConverter(); panoramaConverter.OptimizeConf = SkipUnusedObjectsConversion; panoramaConverter.ConvertUserConf = ConvertUserConfiguration; panoramaConverter.LDAPAccoutUnit = ldapAccountUnit.Trim(); @@ -774,8 +776,9 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) ShowMessage(null, MessageTypes.Error, null, null, null, null, String.Format("{1}{0}{2}", Environment.NewLine, "Could not convert configuration file.", "Reason: Your device is low on memory.")); - } else - ShowMessage("Could not convert configuration file.", "Message:\nModule:\nClass:\nMethod:", string.Format("{0}\n{1}\n{2}\n{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + } + else + ShowMessage("Could not convert configuration file.", "Message:\nModule:\nClass:\nMethod:", string.Format("{0}\n{1}\n{2}\n{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); } return; } @@ -785,11 +788,11 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) vendorConverter.ExportPolicyPackagesAsHtml(); if (ConvertNATConfiguration) { - ConvertedNatPolicyLink.MouseUp -= Link_OnClick; + ConvertedNatPolicyLink.MouseUp -= Link_OnClick; vendorConverter.ExportNatLayerAsHtml(); //check if the user asked for NAT policy and no rules found. - if (vendorConverter.RulesInNatLayer() == 0 ) // anly if 0 then we do not show NAT report. + if (vendorConverter.RulesInNatLayer() == 0) // anly if 0 then we do not show NAT report. { ConvertedNatPolicyLink.Style = (Style)ConvertedNatPolicyLink.FindResource("NormalTextBloclStyle"); } @@ -896,7 +899,7 @@ private void ShowResults(VendorConverter vendorConverter, int convertedLinesCoun case Vendor.CiscoASA: case Vendor.FirePower: ConvertedOptimizedPolicyPanel.Visibility = Visibility.Visible; - RulebaseOptimizedScriptLink.Visibility = Visibility.Visible; + RulebaseOptimizedScriptLink.Visibility = Visibility.Visible; CoversionIssuesPreviewPanel.Visibility = Visibility.Visible; CiscoConverter ciscoConverter = (CiscoConverter)vendorConverter; @@ -1006,7 +1009,7 @@ private void ShowResults(VendorConverter vendorConverter, int convertedLinesCoun ConvertedPolicyPreviewPanel.Visibility = (ConvertedPolicyLink.Visibility == Visibility.Visible || ConvertedNatPolicyPanel.Visibility == Visibility.Visible || ConvertedOptimizedPolicyPanel.Visibility == Visibility.Visible) ? Visibility.Visible : Visibility.Collapsed; } - + private void LoadContactInfo() { @@ -1075,12 +1078,12 @@ private void HandleCommandLineArgs() { } } - + public static void ShowMessage(string header, string columns, string message, MessageTypes messageType) { ShowMessage(message, messageType, null, null, header, columns); } - + public static void ShowMessage(string message, MessageTypes messageType) { ShowMessage(null, messageType, null, null, null, null, message); diff --git a/SmartMove/MessageWindow.xaml.cs b/SmartMove/MessageWindow.xaml.cs index a732ad6..11b2787 100644 --- a/SmartMove/MessageWindow.xaml.cs +++ b/SmartMove/MessageWindow.xaml.cs @@ -50,7 +50,7 @@ public string Header DependencyProperty.Register("Header", typeof(string), typeof(MessageWindow), new PropertyMetadata(null)); #endregion - + #region Message public string Message @@ -89,7 +89,7 @@ public string MessageWoColumns DependencyProperty.Register("MessageWoColumns", typeof(string), typeof(MessageWindow), new PropertyMetadata(null)); #endregion - + #region MessageLink public string MessageLinkText { @@ -117,7 +117,7 @@ public string MessageLinkValue DependencyProperty.Register("MessageLinkValue", typeof(string), typeof(MessageWindow), new PropertyMetadata(null)); #endregion - + #region MessageType public MessageTypes MessageType @@ -147,7 +147,7 @@ private void HeaderPanel_OnMouseDown(object sender, MouseButtonEventArgs e) DragMove(); } } - + private void Link_OnClick(object sender, RoutedEventArgs e) { var link = (Hyperlink)sender; diff --git a/SmartMove/Program.cs b/SmartMove/Program.cs index dda54b8..b951138 100644 --- a/SmartMove/Program.cs +++ b/SmartMove/Program.cs @@ -16,7 +16,7 @@ public static int Main(string[] args) { if (args != null && args.Length > 0) { - CommandLine commandLine = new CommandLine(args); + CommandLine commandLine = new CommandLine(args); //display command help if (args[0].Equals("--help") || args[0].Equals("/?") || args[0].Equals("-h")) @@ -27,34 +27,35 @@ public static int Main(string[] args) args = commandLine.regenerateArgs(Environment.CommandLine); commandLine = commandLine.Parse(args); -/* - Console.WriteLine(); - Console.WriteLine(" -> Config file name: " + commandLine.ConfigFileName); - Console.WriteLine(" -> Target folder: " + commandLine.TargetFolder); - Console.WriteLine(" -> Vendor: " + commandLine.Vendor); - Console.WriteLine(" -> Domain: " + commandLine.Domain); - Console.WriteLine(" -> Convert NAT option: " + commandLine.ConvertNat); - Console.WriteLine(" -> LDAP account unit: " + commandLine.LdapAccountUnit); - Console.WriteLine(" -> Convert user configuration option: " + commandLine.ConvertUserConfiguration); - Console.WriteLine(" -> Don't import unused objects option: " + commandLine.DontImportUnusedObjects); - Console.WriteLine();*/ + /* + Console.WriteLine(); + Console.WriteLine(" -> Config file name: " + commandLine.ConfigFileName); + Console.WriteLine(" -> Target folder: " + commandLine.TargetFolder); + Console.WriteLine(" -> Vendor: " + commandLine.Vendor); + Console.WriteLine(" -> Domain: " + commandLine.Domain); + Console.WriteLine(" -> Convert NAT option: " + commandLine.ConvertNat); + Console.WriteLine(" -> LDAP account unit: " + commandLine.LdapAccountUnit); + Console.WriteLine(" -> Convert user configuration option: " + commandLine.ConvertUserConfiguration); + Console.WriteLine(" -> Don't import unused objects option: " + commandLine.DontImportUnusedObjects); + Console.WriteLine();*/ int exitCode = commandLine.CheckOptionsValidity(commandLine); - + if (exitCode == 0) { return 0; - } else - { - if(commandLine.IsAnalyze) + } + else + { + if (commandLine.IsAnalyze) { Console.WriteLine($"IS ANALYZE {commandLine.IsAnalyze}"); - commandLine.DoAnalyze(commandLine); + commandLine.DoAnalyze(commandLine); } else { commandLine.DoMigration(commandLine); - } + } return 0; } } @@ -65,6 +66,6 @@ public static int Main(string[] args) return app.Run(); } } - + } } diff --git a/SmartMove/Properties/AssemblyInfo.cs b/SmartMove/Properties/AssemblyInfo.cs index 4abce54..6ed58d5 100644 --- a/SmartMove/Properties/AssemblyInfo.cs +++ b/SmartMove/Properties/AssemblyInfo.cs @@ -31,11 +31,11 @@ [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) + //(used if a resource is not found in the page, + // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) )] diff --git a/SmartMove/TripleClickSelectsAllTextBehavior.cs b/SmartMove/TripleClickSelectsAllTextBehavior.cs index 42b7148..7786ae0 100644 --- a/SmartMove/TripleClickSelectsAllTextBehavior.cs +++ b/SmartMove/TripleClickSelectsAllTextBehavior.cs @@ -42,7 +42,7 @@ protected override void OnDetaching() AssociatedObject.PreviewMouseLeftButtonDown -= OnTextBoxPreviewMouseLeftButtonDown; AssociatedObject.LostFocus -= OnTextBoxLostFocus; } - + #endregion #region Event Handlers @@ -60,7 +60,7 @@ private void OnTextBoxLostFocus(object sender, System.Windows.RoutedEventArgs e) { AssociatedObject.Select(0, 0); } - + #endregion } } From 0c373e1c5735ea57dabb3bca95f072d5fefe28dc Mon Sep 17 00:00:00 2001 From: ofir shikolski Date: Tue, 18 Oct 2022 11:34:57 +0300 Subject: [PATCH 04/16] format whitespace format whitespace --- .github/contributing.md | 6 +- .pre-commit-config.yaml | 8 ++ CheckPointObjects/CheckPointObjects.cs | 6 +- CheckPointObjects/CheckPointObjects.csproj | 2 +- .../CheckPointObjectsRepository.cs | 2 +- CheckPointObjects/Properties/AssemblyInfo.cs | 10 +- CheckPointObjects/RuleBaseOptimizer.cs | 2 +- CiscoMigration/CiscoCommands.cs | 46 ++++----- CiscoMigration/CiscoConverter.cs | 16 ++-- CiscoMigration/CiscoMigration.csproj | 2 +- CiscoMigration/Properties/AssemblyInfo.cs | 10 +- CommonUtils/CommonUtils.csproj | 2 +- CommonUtils/ConversionIncident.cs | 2 +- CommonUtils/Properties/AssemblyInfo.cs | 10 +- FortinetMigration/FortiGateConverter.cs | 2 +- FortinetMigration/FortiGateMigration.csproj | 2 +- FortinetMigration/Properties/AssemblyInfo.cs | 10 +- JuniperMigration/JuniperConverter.cs | 20 ++-- JuniperMigration/JuniperMigration.csproj | 2 +- JuniperMigration/Properties/AssemblyInfo.cs | 10 +- JuniperMigration/junos-defaults.xml | 82 ++++++++-------- MigrationBase/MigrationBase.csproj | 2 +- MigrationBase/Properties/AssemblyInfo.cs | 10 +- NetScreenMigration/NetScreenMigration.csproj | 2 +- NetScreenMigration/Properties/AssemblyInfo.cs | 10 +- .../ScreenOSPredefinedServices.csv | 2 +- PaloAltoMigration/PA_Apps_CP.csv | 2 +- PaloAltoMigration/PaloAltoMigration.csproj | 2 +- PaloAltoMigration/PanoramaConverter.cs | 20 ++-- PaloAltoMigration/PanoramaParser.cs | 6 +- PaloAltoMigration/Panorama_Config.cs | 2 +- PaloAltoMigration/Properties/AssemblyInfo.cs | 10 +- README.md | 22 ++--- SmartMove/App.config | 2 +- SmartMove/App.xaml | 2 +- SmartMove/CommandLine.cs | 8 +- SmartMove/CommonResources.xaml | 6 +- SmartMove/MainWindow.xaml.cs | 4 +- SmartMove/Properties/AssemblyInfo.cs | 16 ++-- SmartMove/Properties/Resources.resx | 54 +++++------ SmartMove/SmartConnector/smartconnector.py | 2 +- SmartMove/SmartMove.csproj | 2 +- SmartMove/contact.txt | 2 +- SmartMove/sk.txt | 2 +- .../lib/net45/Newtonsoft.Json.xml | 94 +++++++++---------- 45 files changed, 272 insertions(+), 264 deletions(-) create mode 100644 .pre-commit-config.yaml diff --git a/.github/contributing.md b/.github/contributing.md index eb6befa..01b07e7 100644 --- a/.github/contributing.md +++ b/.github/contributing.md @@ -1,10 +1,10 @@ ## Code and testing requirements: - - The tool is developed using Microsoft C# language and .NET framework version 4.5 (WPF application). + - The tool is developed using Microsoft C# language and .NET framework version 4.5 (WPF application). - The project solution file is configured for Microsoft Visual Studio 2012 (C# v5). - Do not add new external libraries or any 3rd party code (open source or commercial). - - The code will be implemented with high quality standards. It should be designed well, refactored for easy reuse and easy maintenance, efficient as possible, readable and well documented. + - The code will be implemented with high quality standards. It should be designed well, refactored for easy reuse and easy maintenance, efficient as possible, readable and well documented. - Verify functionality and correctness of the tool, including end-to-end testing & QA. - + ## Committing code to GitHub: - Commit/PR name needs to be meaningful and explain the change and not the issue it solves. For example: User is suffering from failure due to host name collision – commit name would be: “Handle host creation in case of name duplications”. - Commit/PR description needs to contain more details about the issue and the solution. diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..918cc35 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,8 @@ +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v2.3.0 + hooks: + - id: trailing-whitespace + - id: mixed-line-ending + - id: check-merge-conflict + - id: check-case-conflict diff --git a/CheckPointObjects/CheckPointObjects.cs b/CheckPointObjects/CheckPointObjects.cs index f07b5ef..9f123aa 100644 --- a/CheckPointObjects/CheckPointObjects.cs +++ b/CheckPointObjects/CheckPointObjects.cs @@ -202,7 +202,7 @@ public class CheckPoint_Domain : CheckPointObject public override string ToCLIScript() { return "add dns-domain " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("is-sub-domain", IsSubDomain, !IsSubDomain) //"is-sub-domain" is a required field by documentation + + WriteParam("is-sub-domain", IsSubDomain, !IsSubDomain) //"is-sub-domain" is a required field by documentation + WriteListParam("tags", Tags, true); } @@ -303,7 +303,7 @@ public class CheckPoint_NetworkGroup : CheckPointObject public bool IsPanoramaDeviceGroup = false; /// - /// This property is used to overcome the problematic order of objects creation for + /// This property is used to overcome the problematic order of objects creation for /// GroupWithExclusion and NetworkGroup types cross-referencing each other. /// public bool CreateAfterGroupsWithExclusion { get; set; } @@ -866,7 +866,7 @@ public bool IsCleanupRule() { return true; // sub-policy's automatic cleanup rule } - return checkRuleType(ActionType.Drop);// user defined cleanup rule + return checkRuleType(ActionType.Drop);// user defined cleanup rule } /// diff --git a/CheckPointObjects/CheckPointObjects.csproj b/CheckPointObjects/CheckPointObjects.csproj index 872f891..fe8d207 100644 --- a/CheckPointObjects/CheckPointObjects.csproj +++ b/CheckPointObjects/CheckPointObjects.csproj @@ -73,7 +73,7 @@ - may be also a icmp service object * object-group service_group_id * object-group protocol_group_id - * + * * source_address_argument/dest_address_argument specification: one of the following options: * ------------------------------------------------------------------------------------------ * any/any4/any6 @@ -2181,17 +2181,17 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti * object network_object_id * object-group network_group_id * ip_address ip_mask - * + * * icmp_argument specification: one of the following options: * ---------------------------------------------------------- * icmp_type * object-group icmp_group_id --> object-group icmp-type command - * + * * port_argument specification: one of the following options: * ---------------------------------------------------------- * operator port --> where operator can be one of: lt, gt, eq, neq, range; port can be number or name of a TCP or UDP port * object-group service_group_id - * + * */ base.Parse(command, prevCommand, ciscoIds, aliases); diff --git a/CiscoMigration/CiscoConverter.cs b/CiscoMigration/CiscoConverter.cs index 20bcdb5..10c6c3f 100644 --- a/CiscoMigration/CiscoConverter.cs +++ b/CiscoMigration/CiscoConverter.cs @@ -2167,7 +2167,7 @@ private void Add_ServicesAndServiceGroups() break; default: - // No need to check also for CiscoKnownServices.IsKnownServiceNumber here, + // No need to check also for CiscoKnownServices.IsKnownServiceNumber here, // because it is already done in Cisco_ServiceObject class!!! if (CiscoKnownServices.IsKnownService(ciscoService.Protocol)) { @@ -2781,7 +2781,7 @@ private void Add_ParentLayer(CheckPoint_Package package) availableZones.Add(cpZone); - // If the _isInterInterfaceTrafficAllowed flag is on and there are at least two Cisco interfaces with zero security level, + // If the _isInterInterfaceTrafficAllowed flag is on and there are at least two Cisco interfaces with zero security level, // we should add parent rules for the equivalent CP zones to allow traffic between them. if (ciscoInterface.SecurityLevel == 0) { @@ -2983,7 +2983,7 @@ private void Add_Global_Rules(CheckPoint_Package package) { if (_ciscoGlobalAclCommands.Count > 0) { - // remove clenup rule of each sublayer if global rules exist because cleanup rule should be added after global-rules + // remove clenup rule of each sublayer if global rules exist because cleanup rule should be added after global-rules foreach (var subpolicy in package.SubPolicies) { if (subpolicy.Rules.Count > 0) @@ -3035,7 +3035,7 @@ private void Add_Global_Rules(CheckPoint_Package package) foreach (var globalPolicyRule in _ciscoGlobalAclCommands) { - // Append the global policy rules BELOW the existing sub-policies. + // Append the global policy rules BELOW the existing sub-policies. CheckPoint_Rule cpRule = Acl_To_CPRule(globalPolicyRule, cpSubLayer4GlobalRules.Name); cpSubLayer4GlobalRules.Rules.Add(cpRule); } @@ -3123,7 +3123,7 @@ private void Add_Global_Rules(CheckPoint_Package package) NewCiscoAnalizStatistic._nonServicesLoggingServicesRulesCount++; } - // If the global ACL didn't have an incident previously, + // If the global ACL didn't have an incident previously, // and the incident was just encountered during this convertion, retain the incident!!! if (ciscoAcl.ConversionIncidentType == ConversionIncidentType.None) { @@ -3721,7 +3721,7 @@ private void Add_AclServices_To_CPRule(Cisco_AccessList ciscoAcl, Cisco_GroupObj NewCiscoAnalizStatistic._rulesServicesutilizingServicesAnyCount++; } - // This may happen, for example, if: + // This may happen, for example, if: // 1. both source and destination protocols are defined on the Cisco service // 2. the Cisco service has a duplicate name if (ciscoReferencedService.ConversionIncidentType != ConversionIncidentType.None) @@ -4052,7 +4052,7 @@ private void Add_Layers_And_Rules_For_Other_Zones(CheckPoint_Package package) availableZones.Add(cpZone); - // If the _isInterInterfaceTrafficAllowed flag is on and there are at least two Cisco interfaces with zero security level, + // If the _isInterInterfaceTrafficAllowed flag is on and there are at least two Cisco interfaces with zero security level, // we should add sub-policies for the equivalent CP zones to allow traffic between them. if (ciscoInterface.SecurityLevel == 0) { @@ -4834,7 +4834,7 @@ private void Add_NAT_Rules() "Translated service details: " + ciscoNat.TranslatedServiceId + "."); } - // Static NAT: if a source is a network or a network group and a translated source is a host, + // Static NAT: if a source is a network or a network group and a translated source is a host, // we should convert to dynamic NAT rule!!! if (cpNatRule.Method == CheckPoint_NAT_Rule.NatMethod.Static) { diff --git a/CiscoMigration/CiscoMigration.csproj b/CiscoMigration/CiscoMigration.csproj index d9b4816..bd039e7 100644 --- a/CiscoMigration/CiscoMigration.csproj +++ b/CiscoMigration/CiscoMigration.csproj @@ -75,7 +75,7 @@ - @@ -229,7 +229,7 @@ - + @@ -306,7 +306,7 @@ diff --git a/SmartMove/MainWindow.xaml.cs b/SmartMove/MainWindow.xaml.cs index 6964126..c5eccef 100644 --- a/SmartMove/MainWindow.xaml.cs +++ b/SmartMove/MainWindow.xaml.cs @@ -1090,8 +1090,8 @@ public static void ShowMessage(string message, MessageTypes messageType) } /// - /// Build a message for displaying. If need to show technical columns like "method", "Class" then need to pass to message - /// message after columns, list of columns to colums and to header pass main message. If need just display a text + /// Build a message for displaying. If need to show technical columns like "method", "Class" then need to pass to message + /// message after columns, list of columns to colums and to header pass main message. If need just display a text /// then pass to message, columns, header null values and fill only messageWoColumns /// /// message for displaying with columns. If need display without columns set to null diff --git a/SmartMove/Properties/AssemblyInfo.cs b/SmartMove/Properties/AssemblyInfo.cs index 6ed58d5..5647872 100644 --- a/SmartMove/Properties/AssemblyInfo.cs +++ b/SmartMove/Properties/AssemblyInfo.cs @@ -2,7 +2,7 @@ using System.Runtime.InteropServices; using System.Windows; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SmartMove")] @@ -14,12 +14,12 @@ [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] -//In order to begin building localizable applications, set +//In order to begin building localizable applications, set //CultureYouAreCodingWith in your .csproj file //inside a . For example, if you are using US english //in your source files, set the to en-US. Then uncomment @@ -31,10 +31,10 @@ [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, + //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, + //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] @@ -42,11 +42,11 @@ // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Build and Revision Numbers +// You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("9.19.*")] diff --git a/SmartMove/Properties/Resources.resx b/SmartMove/Properties/Resources.resx index af7dbeb..9c90483 100644 --- a/SmartMove/Properties/Resources.resx +++ b/SmartMove/Properties/Resources.resx @@ -1,17 +1,17 @@  - diff --git a/SmartMove/SmartConnector/smartconnector.py b/SmartMove/SmartConnector/smartconnector.py index 57f7b41..153c6ce 100644 --- a/SmartMove/SmartConnector/smartconnector.py +++ b/SmartMove/SmartConnector/smartconnector.py @@ -395,7 +395,7 @@ def is_valid_ipv6(ip): | (? - - \ No newline at end of file + diff --git a/CiscoMigration/CiscoAnalizStatistic.cs b/CiscoMigration/CiscoAnalizStatistic.cs index 53b123e..fb6e268 100644 --- a/CiscoMigration/CiscoAnalizStatistic.cs +++ b/CiscoMigration/CiscoAnalizStatistic.cs @@ -188,4 +188,4 @@ public override void CalculateServices(List _cpTcpService } } -} \ No newline at end of file +} diff --git a/CiscoMigration/CiscoMigration.csproj b/CiscoMigration/CiscoMigration.csproj index bd039e7..117f5b7 100644 --- a/CiscoMigration/CiscoMigration.csproj +++ b/CiscoMigration/CiscoMigration.csproj @@ -82,4 +82,4 @@ --> - \ No newline at end of file + diff --git a/CommonUtils/CommonUtils.csproj b/CommonUtils/CommonUtils.csproj index 6dd5c64..387ab31 100644 --- a/CommonUtils/CommonUtils.csproj +++ b/CommonUtils/CommonUtils.csproj @@ -62,4 +62,4 @@ --> - \ No newline at end of file + diff --git a/FortinetMigration/FortiGateConverter.cs b/FortinetMigration/FortiGateConverter.cs index c78e4f8..9a8942a 100644 --- a/FortinetMigration/FortiGateConverter.cs +++ b/FortinetMigration/FortiGateConverter.cs @@ -5816,4 +5816,4 @@ public void CalculateCorrectAll(List _cpNetworks, count = _nestedServicesGroupsCountAll = vs.Count; _nestedServicesGroupsCount = count - vs.Distinct().Count(); } -} \ No newline at end of file +} diff --git a/FortinetMigration/FortiGateMigration.csproj b/FortinetMigration/FortiGateMigration.csproj index 093837f..d39024b 100644 --- a/FortinetMigration/FortiGateMigration.csproj +++ b/FortinetMigration/FortiGateMigration.csproj @@ -73,4 +73,4 @@ --> - \ No newline at end of file + diff --git a/JuniperMigration/JuniperMigration.csproj b/JuniperMigration/JuniperMigration.csproj index acd9c9d..5cc4f16 100644 --- a/JuniperMigration/JuniperMigration.csproj +++ b/JuniperMigration/JuniperMigration.csproj @@ -91,4 +91,4 @@ --> - \ No newline at end of file + diff --git a/JuniperMigration/junos-defaults.xml b/JuniperMigration/junos-defaults.xml index 4092ccb..c99b67e 100644 --- a/JuniperMigration/junos-defaults.xml +++ b/JuniperMigration/junos-defaults.xml @@ -2126,4 +2126,4 @@ [edit] - \ No newline at end of file + diff --git a/MigrationBase/MigrationBase.csproj b/MigrationBase/MigrationBase.csproj index 92b12cb..8d67328 100644 --- a/MigrationBase/MigrationBase.csproj +++ b/MigrationBase/MigrationBase.csproj @@ -67,4 +67,4 @@ --> - \ No newline at end of file + diff --git a/NetScreenMigration/NetScreenMigration.csproj b/NetScreenMigration/NetScreenMigration.csproj index e99caf9..5313d19 100644 --- a/NetScreenMigration/NetScreenMigration.csproj +++ b/NetScreenMigration/NetScreenMigration.csproj @@ -88,4 +88,4 @@ --> - \ No newline at end of file + diff --git a/NetScreenMigration/ScreenOSPredefinedGroupServiceCPMap.csv b/NetScreenMigration/ScreenOSPredefinedGroupServiceCPMap.csv index 9c69a28..ad035a8 100644 --- a/NetScreenMigration/ScreenOSPredefinedGroupServiceCPMap.csv +++ b/NetScreenMigration/ScreenOSPredefinedGroupServiceCPMap.csv @@ -1,4 +1,4 @@ DISCARD,discard ECHO,echo GNUTELLA,GNUtella -NTP,ntp \ No newline at end of file +NTP,ntp diff --git a/NetScreenMigration/ScreenOSPredefinedServiceGroups.csv b/NetScreenMigration/ScreenOSPredefinedServiceGroups.csv index 1f169ff..d138539 100644 --- a/NetScreenMigration/ScreenOSPredefinedServiceGroups.csv +++ b/NetScreenMigration/ScreenOSPredefinedServiceGroups.csv @@ -3,4 +3,4 @@ MGCP,MGCP-CA,MGCP-UA MS-AD,MS-AD-BR,MS-AD-DRSUAPI,MS-AD-DSROLE,MS-AD-DSSETUP MS-EXCHANGE,MS-EXCHANGE-DATABASE,MS-EXCHANGE-DIRECTORY,MS-EXCHANGE-INFO-STORE,MS-EXCHANGE-MTA,MS-EXCHANGE-STORE,MS-EXCHANGE-SYSATD MS-IIS,MS-IIS-COM,MS-IIS-IMAP4,MS-IIS-INETINFO,MS-IIS-NNTP,MS-IIS-POP3,MS-IIS-SMTP -VOIP,H.323,MGCP-CA,MGCP-UA,SCCP,SIP \ No newline at end of file +VOIP,H.323,MGCP-CA,MGCP-UA,SCCP,SIP diff --git a/PaloAltoMigration/PA_Apps_CP.csv b/PaloAltoMigration/PA_Apps_CP.csv index d7ac619..205ca6a 100644 --- a/PaloAltoMigration/PA_Apps_CP.csv +++ b/PaloAltoMigration/PA_Apps_CP.csv @@ -2857,4 +2857,4 @@ zumodrive;ZumoDrive; zwiki-editing;; zynga-games;Zynga Games; unknown-tcp;Unknown Traffic; -unknown-udp;Unknown Traffic; \ No newline at end of file +unknown-udp;Unknown Traffic; diff --git a/PaloAltoMigration/PaloAltoMigration.csproj b/PaloAltoMigration/PaloAltoMigration.csproj index df207d8..58dc29d 100644 --- a/PaloAltoMigration/PaloAltoMigration.csproj +++ b/PaloAltoMigration/PaloAltoMigration.csproj @@ -85,4 +85,4 @@ --> - \ No newline at end of file + diff --git a/PaloAltoMigration/PanoramaAnalizStatistic.cs b/PaloAltoMigration/PanoramaAnalizStatistic.cs index e6278da..2c32a44 100644 --- a/PaloAltoMigration/PanoramaAnalizStatistic.cs +++ b/PaloAltoMigration/PanoramaAnalizStatistic.cs @@ -140,4 +140,4 @@ public override void CalculateServices(List _cpTcpService _unusedServicesObjectsCount = vs.Count(); } } -} \ No newline at end of file +} diff --git a/SmartMove/App.config b/SmartMove/App.config index bc3672d..486e3ea 100644 --- a/SmartMove/App.config +++ b/SmartMove/App.config @@ -3,4 +3,4 @@ - \ No newline at end of file + diff --git a/SmartMove/CommonResources.xaml b/SmartMove/CommonResources.xaml index e6a282a..b117d0a 100644 --- a/SmartMove/CommonResources.xaml +++ b/SmartMove/CommonResources.xaml @@ -388,4 +388,4 @@ - \ No newline at end of file + diff --git a/SmartMove/Properties/Resources.resx b/SmartMove/Properties/Resources.resx index 9c90483..ea9cbcd 100644 --- a/SmartMove/Properties/Resources.resx +++ b/SmartMove/Properties/Resources.resx @@ -114,4 +114,4 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - \ No newline at end of file + diff --git a/SmartMove/Properties/Settings.settings b/SmartMove/Properties/Settings.settings index 033d7a5..c2dbd5c 100644 --- a/SmartMove/Properties/Settings.settings +++ b/SmartMove/Properties/Settings.settings @@ -4,4 +4,4 @@ - \ No newline at end of file + diff --git a/SmartMove/SmartConnector/smartconnector.py b/SmartMove/SmartConnector/smartconnector.py index 153c6ce..62daabc 100644 --- a/SmartMove/SmartConnector/smartconnector.py +++ b/SmartMove/SmartConnector/smartconnector.py @@ -1383,7 +1383,7 @@ def processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, login_res = client.login_with_api_key(args.key, domain=args.domain) if login_res.success is False: - printStatus(None, "Login failed: {}".format(login_res.error_message)) + printStatus(None, f"Login failed: {login_res.error_message}") else: printStatus(None, "") mergedNetworkObjectsMap = {} @@ -1409,4 +1409,4 @@ def processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, mergedServicesObjectsMap) printStatus(None, "==========") file_log.close() -# END \ No newline at end of file +# END diff --git a/SmartMove/SmartMove Tool Legal.rtf b/SmartMove/SmartMove Tool Legal.rtf index d46d7a5c1a8ba4966a1f8ca27ee8f75c357c0f8d..da084179e73c17642258b6f4b66b78a5a993ef50 100644 GIT binary patch delta 10 Rcmey(_m^)&H9He87XTS;17H9E delta 7 Ocmey%_nU7+H9G(gasx*I diff --git a/SmartMove/SmartMove.csproj b/SmartMove/SmartMove.csproj index be95f11..e2c0a24 100644 --- a/SmartMove/SmartMove.csproj +++ b/SmartMove/SmartMove.csproj @@ -254,4 +254,4 @@ --> - \ No newline at end of file + diff --git a/SmartMove/packages.config b/SmartMove/packages.config index 78de1fe..40fdc0d 100644 --- a/SmartMove/packages.config +++ b/SmartMove/packages.config @@ -2,4 +2,4 @@ - \ No newline at end of file + diff --git a/packages/IPNetwork2.2.0.3/lib/net40/LICENSE.txt b/packages/IPNetwork2.2.0.3/lib/net40/LICENSE.txt index 64b1b05..6012301 100644 --- a/packages/IPNetwork2.2.0.3/lib/net40/LICENSE.txt +++ b/packages/IPNetwork2.2.0.3/lib/net40/LICENSE.txt @@ -20,4 +20,4 @@ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/Newtonsoft.Json.8.0.3/lib/net45/LICENSE.txt b/packages/Newtonsoft.Json.8.0.3/lib/net45/LICENSE.txt index 0fecee7..dfaadbe 100644 --- a/packages/Newtonsoft.Json.8.0.3/lib/net45/LICENSE.txt +++ b/packages/Newtonsoft.Json.8.0.3/lib/net45/LICENSE.txt @@ -17,4 +17,4 @@ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. From 99cd36b4db21511e16ec6d252ec618eb2d0ace4a Mon Sep 17 00:00:00 2001 From: ofir shikolski Date: Tue, 18 Oct 2022 13:27:30 +0300 Subject: [PATCH 07/16] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 90674c6..3694a45 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # SmartMove Check Point SmartMove tool enables you to convert 3rd party database with firewall security policy and NAT to Check Point database. -At the moment, the tool parses Cisco ASA, FirePower with ASA syntax, Juniper JunosOS/ScreenOS, Fortinet FortiOS, PaloAlto PAN-OS and PaloAlto Panorama configurations and converts the objects, NAT and firewall policy to a Check Point R80.10 compliant policy. The tool is planned to support additional vendors and security configurations in the future. +At the moment, the tool parses Cisco ASA, FirePower with ASA syntax, Juniper JunosOS/ScreenOS, Fortinet FortiOS, PaloAlto PAN-OS and PaloAlto Panorama configurations and converts the objects, NAT and firewall policy to a Check Point R80.40+ compliant policy. The tool is planned to support additional vendors and security configurations in the future. -The tool generates bash scripts by utilizing Check Point Management API's command line interface, to migrate the converted policy into a R80.10 Management (or Multi-Domain) server. +The tool generates python package by utilizing Check Point Management API's command line interface, to migrate the converted policy into a R80.40+ Management (or Multi-Domain) server. For SmartMove tool release notes and latest updates, please refer to Check Point [sk115416](https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk115416) From ec8dec479af2755213ac0f0304d885d4410eddbd Mon Sep 17 00:00:00 2001 From: ofir shikolski Date: Tue, 18 Oct 2022 13:45:52 +0300 Subject: [PATCH 08/16] Update .pre-commit-config.yaml --- .pre-commit-config.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3666975..ce6ed31 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,6 +9,9 @@ repos: - id: check-ast - id: check-docstring-first - id: end-of-file-fixer + - id: check-builtin-literals + - id: debug-statements + - id: forbid-new-submodules - repo: https://github.com/asottile/pyupgrade rev: v3.1.0 hooks: From 8f2d687bb449fd7cf6b466b7b020e164c6235968 Mon Sep 17 00:00:00 2001 From: ofir shikolski Date: Tue, 18 Oct 2022 14:14:28 +0300 Subject: [PATCH 09/16] Update .pre-commit-config.yaml Detect hardcoded secrets --- .pre-commit-config.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ce6ed31..839d4c5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,3 +17,10 @@ repos: hooks: - id: pyupgrade args: [--py37-plus] +- repo: https://github.com/zricethezav/gitleaks + rev: v7.6.1 + hooks: + - id: gitleaks + name: Detect hardcoded secrets + description: Detect hardcoded secrets using Gitleaks + args: [--debug, --verbose, --repo-url, .] From 6ccb8b6dd64909ca6a3f1e40e5d6d583171ba2b1 Mon Sep 17 00:00:00 2001 From: ofir shikolski Date: Tue, 18 Oct 2022 18:48:39 +0300 Subject: [PATCH 10/16] Update .gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 5dd3e44..b1c1ac1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ - +build.bat SmartMove/SmartConnector/*.pyc SmartMove/SmartConnector/.idea SmartMove/compressors/*.exe From 40cc1f70b388290b7b1d783f6110ffec1f60be36 Mon Sep 17 00:00:00 2001 From: Sivan Shlomov Date: Wed, 19 Oct 2022 11:34:07 +0300 Subject: [PATCH 11/16] Adding the option to optimize by commets --- CheckPointObjects/RuleBaseOptimizer.cs | 23 +++++++--- CiscoMigration/CiscoCommands.cs | 8 ++-- CiscoMigration/CiscoConverter.cs | 5 +- CiscoMigration/CiscoParser.cs | 6 ++- SmartMove/CommandLine.cs | 36 ++++++++++++++- SmartMove/MainWindow.xaml | 11 ++++- SmartMove/MainWindow.xaml.cs | 63 +++++++++++++++++++++++++- SmartMove/SmartMove.csproj | 4 ++ 8 files changed, 137 insertions(+), 19 deletions(-) diff --git a/CheckPointObjects/RuleBaseOptimizer.cs b/CheckPointObjects/RuleBaseOptimizer.cs index 48e9367..a0c4893 100644 --- a/CheckPointObjects/RuleBaseOptimizer.cs +++ b/CheckPointObjects/RuleBaseOptimizer.cs @@ -15,12 +15,13 @@ You may obtain a copy of the License at limitations under the License. ********************************************************************/ +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using CommonUtils; - + namespace CheckPointObjects { /// @@ -34,9 +35,13 @@ namespace CheckPointObjects /// 5.1. both the source and destination columns match /// 5.2. both the source and service columns match /// 5.3. both the destination and service columns match + /// for CiscoASA and FirePower vendors there is an option to optimize by comments - + /// two rules can be merged if they have the same comments and in addition they up to the above criteria. /// public static class RuleBaseOptimizer { + + public static bool IsOptimizeByComments = false; public static CheckPoint_Layer Optimize(CheckPoint_Layer originalLayer, string newName) { CheckPoint_Layer curLayer = originalLayer; @@ -67,7 +72,7 @@ public static CheckPoint_Layer Optimize(CheckPoint_Layer originalLayer, string n return newLayer; } - + private static void AddRule(CheckPoint_Layer layer, CheckPoint_Rule newRule) { bool match = false; @@ -90,7 +95,7 @@ private static void AddRule(CheckPoint_Layer layer, CheckPoint_Rule newRule) { CheckPoint_Rule rule = newRule.Clone(); rule.Layer = layer.Name; - rule.Comments = ""; + rule.Comments = IsOptimizeByComments ? rule.Comments : ""; rule.ConversionComments = newRule.ConversionComments; layer.Rules.Add(rule); } @@ -131,7 +136,7 @@ private static CheckPoint_Rule MergeRules(CheckPoint_Rule rule1, CheckPoint_Rule mergedRule.Track = rule1.Track; mergedRule.SourceNegated = rule1.SourceNegated; mergedRule.DestinationNegated = rule1.DestinationNegated; - mergedRule.Comments = ""; + mergedRule.Comments = IsOptimizeByComments ? rule1.Comments : ""; // adding or not adding comments by the user request mergedRule.ConversionComments = rule1.ConversionComments + " | " + rule2.ConversionComments; mergedRule.ConvertedCommandId = rule1.ConvertedCommandId; mergedRule.ConversionIncidentType = ConversionIncidentType.None; @@ -178,9 +183,15 @@ private static int GetFirstRuleWithSameAction(CheckPoint_Layer layer, CheckPoint return (matchedRules == 0) ? -1 : (pos + 1); } - + private static bool IsRuleSimilarToRule(CheckPoint_Rule rule1, CheckPoint_Rule rule2) { + // Optimizing by comments - checks if comments of the two rules are matched and not empty + if (IsOptimizeByComments && rule1.Comments != rule2.Comments || IsOptimizeByComments && string.IsNullOrEmpty(rule1.Comments)) + { + return false; + } + if (rule1.Action != rule2.Action) { return false; @@ -276,7 +287,7 @@ private static string OptimizeConverstionComments(string commentToProcess) } } - else + else return commentToProcess.Trim(); } diff --git a/CiscoMigration/CiscoCommands.cs b/CiscoMigration/CiscoCommands.cs index 9096f28..e95b956 100644 --- a/CiscoMigration/CiscoCommands.cs +++ b/CiscoMigration/CiscoCommands.cs @@ -19,7 +19,9 @@ limitations under the License. using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; +using CheckPointObjects; using CommonUtils; +using MigrationBase; namespace CiscoMigration { @@ -124,7 +126,7 @@ public string FirstWord public ConversionIncidentType ConversionIncidentType { get; set; } public string ConversionIncidentMessage { get; set; } public List Children { get; set; } - + public CiscoCommand() { CiscoId = ""; @@ -2231,11 +2233,11 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti return; } - + if (prevAclCommand != null && ACLName.Equals(prevAclCommand.ACLName) && !string.IsNullOrEmpty(prevAclCommand.DataForNextElement)) { Remark = prevAclCommand.DataForNextElement; - + if (CiscoParser.SpreadAclRemarks) { DataForNextElement = Remark; diff --git a/CiscoMigration/CiscoConverter.cs b/CiscoMigration/CiscoConverter.cs index 4d8e766..67b2351 100644 --- a/CiscoMigration/CiscoConverter.cs +++ b/CiscoMigration/CiscoConverter.cs @@ -24,6 +24,7 @@ limitations under the License. using CheckPointObjects; using MigrationBase; using System.Globalization; +using System.Runtime.InteropServices; using System.Threading; using CiscoMigration.CiscoMigration; using static CheckPointObjects.CheckPoint_Rule; @@ -47,7 +48,7 @@ public class CiscoConverter : VendorConverter #region GUI params public bool SkipUnusedObjects { get; set; } //check if Optimized configuration is requested - + #endregion #region Helper Classes @@ -5737,7 +5738,7 @@ private void Add_Optimized_Package() foreach (CheckPoint_Layer layer in regularPackage.SubPolicies) { string optimizedSubPolicyName = layer.Name + "_opt"; - + CheckPoint_Layer optimizedLayer = RuleBaseOptimizer.Optimize(layer, optimizedSubPolicyName); foreach (CheckPoint_Rule subSubRule in optimizedLayer.Rules) { diff --git a/CiscoMigration/CiscoParser.cs b/CiscoMigration/CiscoParser.cs index 5b17172..4fc7109 100644 --- a/CiscoMigration/CiscoParser.cs +++ b/CiscoMigration/CiscoParser.cs @@ -35,6 +35,8 @@ public class CiscoParser : VendorParser //if we are using cisco code for fire power vendor we need set this flag to true value public bool isUsingForFirePower { get; set; } = false; + #region Private Members + #region Helper Classes private class Indentation @@ -51,14 +53,14 @@ public Indentation(int? id, int spaces) #endregion - #region Private Members + private IList _ciscoCommands = new List(); private Dictionary _ciscoIds = new Dictionary(); private Dictionary _ciscoAliases = new Dictionary(); public static bool SpreadAclRemarks = false; - + #endregion #region Public Methods diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index d110877..05b9e7d 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -13,6 +13,7 @@ using System.Text.RegularExpressions; using CommonUtils; using System.Threading; +using CheckPointObjects; namespace SmartMove { @@ -110,6 +111,7 @@ public bool IsAnalyze private bool _isInteractive = true; private bool _isCiscoSpreadAclRemarks = false; + private bool _isOptimizeByComments; #endregion public int DisplayHelp() @@ -129,6 +131,7 @@ public int DisplayHelp() Console.WriteLine("\t" + "-f | --format" + "\t\t" + "format of the output file (JSON[default], TEXT)"); Console.WriteLine("\t" + "-i | --interactive" + "\t" + @"-i false | -i true [default] Interactive mode provides a better user experience.Disable when automation is required[enabled by default]"); Console.WriteLine("\t" + "-a | --analyzer" + "\t\t" + @"mode for analyze package"); + Console.WriteLine("\t" + "-obc | --optimize-by-comments" + "\t" + @"(""-obc false"" | ""-obc true"" [default]) create optimized policy by comment and spread acl remarks - only for CiscoASA, FirePower"); Console.WriteLine(); Console.WriteLine("Example:"); Console.WriteLine("\t" + "SmartMove.exe –s \"D:\\SmartMove\\Content\\config.txt\" –v CiscoASA - t \"D:\\SmartMove\\Content\" –n true -k false -f json -a"); @@ -459,6 +462,23 @@ public CommandLine Parse(string[] args) this.isAnalyze = true; break; } + case "-obc": + case "--optimize-by-comments": // adding flag to optimize by comments option + { + if (args[i] == args.Last()) + { + _successCommands = false; + Console.WriteLine("Value for option --optimize-by-comments is not specified! ", MessageTypes.Error); + } + else if (bool.TryParse(args[i + 1].ToLower(), out _isOptimizeByComments)) + break; + else + { + _successCommands = false; + Console.WriteLine("Value for option format is not corrected! Allow only 'true' or 'false' ", MessageTypes.Error); + } + break; + } } } return this; @@ -533,10 +553,17 @@ public void DoAnalyze(CommandLine commandLine) switch (commandLine.Vendor) { case "CiscoASA": - CiscoParser.SpreadAclRemarks = _isCiscoSpreadAclRemarks; + CiscoParser.SpreadAclRemarks = _isOptimizeByComments; + RuleBaseOptimizer.IsOptimizeByComments = _isOptimizeByComments; + // verifying that the user or the default option won't reverse the flag to false if asking optimize by comments option + CiscoParser.SpreadAclRemarks = _isOptimizeByComments ? true : _isCiscoSpreadAclRemarks; vendorParser = new CiscoParser(); break; case "FirePower": + CiscoParser.SpreadAclRemarks = _isOptimizeByComments; + RuleBaseOptimizer.IsOptimizeByComments = _isOptimizeByComments; + // verifying that the user or the default option won't reverse the flag to false if asking optimize by comments option + CiscoParser.SpreadAclRemarks = _isOptimizeByComments ? true : _isCiscoSpreadAclRemarks; vendorParser = new CiscoParser() { isUsingForFirePower = true @@ -968,10 +995,15 @@ public void DoMigration(CommandLine commandLine) switch (commandLine.Vendor) { case "CiscoASA": - CiscoParser.SpreadAclRemarks = _isCiscoSpreadAclRemarks; + CiscoParser.SpreadAclRemarks = _isOptimizeByComments; + RuleBaseOptimizer.IsOptimizeByComments = _isOptimizeByComments; + CiscoParser.SpreadAclRemarks = _isOptimizeByComments ? true : _isCiscoSpreadAclRemarks; vendorParser = new CiscoParser(); break; case "FirePower": + CiscoParser.SpreadAclRemarks = _isOptimizeByComments; + RuleBaseOptimizer.IsOptimizeByComments = _isOptimizeByComments; + CiscoParser.SpreadAclRemarks = _isOptimizeByComments ? true : _isCiscoSpreadAclRemarks; vendorParser = new CiscoParser() { isUsingForFirePower = true diff --git a/SmartMove/MainWindow.xaml b/SmartMove/MainWindow.xaml index 3b19dfb..815799d 100644 --- a/SmartMove/MainWindow.xaml +++ b/SmartMove/MainWindow.xaml @@ -226,16 +226,23 @@ + - + + + +