Skip to content

Commit

Permalink
Merge pull request #97 from SivanShl/optimize_by_comments
Browse files Browse the repository at this point in the history
Adding the option to optimize by comments for Cisco and FirePower:
CheckPointObjects/RuleBaseOptimizer.cs 
            if (IsOptimizeByComments && rule1.Comments != rule2.Comments || IsOptimizeByComments && string.IsNullOrEmpty(rule1.Comments))
Logic:
        1. rules can be merged if they have the same comments
        2. both the source and destination columns match
         3. both the source and service columns match
        4.  both the destination and service columns match
Enabled by a checkbox
 a command line argument that default value false ( '-obc | --optimize-by-comments')
  • Loading branch information
chkp-ofirs committed Oct 20, 2022
2 parents d45323e + 9582ded commit 2e4d172
Show file tree
Hide file tree
Showing 8 changed files with 141 additions and 21 deletions.
29 changes: 21 additions & 8 deletions CheckPointObjects/RuleBaseOptimizer.cs
Expand Up @@ -15,12 +15,13 @@
limitations under the License.
********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using CommonUtils;

namespace CheckPointObjects
{
/// <summary>
Expand All @@ -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.
/// </summary>
public static class RuleBaseOptimizer
{

public static bool IsOptimizeByComments = false;
public static CheckPoint_Layer Optimize(CheckPoint_Layer originalLayer, string newName)
{
CheckPoint_Layer curLayer = originalLayer;
Expand Down Expand Up @@ -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;
Expand All @@ -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);
}
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -276,9 +287,11 @@ private static string OptimizeConverstionComments(string commentToProcess)
commentBuilder += ", " + comments_parts[i];
}

}
else
return commentToProcess.Trim();

}
else
return commentToProcess.Trim();

}

return commentBuilder == "Matched rule(s)" ? "" : commentBuilder;
Expand Down
8 changes: 5 additions & 3 deletions CiscoMigration/CiscoCommands.cs
Expand Up @@ -19,7 +19,9 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using CheckPointObjects;
using CommonUtils;
using MigrationBase;

namespace CiscoMigration
{
Expand Down Expand Up @@ -124,7 +126,7 @@ public string FirstWord
public ConversionIncidentType ConversionIncidentType { get; set; }
public string ConversionIncidentMessage { get; set; }
public List<CiscoCommand> Children { get; set; }

public CiscoCommand()
{
CiscoId = "";
Expand Down Expand Up @@ -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;
Expand Down
5 changes: 3 additions & 2 deletions CiscoMigration/CiscoConverter.cs
Expand Up @@ -24,6 +24,7 @@
using CheckPointObjects;
using MigrationBase;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using CiscoMigration.CiscoMigration;
using static CheckPointObjects.CheckPoint_Rule;
Expand All @@ -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
Expand Down Expand Up @@ -5738,7 +5739,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)
{
Expand Down
6 changes: 4 additions & 2 deletions CiscoMigration/CiscoParser.cs
Expand Up @@ -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
Expand All @@ -51,14 +53,14 @@ public Indentation(int? id, int spaces)

#endregion

#region Private Members


private IList<CiscoCommand> _ciscoCommands = new List<CiscoCommand>();
private Dictionary<string, CiscoCommand> _ciscoIds = new Dictionary<string, CiscoCommand>();
private Dictionary<string, string> _ciscoAliases = new Dictionary<string, string>();

public static bool SpreadAclRemarks = false;

#endregion

#region Public Methods
Expand Down
36 changes: 34 additions & 2 deletions SmartMove/CommandLine.cs
Expand Up @@ -13,6 +13,7 @@
using System.Text.RegularExpressions;
using CommonUtils;
using System.Threading;
using CheckPointObjects;

namespace SmartMove
{
Expand Down Expand Up @@ -110,6 +111,7 @@ public bool IsAnalyze
private bool _isInteractive = true;

private bool _isCiscoSpreadAclRemarks = false;
private bool _isOptimizeByComments;
#endregion

public int DisplayHelp()
Expand All @@ -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");
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
11 changes: 9 additions & 2 deletions SmartMove/MainWindow.xaml
Expand Up @@ -226,16 +226,23 @@
<CheckBox x:Name="SkipUnusedObjects" Grid.Row="13" Content="Do not import unused objects"
IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=SkipUnusedObjectsConversion, Mode=TwoWay}"
Margin="0,15,0,0" Background="Transparent" Focusable="False"/>
<CheckBox x:Name="OptimizeByComments" Grid.Row="14" Content="Optimize by comments"
IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=OptimizeByCommentsConversion, Mode=TwoWay}"
Margin="0,15,0,0" Background="Transparent" Focusable="False" Checked="OptimizeByComments_Checked" Unchecked="OptimizeByComments_Checked"/>
<CheckBox x:Name="CreateServiceGroupsConf" Grid.Row="14" Content="Import service groups"
IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=CreateServiceGroupsConfiguration, Mode=TwoWay}"
Margin="0,15,0,0" Background="Transparent" Focusable="False" Visibility="Collapsed"/>
<Grid Grid.Row="15" Margin="0,30,0,0" Background="Transparent" Focusable="False">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="8*"/>
<ColumnDefinition Width="8*"/>
<ColumnDefinition Width="84*"/>
<ColumnDefinition Width="401*"/>
</Grid.ColumnDefinitions>
<Button x:Name="Go" Style="{StaticResource GoButtonControlStyle}" HorizontalAlignment="Right"
Click="Go_OnClick"/>
Click="Go_OnClick" Grid.Column="3" Margin="0,0,-0.2,2.4"/>
</Grid>

</Grid>
</Grid>
<Grid x:Name="OutputPanel" Grid.Row="1" Background="Transparent" Focusable="False" Visibility="Collapsed">
Expand Down

0 comments on commit 2e4d172

Please sign in to comment.