From b4690aae6b9f4573fe6048dcb68abc867c59e6b5 Mon Sep 17 00:00:00 2001 From: AnastasiaIBA <67756010+AnastasiaIBA@users.noreply.github.com> Date: Fri, 3 Jul 2020 00:03:42 +0300 Subject: [PATCH 01/12] cherry-pick commit baaedb1e48f3f26da0494b08b5cff943b063cc57 from the repo chkp-yaelg/SmartMove --- SmartMove/CommandLine.cs | 48 ++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index 725ea214..1c51e945 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -132,30 +132,30 @@ public int CheckOptionsValidity(CommandLine commandLine) return 0; } if (!fullVendorsList.Contains(commandLine.Vendor)) - { - Console.WriteLine("Specified vendor \"" + commandLine.Vendor + "\" is not available.", MessageTypes.Error); + { + Console.WriteLine("Specified vendor \"" + commandLine.Vendor + "\" is not available.", MessageTypes.Error); Console.WriteLine("Available options are: CiscoASA, JuniperSRX, JuniperSSG, FortiNet, PaloAlto, Panorama", MessageTypes.Error); - Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); - return 0; - } + Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); + return 0; + } if (vendorsList1.Contains(commandLine.Vendor)) - { + { if (commandLine.ConvertUserConfiguration == true) - { - Console.WriteLine("Option -u is not valid for vendor " + commandLine.Vendor + "!"); - Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); + { + Console.WriteLine("Option -u is not valid for vendor " + commandLine.Vendor + "!"); + Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); return 0; } - + if (commandLine.DontImportUnusedObjects == true) - { - Console.WriteLine("Option -i is not valid for vendor " + commandLine.Vendor + "!"); - Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); + { + Console.WriteLine("Option -i is not valid for vendor " + commandLine.Vendor + "!"); + Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); return 0; - } - - } - if (vendorsList2.Contains(commandLine.Vendor)) + } + + } + if (vendorsList2.Contains(commandLine.Vendor)) { if (commandLine.ConvertUserConfiguration == true && commandLine.LdapAccountUnit == null) { @@ -163,7 +163,7 @@ public int CheckOptionsValidity(CommandLine commandLine) Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); return 0; } - + } if ((commandLine.vendor == "JuniperSRX" || commandLine.vendor == "PaloAlto") && !commandLine.configFileName.EndsWith(".xml")) { @@ -308,7 +308,7 @@ public CommandLine Parse(string[] args) public void DoMigration(CommandLine commandLine) { - string fileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName); + string fileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName); //Console.WriteLine("File name: " + fileName); if (string.IsNullOrEmpty(commandLine.ConfigFileName) || string.IsNullOrEmpty(fileName)) @@ -373,7 +373,7 @@ public void DoMigration(CommandLine commandLine) } else { - vendorParser.Parse(ciscoFile); + vendorParser.Parse(ciscoFile); } } catch (Exception ex) @@ -485,12 +485,12 @@ public void DoMigration(CommandLine commandLine) fgConverter.LDAPAccoutUnit = ldapAccountUnit; vendorConverter = fgConverter; break; - case "PaloAlto": + case "PaloAlto": PaloAltoConverter paConverter = new PaloAltoConverter(); paConverter.OptimizeConf = commandLine.DontImportUnusedObjects; paConverter.ConvertUserConf = commandLine.ConvertUserConfiguration; paConverter.LDAPAccoutUnit = ldapAccountUnit; - vendorConverter = paConverter; + vendorConverter = paConverter; break; case "Panorama": PanoramaConverter panoramaConverter = new PanoramaConverter(); @@ -513,7 +513,7 @@ public void DoMigration(CommandLine commandLine) } catch (Exception ex) { - + if (ex is InvalidDataException && ex.Message != null && ex.Message.Contains("Policy exceeds the maximum number")) { Console.WriteLine(String.Format("{1}{0}{2}{0}{3}", Environment.NewLine, "SmartMove is unable to convert the provided policy.", @@ -522,7 +522,7 @@ public void DoMigration(CommandLine commandLine) } else { - Console.WriteLine(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + Console.WriteLine(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); } return; } From ca520934ed4aa917cd028f3cff231fe21dd452b2 Mon Sep 17 00:00:00 2001 From: AnastasiaIBA <67756010+AnastasiaIBA@users.noreply.github.com> Date: Thu, 2 Jul 2020 23:58:04 +0300 Subject: [PATCH 02/12] cherry-pick the commit f5910e37c0a5f321cc04660fabf98dee00a034a4 from fork chkp-yaelg/SmartMove --- SmartMove/MainWindow.xaml.cs | 8 ++++++++ SmartMove/SmartMove.csproj | 5 ++++- SmartMove/packages.config | 4 ++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 SmartMove/packages.config diff --git a/SmartMove/MainWindow.xaml.cs b/SmartMove/MainWindow.xaml.cs index 95a741ca..595623ca 100644 --- a/SmartMove/MainWindow.xaml.cs +++ b/SmartMove/MainWindow.xaml.cs @@ -514,10 +514,12 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) if (string.IsNullOrEmpty(vendorParser.Version)) { ShowMessage("Unspecified ASA version.\nCannot find ASA version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + return; } else if (vendorParser.MajorVersion < 8 || (vendorParser.MajorVersion == 8 && vendorParser.MinorVersion < 3)) { ShowMessage("Unsupported ASA version (" + vendorParser.Version + ").\nThis tool supports ASA 8.3 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + return; } break; @@ -525,10 +527,12 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) if (string.IsNullOrEmpty(vendorParser.Version)) { ShowMessage("Unspecified SRX version.\nCannot find SRX version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + return; } else if (vendorParser.MajorVersion < 12 || (vendorParser.MajorVersion == 12 && vendorParser.MinorVersion < 1)) { ShowMessage("Unsupported SRX version (" + vendorParser.Version + ").\nThis tool supports SRX 12.1 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + return; } break; @@ -539,20 +543,24 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) if (string.IsNullOrEmpty(vendorParser.Version)) { ShowMessage("Unspecified FortiGate version.\nCannot find FortiGate version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + return; } else if(vendorParser.MajorVersion < 5) { ShowMessage("Unsupported FortiGate version (" + vendorParser.Version + ").\nThis tool supports FortiGate 5.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + return; } break; case Vendor.PaloAlto: if (string.IsNullOrEmpty(vendorParser.Version)) { ShowMessage("Unspecified PaloAlto version.\nCannot find PaloAlto PAN-OS version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + return; } else if (vendorParser.MajorVersion < 7) { ShowMessage("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto PAN-OS 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + return; } break; case Vendor.PaloAltoPanorama: diff --git a/SmartMove/SmartMove.csproj b/SmartMove/SmartMove.csproj index 8f88ad71..6d509ed2 100644 --- a/SmartMove/SmartMove.csproj +++ b/SmartMove/SmartMove.csproj @@ -68,7 +68,9 @@ - + + ..\packages\System.Windows.Interactivity.WPF.2.0.20525\lib\net40\System.Windows.Interactivity.dll + @@ -145,6 +147,7 @@ ResXFileCodeGenerator Resources.Designer.cs + SettingsSingleFileGenerator Settings.Designer.cs diff --git a/SmartMove/packages.config b/SmartMove/packages.config new file mode 100644 index 00000000..1f01b947 --- /dev/null +++ b/SmartMove/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file From 8f94dd64e65e1143fc60608e1f15d17abf9ee191 Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Tue, 8 Jun 2021 14:38:30 +0300 Subject: [PATCH 03/12] add duplicates for flags to console for source, target, vendor, nat, domain, ldap --- SmartMove/CommandLine.cs | 38 +++++++++++++++++++++++--------------- SmartMove/SmartMove.csproj | 6 ------ 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index 1c51e945..667ce8ee 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -94,15 +94,15 @@ public int DisplayHelp() { Console.WriteLine("SmartMove command usage:"); Console.WriteLine(); - Console.WriteLine("SmartMove.exe [–f config_file_name] [-v vendor] [-t target_folder] [-d domain] [-n] [-u LDAP_Account_unit] [-i]"); + Console.WriteLine("SmartMove.exe [–s config_file_name] [-v vendor] [-t target_folder] [-d domain] [-n] [-l LDAP_Account_unit] [-i]"); Console.WriteLine(); Console.WriteLine("Options:"); - Console.WriteLine("\t" + "-f" + "\t" + "full path to vendor configuration file"); - Console.WriteLine("\t" + "-v" + "\t" + "vendor for conversion (available options: CiscoASA, JuniperSRX, JuniperSSG, FortiNet, PaloAlto, Panorama)"); - Console.WriteLine("\t" + "-t" + "\t" + "migration output folder"); - Console.WriteLine("\t" + "-d" + "\t" + "domain name (for CiscoASA, JuniperSRX, JuniperSSG only)"); - Console.WriteLine("\t" + "-n" + "\t" + "convert NAT configuration"); - Console.WriteLine("\t" + "-u" + "\t" + "LDAP Account unit for convert user configuration option (for FortiNet, PaloAlto and Panorama only)"); + Console.WriteLine("\t" + "-s | --source" + "\t" + "full path to vendor configuration file"); + Console.WriteLine("\t" + "-v | --vendor" + "\t" + "vendor for conversion (available options: CiscoASA, JuniperSRX, JuniperSSG, FortiNet, PaloAlto, Panorama)"); + Console.WriteLine("\t" + "-t | --target" + "\t" + "migration output folder"); + Console.WriteLine("\t" + "-d | --domain" + "\t" + "domain name (for CiscoASA, JuniperSRX, JuniperSSG only)"); + Console.WriteLine("\t" + "-n | --nat" + "\t" + "convert NAT configuration"); + Console.WriteLine("\t" + "-l | --ldap" + "\t" + "LDAP Account unit for convert user configuration option (for FortiNet, PaloAlto and Panorama only)"); Console.WriteLine("\t" + "-i" + "\t" + "do not import unused objects (for FortiNet, PaloAlto and Panorama only)"); Console.WriteLine(); Console.WriteLine("Example:"); @@ -122,20 +122,20 @@ public int CheckOptionsValidity(CommandLine commandLine) if (String.IsNullOrEmpty(commandLine.Vendor)) { Console.WriteLine("Option -v is mandatory but not specified.", MessageTypes.Error); - Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } if (String.IsNullOrEmpty(commandLine.ConfigFileName)) { Console.WriteLine("Option -f is mandatory but not specified.", MessageTypes.Error); - Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } if (!fullVendorsList.Contains(commandLine.Vendor)) { Console.WriteLine("Specified vendor \"" + commandLine.Vendor + "\" is not available.", MessageTypes.Error); Console.WriteLine("Available options are: CiscoASA, JuniperSRX, JuniperSSG, FortiNet, PaloAlto, Panorama", MessageTypes.Error); - Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } if (vendorsList1.Contains(commandLine.Vendor)) @@ -143,14 +143,14 @@ public int CheckOptionsValidity(CommandLine commandLine) if (commandLine.ConvertUserConfiguration == true) { Console.WriteLine("Option -u is not valid for vendor " + commandLine.Vendor + "!"); - Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } if (commandLine.DontImportUnusedObjects == true) { Console.WriteLine("Option -i is not valid for vendor " + commandLine.Vendor + "!"); - Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } @@ -160,7 +160,7 @@ public int CheckOptionsValidity(CommandLine commandLine) if (commandLine.ConvertUserConfiguration == true && commandLine.LdapAccountUnit == null) { Console.WriteLine("Value for option -u is not specified!"); - Console.WriteLine("For command help run \"SmartMove.exe -help\"", MessageTypes.Error); + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } @@ -221,11 +221,14 @@ public string[] regenerateArgs(string commandLineString) */ public CommandLine Parse(string[] args) { + //set default values + for (int i = 0; i < args.Length; i++) { switch (args[i]) { - case "-f": + case "-s": + case "--source": { if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) { @@ -249,6 +252,7 @@ public CommandLine Parse(string[] args) break; } case "-v": + case "--vendor": { if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) this.vendor = args[i + 1]; @@ -257,6 +261,7 @@ public CommandLine Parse(string[] args) break; } case "-t": + case "--target": { if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) this.targetFolder = args[i + 1]; @@ -265,6 +270,7 @@ public CommandLine Parse(string[] args) break; } case "-d": + case "--domain": { if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) this.domain = args[i + 1]; @@ -273,11 +279,13 @@ public CommandLine Parse(string[] args) break; } case "-n": + case "--nat": { this.convertNat = true; break; } - case "-u": + case "-l": + case "--ldap": { if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) { diff --git a/SmartMove/SmartMove.csproj b/SmartMove/SmartMove.csproj index 6d509ed2..5c2b3e1f 100644 --- a/SmartMove/SmartMove.csproj +++ b/SmartMove/SmartMove.csproj @@ -59,12 +59,6 @@ ..\packages\System.Windows.Interactivity.WPF.2.0.20525\lib\net40\Microsoft.Expression.Interactions.dll - - ..\packages\Microsoft.Xaml.Behaviors.Wpf.1.1.19\lib\net45\Microsoft.Xaml.Behaviors.dll - - - ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll - From d4c77b1e6daadcebdf3b9d46573b3d91d57c1538 Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Tue, 8 Jun 2021 14:38:52 +0300 Subject: [PATCH 04/12] decorations for Command line (fix 5 spaces) --- SmartMove/CommandLine.cs | 149 ++++++++++++++++++++------------------- 1 file changed, 75 insertions(+), 74 deletions(-) diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index 667ce8ee..4f2adb03 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -18,7 +18,7 @@ namespace SmartMove /// Represents command line logic /// class CommandLine - { + { private string[] arguments { get; set; } public CommandLine(string[] args) @@ -34,7 +34,7 @@ public string ConfigFileName get { return configFileName; } set { configFileName = value; } } - + //–v CiscoASA private string vendor { get; set; } public string Vendor @@ -50,7 +50,7 @@ public string TargetFolder get { return targetFolder; } set { targetFolder = value; } } - + //-d domain private string domain { get; set; } public string Domain @@ -132,30 +132,30 @@ public int CheckOptionsValidity(CommandLine commandLine) return 0; } if (!fullVendorsList.Contains(commandLine.Vendor)) - { - Console.WriteLine("Specified vendor \"" + commandLine.Vendor + "\" is not available.", MessageTypes.Error); + { + Console.WriteLine("Specified vendor \"" + commandLine.Vendor + "\" is not available.", MessageTypes.Error); Console.WriteLine("Available options are: CiscoASA, JuniperSRX, JuniperSSG, FortiNet, PaloAlto, Panorama", MessageTypes.Error); - Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); - return 0; - } + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); + return 0; + } if (vendorsList1.Contains(commandLine.Vendor)) - { + { if (commandLine.ConvertUserConfiguration == true) - { - Console.WriteLine("Option -u is not valid for vendor " + commandLine.Vendor + "!"); - Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); + { + Console.WriteLine("Option -u is not valid for vendor " + commandLine.Vendor + "!"); + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } - + if (commandLine.DontImportUnusedObjects == true) - { - Console.WriteLine("Option -i is not valid for vendor " + commandLine.Vendor + "!"); - Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); + { + Console.WriteLine("Option -i is not valid for vendor " + commandLine.Vendor + "!"); + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; - } - - } - if (vendorsList2.Contains(commandLine.Vendor)) + } + + } + if (vendorsList2.Contains(commandLine.Vendor)) { if (commandLine.ConvertUserConfiguration == true && commandLine.LdapAccountUnit == null) { @@ -163,7 +163,7 @@ public int CheckOptionsValidity(CommandLine commandLine) Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } - + } if ((commandLine.vendor == "JuniperSRX" || commandLine.vendor == "PaloAlto") && !commandLine.configFileName.EndsWith(".xml")) { @@ -189,7 +189,7 @@ public int CheckOptionsValidity(CommandLine commandLine) public string[] regenerateArgs(string commandLineString) { String[] args = null; - + var parts = Regex.Matches(commandLineString, @"[\""].+?[\""]|[^ ]+") .Cast() .Select(m => m.Value) @@ -197,7 +197,7 @@ public string[] regenerateArgs(string commandLineString) parts.RemoveAt(0); string buf; - List finalArgs = new List (); + List finalArgs = new List(); foreach (var item in parts) { if (item.StartsWith("\"") && item.EndsWith("\"")) @@ -209,10 +209,10 @@ public string[] regenerateArgs(string commandLineString) { finalArgs.Add(item); } - + } - args = finalArgs.ToArray(); - + args = finalArgs.ToArray(); + return args; } @@ -220,34 +220,34 @@ public string[] regenerateArgs(string commandLineString) * Parses input options and writes its values to ComamndLine class fields */ public CommandLine Parse(string[] args) - { - //set default values + { - for (int i = 0; i < args.Length; i++) - { + for (int i = 0; i < args.Length; i++) + { switch (args[i]) { case "-s": case "--source": { if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) - { + { if (args[i + 1].IndexOf("\\") != -1) - { + { this.ConfigFileName = args[i + 1]; } else { this.configFileName = Directory.GetCurrentDirectory() + "\\" + args[i + 1]; - + } //set default velue of target folder to cofig file directory this.TargetFolder = this.ConfigFileName.Substring(0, this.ConfigFileName.LastIndexOf("\\")); - - } else + + } + else { Console.WriteLine("Value for mandatory option -f is not specified! ", MessageTypes.Error); - } + } break; } @@ -256,15 +256,15 @@ public CommandLine Parse(string[] args) { if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) this.vendor = args[i + 1]; - else - Console.WriteLine("Value for mandatory option -v is not specified! ", MessageTypes.Error); + else + Console.WriteLine("Value for mandatory option -v is not specified! ", MessageTypes.Error); break; } case "-t": case "--target": { if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) - this.targetFolder = args[i + 1]; + this.targetFolder = args[i + 1]; else Console.WriteLine("Value for target folder option -t is not specified. Default value will be set!", MessageTypes.Error); break; @@ -291,22 +291,23 @@ 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); } - + break; } case "-i": { this.dontImportUnusedObjects = true; break; - } - } - } - return this; + } + } + } + return this; } /* @@ -315,13 +316,13 @@ public CommandLine Parse(string[] args) */ public void DoMigration(CommandLine commandLine) { - - string fileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName); + + string fileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName); //Console.WriteLine("File name: " + fileName); - if (string.IsNullOrEmpty(commandLine.ConfigFileName) || string.IsNullOrEmpty(fileName)) + if (string.IsNullOrEmpty(commandLine.ConfigFileName) || string.IsNullOrEmpty(fileName)) { - Console.WriteLine("Configuration file is not selected.", MessageTypes.Error); + Console.WriteLine("Configuration file is not selected.", MessageTypes.Error); return; } @@ -336,7 +337,7 @@ public void DoMigration(CommandLine commandLine) Console.WriteLine("Configuration file name is restricted to 20 characters at most.", MessageTypes.Error); return; } - + if (!Directory.Exists(commandLine.TargetFolder)) { Console.WriteLine("Cannot find target folder for conversion output.", MessageTypes.Error); @@ -345,9 +346,9 @@ public void DoMigration(CommandLine commandLine) VendorParser vendorParser; - switch (commandLine.Vendor) + switch (commandLine.Vendor) { - case "CiscoASA": + case "CiscoASA": vendorParser = new CiscoParser(); break; case "JuniperSRX": @@ -359,8 +360,8 @@ public void DoMigration(CommandLine commandLine) case "FortiNet": vendorParser = new FortiGateParser(); break; - case "PaloAlto": - vendorParser = new PaloAltoParser(); + case "PaloAlto": + vendorParser = new PaloAltoParser(); break; case "Panorama": vendorParser = new PanoramaParser(); @@ -370,10 +371,10 @@ public void DoMigration(CommandLine commandLine) } try - { + { string ciscoFile = commandLine.ConfigFileName; Console.WriteLine("Parsing configuration file..."); - + if (commandLine.Vendor.Equals("Panorama")) { PanoramaParser panParser = (PanoramaParser)vendorParser; @@ -381,11 +382,11 @@ public void DoMigration(CommandLine commandLine) } else { - vendorParser.Parse(ciscoFile); + vendorParser.Parse(ciscoFile); } } catch (Exception ex) - { + { Console.WriteLine(string.Format("Could not parse configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); return; } @@ -461,23 +462,23 @@ public void DoMigration(CommandLine commandLine) } #endregion - string vendorFileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName); + string vendorFileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName); string toolVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); - - string targetFolder = commandLine.TargetFolder + "\\"; + + string targetFolder = commandLine.TargetFolder + "\\"; bool convertNat = commandLine.ConvertNat; - + string ldapAccountUnit = commandLine.LdapAccountUnit; - + vendorParser.Export(targetFolder + vendorFileName + ".json"); VendorConverter vendorConverter; switch (commandLine.Vendor) { - case "CiscoASA": + case "CiscoASA": vendorConverter = new CiscoConverter(); break; case "JuniperSRX": @@ -493,7 +494,7 @@ public void DoMigration(CommandLine commandLine) fgConverter.LDAPAccoutUnit = ldapAccountUnit; vendorConverter = fgConverter; break; - case "PaloAlto": + case "PaloAlto": PaloAltoConverter paConverter = new PaloAltoConverter(); paConverter.OptimizeConf = commandLine.DontImportUnusedObjects; paConverter.ConvertUserConf = commandLine.ConvertUserConfiguration; @@ -512,7 +513,7 @@ public void DoMigration(CommandLine commandLine) } vendorConverter.Initialize(vendorParser, commandLine.ConfigFileName, toolVersion, targetFolder, commandLine.Domain); - + try { Console.WriteLine("Conversion is in progress..."); @@ -521,7 +522,7 @@ public void DoMigration(CommandLine commandLine) } catch (Exception ex) { - + if (ex is InvalidDataException && ex.Message != null && ex.Message.Contains("Policy exceeds the maximum number")) { Console.WriteLine(String.Format("{1}{0}{2}{0}{3}", Environment.NewLine, "SmartMove is unable to convert the provided policy.", @@ -530,17 +531,17 @@ public void DoMigration(CommandLine commandLine) } else { - Console.WriteLine(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + Console.WriteLine(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); } return; - } - - vendorConverter.ExportConfigurationAsHtml(); - vendorConverter.ExportPolicyPackagesAsHtml(); + } + + vendorConverter.ExportConfigurationAsHtml(); + vendorConverter.ExportPolicyPackagesAsHtml(); if (commandLine.ConvertNat) { - vendorConverter.ExportNatLayerAsHtml(); - } + vendorConverter.ExportNatLayerAsHtml(); + } } } } From 0583f8479ac589bcec2b8f34439d6dc7fb0c5bee Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Fri, 11 Jun 2021 12:10:44 +0300 Subject: [PATCH 05/12] * changed help page for console * added results of conversion to the console * from the console ldap flag now by default is empty string for disabling null reference exception during parsing (by the example of UI code) --- CiscoMigration/CiscoConverter.cs | 14 +- FortinetMigration/FortiGateConverter.cs | 53 +++++--- JuniperMigration/JuniperConverter.cs | 11 +- MigrationBase/VendorConverter.cs | 6 +- NetScreenMigration/ScreenOSConverter.cs | 22 +++- PaloAltoMigration/PaloAltoConverter.cs | 11 +- PaloAltoMigration/PanoramaConverter.cs | 11 +- SmartMove/CommandLine.cs | 167 +++++++++++++++++++----- SmartMove/MainWindow.xaml.cs | 3 +- SmartMove/Program.cs | 2 +- 10 files changed, 227 insertions(+), 73 deletions(-) diff --git a/CiscoMigration/CiscoConverter.cs b/CiscoMigration/CiscoConverter.cs index 00b23789..d1e22518 100644 --- a/CiscoMigration/CiscoConverter.cs +++ b/CiscoMigration/CiscoConverter.cs @@ -522,6 +522,7 @@ private static void GetServicePortRanges(string servicePort, out int from, out i private IList _ciscoSshCommands; private Cisco_Hostname _ciscoHostnameCommand; private List _ciscoGlobalAclCommands = new List(); + private string _outputFormat; private List _cpPreorderedNatRules = new List(); @@ -4522,10 +4523,7 @@ private bool IsFirewallRuleMatchedByNATRule(CheckPoint_Zone parentLayerRuleZone, return true; } - if (fwRule.Service.Count == 0) - { - // TODO: ??? - } + 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... @@ -4683,18 +4681,19 @@ private string BuildInspectedRuleLinkTag(string ciscoClassMapName) #region Public Methods - public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName) + public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName, string outputFormat = "json") { _ciscoParser = (CiscoParser)vendorParser; if (_ciscoParser == null) { throw new InvalidDataException("Unexpected!!!"); } + this._outputFormat = outputFormat; - base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName); + base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName, outputFormat); } - public override void Convert(bool convertNat) + public override Dictionary Convert(bool convertNat) { RaiseConversionProgress(20, "Converting obects ..."); _cpObjects.Initialize(); // must be first!!! @@ -4748,6 +4747,7 @@ public override void Convert(bool convertNat) ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); CreateSmartConnector(); + return new Dictionary() { { "warnings", ConversionIncidentCategoriesCount } }; } public override int RulesInConvertedPackage() diff --git a/FortinetMigration/FortiGateConverter.cs b/FortinetMigration/FortiGateConverter.cs index 83de468f..53323429 100644 --- a/FortinetMigration/FortiGateConverter.cs +++ b/FortinetMigration/FortiGateConverter.cs @@ -19,6 +19,7 @@ public class FortiGateConverter : VendorConverter public bool OptimizeConf { get; set; } //check if Optimized configuration is requested public bool ConvertUserConf { get; set; } //check if User converion is requested public string LDAPAccoutUnit { get; set; } //read LDAP Account Unit Name for gethering users + public string OutputFormat { get; set; } //json or text format for output file #endregion @@ -31,7 +32,7 @@ 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 Dictionary> _localMapperFgCp = new Dictionary>(); //storing map of FG names to CheckPoint objects + private Dictionary> _localMapperFgCp = new Dictionary>(); //storing map of FG names to CheckPoint objects private Dictionary> _interfacesMapperFgCp = new Dictionary>(); //storing information about interfaces @@ -83,14 +84,15 @@ public class FortiGateConverter : VendorConverter #endregion //Initialization method... stupid method because you must to initialize CheckPoint Objects Store in convert. (from Cisco converter) - public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName) + public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName, string outputFormat = "json") { _fortiGateParser = (FortiGateParser)vendorParser; if (_fortiGateParser == null) { throw new InvalidDataException("Unexpected!!!"); } - base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName); + OutputFormat = outputFormat; + base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName, outputFormat); } protected override bool AddCheckPointObject(CheckPointObject cpObject) @@ -477,7 +479,7 @@ public string BuildInspectedRuleInfo(string fortiClassMapName) public void CreateCatalogObjects() { string filename = this.ObjectsHtmlFile; - + using (var file = new StreamWriter(filename, false)) { file.WriteLine(""); @@ -624,10 +626,11 @@ public void CreateCatalogWarnings() } //report about Errors - public void CreateErrorsHtml(string vDomName) + public void CreateErrorsReport(string vDomName) { if (_errorsList.Count > 0) { + // if (OutputFormat == "text") { string filename = _targetFolder + "//" + vDomName + "_errors.html"; using (var file = new StreamWriter(filename, false)) @@ -653,11 +656,27 @@ public void CreateErrorsHtml(string vDomName) file.WriteLine(""); file.WriteLine(""); } + /*}else + { + string filename = _targetFolder + "//" + vDomName + "_errors.json"; + + using (var file = new StreamWriter(filename, false)) + { + FgJsonOutputReportsList fgJsonOutput = new FgJsonOutputReportsList(); + fgJsonOutput.header = vDomName; + for (int i = 0; i < _errorsList.Count; i++) + { + fgJsonOutput.reports.Add(i, _errorsList[i]); + } + file.WriteLine(JsonConvert.SerializeObject(fgJsonOutput, Formatting.Indented)); + } + + }*/ } } //report about Warnings - public void CreateWarningsHtml(string vDomName) + public void CreateWarningsReport(string vDomName) { if (_errorsList.Count > 0) { @@ -694,7 +713,7 @@ public void CreateWarningsHtml(string vDomName) #region Converter //MAIN method to convert configuration file. - public override void Convert(bool convertNat) + public override Dictionary Convert(bool convertNat) { string targetFileNameMain = _vendorFileName; string targetFolderMain = _targetFolder; @@ -732,9 +751,11 @@ public override void Convert(bool convertNat) } VendorHtmlFile = _vendorFilePath; - + ObjectsScriptFile = _targetFolder; PolicyScriptFile = _targetFolder; + + return new Dictionary() { { "errors", ErrorsInConvertedPackage() }, { "warnings", WarningsInConvertedPackage() } }; } //Convertint VDOMs to each VDOM and then Convert each VDOM as simple Configuration @@ -890,7 +911,7 @@ public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List { FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommand; - if(fgCommandConfig.ObjectName.Equals("firewall address")) + if (fgCommandConfig.ObjectName.Equals("firewall address")) { Add_ConfigFirewallAddress(fgCommandConfig.SubCommandsList); } @@ -898,7 +919,7 @@ public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List { AddFirewallVip(fgCommandConfig.SubCommandsList); } - else if(fgCommandConfig.ObjectName.Equals("firewall vipgrp")) + else if (fgCommandConfig.ObjectName.Equals("firewall vipgrp")) { AddFirewallVipGroups(fgCommandConfig.SubCommandsList); } @@ -934,11 +955,11 @@ public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List { AddSystemZone(fgCommandConfig.SubCommandsList); } - else if(fgCommandConfig.ObjectName.Equals("router static")) + else if (fgCommandConfig.ObjectName.Equals("router static")) { AddRoutesStatic(fgCommandConfig.SubCommandsList); } - else if(fgCommandConfig.ObjectName.Equals("router rip")) + else if (fgCommandConfig.ObjectName.Equals("router rip")) { CheckDynamicRoutesRip(fgCommandConfig.SubCommandsList); } @@ -1000,15 +1021,15 @@ public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List CreatePackagesScript(); - CreateErrorsHtml(targetFileNameNew); - CreateWarningsHtml(targetFileNameNew); + CreateErrorsReport(targetFileNameNew); + CreateWarningsReport(targetFileNameNew); ExportNatLayerAsHtml(); ExportPolicyPackagesAsHtmlConfig(); _warningsConvertedPackage = _warningsList.Count; _errorsConvertedPackage = _errorsList.Count; - + CreateSmartConnector(); // to clean; must be the last!!! @@ -1038,7 +1059,7 @@ public void CleanSavedData() public void AddRoutesStatic(List fgCommandsList) { - foreach(FgCommand fgCommandE in fgCommandsList) + foreach (FgCommand fgCommandE in fgCommandsList) { FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; diff --git a/JuniperMigration/JuniperConverter.cs b/JuniperMigration/JuniperConverter.cs index 18bd99d8..c6c6d477 100644 --- a/JuniperMigration/JuniperConverter.cs +++ b/JuniperMigration/JuniperConverter.cs @@ -169,6 +169,7 @@ public enum RulePriority private List _cpNetworkObjectsInMultipleZones = new List(); private List _cpPreorderedNatRules = new List(); private Dictionary> _natMatchedFirewallRules = new Dictionary>(); + private string _outputFormat; private IEnumerable _juniperZones; public IEnumerable JuniperZones @@ -3735,18 +3736,19 @@ protected override string GetVendorName() #region Public Methods - public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName) + public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName, string outputFormat = "json") { _juniperParser = (JuniperParser)vendorParser; if (_juniperParser == null) { throw new InvalidDataException("Unexpected!!!"); } + _outputFormat = outputFormat; - base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName); + base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName, outputFormat); } - public override void Convert(bool convertNat) + public override Dictionary Convert(bool convertNat) { RaiseConversionProgress(20, "Converting obects ..."); _cpObjects.Initialize(); // must be first!!! @@ -3797,8 +3799,9 @@ public override void Convert(bool convertNat) ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); CreateSmartConnector(); + return new Dictionary() { { "warnings", ConversionIncidentCategoriesCount } }; } - + public override int RulesInConvertedPackage() { return _cpPackages[0].TotalRules(); diff --git a/MigrationBase/VendorConverter.cs b/MigrationBase/VendorConverter.cs index 5d6b6601..3df79ec8 100644 --- a/MigrationBase/VendorConverter.cs +++ b/MigrationBase/VendorConverter.cs @@ -66,6 +66,7 @@ public abstract class VendorConverter protected string _domainName; protected string _policyPackageName; protected string _policyPackageOptimizedName; + protected string _outputFormat; //txt or json protected bool _hasNATConversionIncident = false; protected CheckPointObjectsRepository _cpObjects = new CheckPointObjectsRepository(); @@ -133,12 +134,13 @@ protected void RaiseConversionProgress(int progress, string title) #region Methods - public virtual void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName) + public virtual void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName, string outputFormat) { _vendorFilePath = vendorFilePath; _toolVersion = toolVersion; _targetFolder = targetFolder; _domainName = domainName; + _outputFormat = outputFormat; _vendorFileName = Path.GetFileNameWithoutExtension(vendorFilePath); _vendorFileName = !string.IsNullOrEmpty(_vendorFileName) ? Regex.Replace(_vendorFileName, @"\s+", "_") : ""; @@ -217,7 +219,7 @@ public void CleanCheckPointObjectsLists() #region Abstract - public abstract void Convert(bool convertNat); + public abstract Dictionary Convert(bool convertNat); public abstract int RulesInConvertedPackage(); public abstract int RulesInConvertedOptimizedPackage(); public abstract int RulesInNatLayer(); diff --git a/NetScreenMigration/ScreenOSConverter.cs b/NetScreenMigration/ScreenOSConverter.cs index d30cc12b..86e1e5d8 100644 --- a/NetScreenMigration/ScreenOSConverter.cs +++ b/NetScreenMigration/ScreenOSConverter.cs @@ -669,6 +669,19 @@ private List PolicySimplifiedList } } + private string _outputFormat { get; set; } + private string OutputFormat { + get + { + return _outputFormat; + } + set + { + _outputFormat = value; + } + } + + protected override string GetVendorName() { return Vendor.JuniperScreenOS.ToString(); @@ -3514,18 +3527,18 @@ private void Add_NatPolicy2RegularPolicy() #region Public Methods - public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName) + public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName, string outputFormat = "json") { _screenOSParser = (ScreenOSParser)vendorParser; if (_screenOSParser == null) { throw new InvalidDataException("Unexpected!!!"); } - - base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName); + OutputFormat = outputFormat; + base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName, outputFormat); } - public override void Convert(bool convertNat = false) + public override Dictionary Convert(bool convertNat = false) { RaiseConversionProgress(20, "Converting obects ..."); _cpObjects.Initialize(); // must be first!!! @@ -3582,6 +3595,7 @@ public override void Convert(bool convertNat = false) ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); CreateSmartConnector(); + return new Dictionary() { { "warnings", ConversionIncidentCategoriesCount } }; } public override int RulesInConvertedPackage() diff --git a/PaloAltoMigration/PaloAltoConverter.cs b/PaloAltoMigration/PaloAltoConverter.cs index e1bb6e4e..61e6a8ba 100644 --- a/PaloAltoMigration/PaloAltoConverter.cs +++ b/PaloAltoMigration/PaloAltoConverter.cs @@ -46,6 +46,8 @@ public class PaloAltoConverter : VendorConverter private Dictionary cpPredefServicesTypes = new Dictionary(); + private string outputFormat = ""; + #endregion #region Constants @@ -731,14 +733,15 @@ public void CreateWarningsHtml(string vsysName) #region Converter - public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName) + public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName, string outputFormat = "json") { _paParser = (PaloAltoParser)vendorParser; if (_paParser == null) { throw new InvalidDataException("Unexpected!!!"); } - base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName); + this.outputFormat = outputFormat; + base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName, outputFormat); } protected override bool AddCheckPointObject(CheckPointObject cpObject) @@ -759,7 +762,7 @@ protected override bool AddCheckPointObject(CheckPointObject cpObject) return false; } - public override void Convert(bool convertNat) + public override Dictionary Convert(bool convertNat) { string targetFileNameMain = _vendorFileName; string targetFolderMain = _targetFolder; @@ -884,6 +887,8 @@ public override void Convert(bool convertNat) ObjectsScriptFile = _targetFolder; PolicyScriptFile = _targetFolder; + + return new Dictionary() { { "errors", ErrorsInConvertedPackage() }, { "warnings", WarningsInConvertedPackage() } }; } public void ConvertPaVsysEntry(string targetFolderNew, string targetFileNameNew, PA_VsysEntry paVsysEntry, diff --git a/PaloAltoMigration/PanoramaConverter.cs b/PaloAltoMigration/PanoramaConverter.cs index 3010ec75..82ef6039 100644 --- a/PaloAltoMigration/PanoramaConverter.cs +++ b/PaloAltoMigration/PanoramaConverter.cs @@ -50,6 +50,8 @@ public class PanoramaConverter : VendorConverter private Dictionary cpPredefServicesTypes = new Dictionary(); + private string outputFormat = ""; + #endregion #region Constants @@ -745,14 +747,15 @@ public void CreateWarningsHtml(string deviceGroupName) #region Converter - public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName) + public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName, string outputFormat = "json") { _paParser = (PanoramaParser)vendorParser; if (_paParser == null) { throw new InvalidDataException("Unexpected!!!"); } - base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName); + this.outputFormat = outputFormat; + base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName, outputFormat); } protected override bool AddCheckPointObject(CheckPointObject cpObject) @@ -848,7 +851,7 @@ public Dictionary> getZones(Panorama_Config paConfig) return devgroupZoneDictionary; } - public override void Convert(bool convertNat) + public override Dictionary Convert(bool convertNat) { string targetFileNameMain = _vendorFileName; string targetFolderMain = _targetFolder; @@ -1036,6 +1039,8 @@ public override void Convert(bool convertNat) ObjectsScriptFile = _targetFolder; PolicyScriptFile = _targetFolder; + + return new Dictionary() { { "errors", ErrorsInConvertedPackage() }, { "warnings", WarningsInConvertedPackage() } }; } /// diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index 4f2adb03..da8cc4a4 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -67,7 +67,7 @@ public bool ConvertNat set { convertNat = value; } } - //-u unit1 + //-l unit1 private string ldapAccountUnit { get; set; } public string LdapAccountUnit { @@ -81,32 +81,40 @@ public bool ConvertUserConfiguration get { return convertUserConfiguration; } set { convertUserConfiguration = value; } } - //-i + //-k private bool dontImportUnusedObjects { get; set; } public bool DontImportUnusedObjects { get { return dontImportUnusedObjects; } set { dontImportUnusedObjects = value; } } + //-f + private string formatOutput { get; set; } + public string FormatOutput + { + get { return formatOutput; } + set { formatOutput = value; } + } #endregion public int DisplayHelp() { Console.WriteLine("SmartMove command usage:"); Console.WriteLine(); - Console.WriteLine("SmartMove.exe [–s config_file_name] [-v vendor] [-t target_folder] [-d domain] [-n] [-l LDAP_Account_unit] [-i]"); + Console.WriteLine("SmartMove.exe [–s config_file_name] [-v vendor] [-t target_folder] [-d domain] [-n] [-l LDAP_Account_unit] [-k]"); Console.WriteLine(); Console.WriteLine("Options:"); - Console.WriteLine("\t" + "-s | --source" + "\t" + "full path to vendor configuration file"); + Console.WriteLine("\t" + "-s | --source" + "\t" + "full path to the vendor configuration file"); Console.WriteLine("\t" + "-v | --vendor" + "\t" + "vendor for conversion (available options: CiscoASA, JuniperSRX, JuniperSSG, FortiNet, PaloAlto, Panorama)"); Console.WriteLine("\t" + "-t | --target" + "\t" + "migration output folder"); Console.WriteLine("\t" + "-d | --domain" + "\t" + "domain name (for CiscoASA, JuniperSRX, JuniperSSG only)"); - Console.WriteLine("\t" + "-n | --nat" + "\t" + "convert NAT configuration"); + Console.WriteLine("\t" + "-n | --nat" + "\t" + @"(""-n false"" |"" -n true"" [default]) convert NAT configuration [enabled by default]"); Console.WriteLine("\t" + "-l | --ldap" + "\t" + "LDAP Account unit for convert user configuration option (for FortiNet, PaloAlto and Panorama only)"); - Console.WriteLine("\t" + "-i" + "\t" + "do not import unused objects (for FortiNet, PaloAlto and Panorama only)"); + Console.WriteLine("\t" + "-k | --skip" + "\t" + @"(""-k false"" |"" -k true"" [default]) do not import unused objects (for FortiNet, PaloAlto and Panorama only) [enabled by default]"); + Console.WriteLine("\t" + "-f | --format" + "\t" + "format of the output file (JSON[default], TEXT)"); Console.WriteLine(); Console.WriteLine("Example:"); - Console.WriteLine("\t" + "SmartMove.exe –f \"D:\\SmartMove\\Content\\config.txt\" –v CiscoASA - t \"D:\\SmartMove\\Content\" –n"); + Console.WriteLine("\t" + "SmartMove.exe –s \"D:\\SmartMove\\Content\\config.txt\" –v CiscoASA - t \"D:\\SmartMove\\Content\" –n true -k false -f json"); return 0; } @@ -149,7 +157,7 @@ public int CheckOptionsValidity(CommandLine commandLine) if (commandLine.DontImportUnusedObjects == true) { - Console.WriteLine("Option -i is not valid for vendor " + commandLine.Vendor + "!"); + Console.WriteLine("Option -k is not valid for vendor " + commandLine.Vendor + "!"); Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } @@ -221,6 +229,11 @@ public string[] regenerateArgs(string commandLineString) */ public CommandLine Parse(string[] args) { + //set default values + ConvertNat = true; + FormatOutput = "json"; + //not default value, just for disabling null reference exception during conversion + LdapAccountUnit = string.Empty; for (int i = 0; i < args.Length; i++) { @@ -246,7 +259,7 @@ public CommandLine Parse(string[] args) } else { - Console.WriteLine("Value for mandatory option -f is not specified! ", MessageTypes.Error); + Console.WriteLine("Value for mandatory option -s is not specified! ", MessageTypes.Error); } break; @@ -300,11 +313,21 @@ public CommandLine Parse(string[] args) break; } - case "-i": + case "-k": + case "--skip": { this.dontImportUnusedObjects = true; break; } + case "-f": + case "--format": + { + if (new List() { "text", "json" }.Contains(args[i+1].ToLower())) + FormatOutput = args[i+1]; + else + Console.WriteLine("Value for option format is not corrected! Allow only 'text' or 'json' ", MessageTypes.Error); + break; + } } } return this; @@ -322,25 +345,41 @@ public void DoMigration(CommandLine commandLine) if (string.IsNullOrEmpty(commandLine.ConfigFileName) || string.IsNullOrEmpty(fileName)) { - Console.WriteLine("Configuration file is not selected.", MessageTypes.Error); + if (FormatOutput == "text") + Console.WriteLine("Configuration file is not selected.", MessageTypes.Error); + else + //TODO: json + Console.WriteLine(JsonConvert.SerializeObject(new A())); return; } if (!File.Exists(commandLine.ConfigFileName)) { - Console.WriteLine("Cannot find configuration file.", MessageTypes.Error); + if (FormatOutput == "text") + Console.WriteLine("Cannot find configuration file.", MessageTypes.Error); + else + //TODO: json + Console.WriteLine("{\n msg: Cannot find configuration file.\n error: generic_err_object_not_found\n}"); return; } if (fileName.Length > 20) { - Console.WriteLine("Configuration file name is restricted to 20 characters at most.", MessageTypes.Error); + if (FormatOutput == "text") + Console.WriteLine("Configuration file name is restricted to 20 characters at most.", MessageTypes.Error); + else + //TODO: json + Console.WriteLine("{\n msg: Configuration file name is restricted to 20 characters at most.\n error: err_validation_failed\n}"); return; } if (!Directory.Exists(commandLine.TargetFolder)) { - Console.WriteLine("Cannot find target folder for conversion output.", MessageTypes.Error); + if (FormatOutput == "text") + Console.WriteLine("Cannot find target folder for conversion output.", MessageTypes.Error); + else + //TODO: json + Console.WriteLine("{\n msg: Cannot find target folder for conversion output.\n error: generic_err_object_not_found\n}"); return; } @@ -387,8 +426,17 @@ public void DoMigration(CommandLine commandLine) } catch (Exception ex) { - Console.WriteLine(string.Format("Could not parse configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); - return; + if (FormatOutput == "text") + { + Console.WriteLine(string.Format("Could not parse configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + return; + } + else + { + //TODO: json + Console.WriteLine("{\n msg: \t Could not parse configuration file.\n error: err_cannot_convert_configuration_file\n}"); + return; + } } #region check middleware version @@ -397,12 +445,20 @@ public void DoMigration(CommandLine commandLine) case "CiscoASA": if (string.IsNullOrEmpty(vendorParser.Version)) { - Console.WriteLine("Unspecified ASA version.\nCannot find ASA version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unspecified ASA version.\nCannot find ASA version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unspecified ASA version.\nCannot find ASA version for the selected configuration.\nThe configuration may not parse correctly.\n}"); return; } else if (vendorParser.MajorVersion < 8 || (vendorParser.MajorVersion == 8 && vendorParser.MinorVersion < 3)) { - Console.WriteLine("Unsupported ASA version (" + vendorParser.Version + ").\nThis tool supports ASA 8.3 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unsupported ASA version (" + vendorParser.Version + "). This tool supports ASA 8.3 and above configuration files. The configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unsupported ASA version (" + vendorParser.Version + "). This tool supports ASA 8.3 and above configuration files. The configuration may not parse correctly.\n}"); return; } break; @@ -410,12 +466,20 @@ public void DoMigration(CommandLine commandLine) case "JuniperSRX": if (string.IsNullOrEmpty(vendorParser.Version)) { - Console.WriteLine("Unspecified SRX version.\nCannot find SRX version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unspecified SRX version.\nCannot find SRX version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unspecified SRX version. Cannot find SRX version for the selected configuration. The configuration may not parse correctly.\n}"); return; } else if (vendorParser.MajorVersion < 12 || (vendorParser.MajorVersion == 12 && vendorParser.MinorVersion < 1)) { - Console.WriteLine("Unsupported SRX version (" + vendorParser.Version + ").\nThis tool supports SRX 12.1 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unsupported SRX version (" + vendorParser.Version + ").\nThis tool supports SRX 12.1 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unsupported SRX version (" + vendorParser.Version + "). This tool supports SRX 12.1 and above configuration files. The configuration may not parse correctly.\n}"); return; } break; @@ -426,36 +490,60 @@ public void DoMigration(CommandLine commandLine) case "FortiNet": if (string.IsNullOrEmpty(vendorParser.Version)) { - Console.WriteLine("Unspecified FortiGate version.\nCannot find FortiGate version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unspecified FortiGate version.\nCannot find FortiGate version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unspecified FortiGate version. Cannot find FortiGate version for the selected configuration. The configuration may not parse correctly.\n}"); return; } else if (vendorParser.MajorVersion < 5) { - Console.WriteLine("Unsupported FortiGate version (" + vendorParser.Version + ").\nThis tool supports FortiGate 5.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unsupported FortiGate version (" + vendorParser.Version + ").\nThis tool supports FortiGate 5.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unsupported FortiGate version (" + vendorParser.Version + "). This tool supports FortiGate 5.x and above configuration files. The configuration may not parse correctly.\n}"); return; } break; case "PaloAlto": if (string.IsNullOrEmpty(vendorParser.Version)) { - Console.WriteLine("Unspecified PaloAlto version.\nCannot find PaloAlto PAN-OS version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unspecified PaloAlto version.\nCannot find PaloAlto PAN-OS version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unspecified PaloAlto version. Cannot find PaloAlto PAN-OS version for the selected configuration. The configuration may not parse correctly.\n}"); return; } else if (vendorParser.MajorVersion < 7) { - Console.WriteLine("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto PAN-OS 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto PAN-OS 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto PAN-OS 7.x and above configuration files. The configuration may not parse correctly.\n}"); return; } break; case "Panorama": if (string.IsNullOrEmpty(vendorParser.Version)) { - Console.WriteLine("Unspecified PaloAlto Panorama version.\nCannot find PaloAlto Panorama version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unspecified PaloAlto Panorama version.\nCannot find PaloAlto Panorama version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unspecified PaloAlto Panorama version. Cannot find PaloAlto Panorama version for the selected configuration. The configuration may not parse correctly.\n}"); return; } else if (vendorParser.MajorVersion < 7) { - Console.WriteLine("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto Panorama 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + if (FormatOutput == "text") + Console.WriteLine("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto Panorama 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + else + //TODO: json + Console.WriteLine("{\n warning: Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto Panorama 7.x and above configuration files. The configuration may not parse correctly.\n}"); return; } break; @@ -512,26 +600,41 @@ public void DoMigration(CommandLine commandLine) throw new InvalidDataException("Unexpected!!!"); } - vendorConverter.Initialize(vendorParser, commandLine.ConfigFileName, toolVersion, targetFolder, commandLine.Domain); + vendorConverter.Initialize(vendorParser, commandLine.ConfigFileName, toolVersion, targetFolder, commandLine.Domain, commandLine.formatOutput); try { Console.WriteLine("Conversion is in progress..."); - vendorConverter.Convert(convertNat); + Dictionary results = vendorConverter.Convert(convertNat); Console.WriteLine("Conversion is finished."); + if (results.ContainsKey("errors")) + Console.WriteLine("Errors: {0}", results["errors"]); + if (results.ContainsKey("warnings")) + Console.WriteLine("Warnings: {0}", results["warnings"]); + //TODO: json + } catch (Exception ex) { if (ex is InvalidDataException && ex.Message != null && ex.Message.Contains("Policy exceeds the maximum number")) { - Console.WriteLine(String.Format("{1}{0}{2}{0}{3}", Environment.NewLine, "SmartMove is unable to convert 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 ps@checkpoint.com")); + if (FormatOutput == "text") + { + Console.WriteLine(String.Format("{1}{0}{2}{0}{3}", Environment.NewLine, "SmartMove is unable to convert 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 ps@checkpoint.com")); + } + else + //TODO: json + Console.WriteLine(String.Format("{\n msg: {0}\n error: {1}\n}", Environment.NewLine, "SmartMove is unable to convert the provided policy. Reason: Policy exceeds the maximum number of supported policy layers.", "generic_error")); } else { - Console.WriteLine(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + if (FormatOutput == "text") + Console.WriteLine(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + /*else + Console.WriteLine(string.Format("{\n msg: {0}\n error: {1}\n}", Environment.NewLine, "Could not convert configuration file.", "generic_error"));*/ } return; } diff --git a/SmartMove/MainWindow.xaml.cs b/SmartMove/MainWindow.xaml.cs index 595623ca..db11e3be 100644 --- a/SmartMove/MainWindow.xaml.cs +++ b/SmartMove/MainWindow.xaml.cs @@ -617,7 +617,8 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) throw new InvalidDataException("Unexpected!!!"); } - vendorConverter.Initialize(vendorParser, ConfigFilePath.Text, toolVersion, targetFolder, DomainName.Text); + //here outputformat was set to 'json' by default manually because there is no an option for it on GUI + vendorConverter.Initialize(vendorParser, ConfigFilePath.Text, toolVersion, targetFolder, DomainName.Text, "json"); vendorConverter.ConversionProgress += OnConversionProgress; try diff --git a/SmartMove/Program.cs b/SmartMove/Program.cs index 700823b1..a984630a 100644 --- a/SmartMove/Program.cs +++ b/SmartMove/Program.cs @@ -19,7 +19,7 @@ public static int Main(string[] args) CommandLine commandLine = new CommandLine(args); //display command help - if (args[0].Equals("-help") || args[0].Equals("/?")) + if (args[0].Equals("--help") || args[0].Equals("/?") || args[0].Equals("-h")) { return commandLine.DisplayHelp(); } From 41c90493496646631a546ed5f5d81b633051b254 Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Mon, 14 Jun 2021 16:03:34 +0300 Subject: [PATCH 06/12] add json output to the console with err codes --- CommonUtils/JsonReport.cs | 83 +++++++++++++ JuniperMigration/JuniperConverter.cs | 5 +- MigrationBase/VendorConverter.cs | 10 +- SmartMove/CommandLine.cs | 173 +++++++++++++++++++-------- 4 files changed, 219 insertions(+), 52 deletions(-) create mode 100644 CommonUtils/JsonReport.cs diff --git a/CommonUtils/JsonReport.cs b/CommonUtils/JsonReport.cs new file mode 100644 index 00000000..b58cc04f --- /dev/null +++ b/CommonUtils/JsonReport.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Threading.Tasks; + +namespace CommonUtils +{ + [DataContract] + 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() + { + this.msg = msg; + if (err != null) + error = err; + if (warning != null) + this.warning = warning; + } + + public string PrintJson() + { + var ms = new MemoryStream(); + var ser = new DataContractJsonSerializer(typeof(JsonReport)); + ser.WriteObject(ms, this); + ms.Position = 0; + var sr = new StreamReader(ms); + return sr.ReadToEnd(); + } + } + + [DataContract] + public class TotalJsonReport + { + [DataMember] + public string msg { get; set; } + //total count at the finish + [DataMember] + public int warnings { get; set; } + [DataMember] + public int errors { get; set; } + + public TotalJsonReport() { + errors = 0; + warnings = 0; + } + public TotalJsonReport(string msg, string errs, string warnings) : this() + { + this.msg = msg; + int errsCount = int.Parse(errs); + int warnCount = int.Parse(warnings); + if (errsCount > 0) + errors = errsCount; + if (warnCount > 0) + this.warnings = warnCount; + } + + public string PrintJson() + { + var ms = new MemoryStream(); + var ser = new DataContractJsonSerializer(typeof(TotalJsonReport)); + ser.WriteObject(ms, this); + ms.Position = 0; + var sr = new StreamReader(ms); + return sr.ReadToEnd(); + } + } +} diff --git a/JuniperMigration/JuniperConverter.cs b/JuniperMigration/JuniperConverter.cs index c6c6d477..d115299b 100644 --- a/JuniperMigration/JuniperConverter.cs +++ b/JuniperMigration/JuniperConverter.cs @@ -3194,10 +3194,7 @@ private bool IsFirewallRuleMatchedByNATRule(CheckPoint_NAT_Rule natRule, CheckPo return true; } - if (fwRule.Service.Count == 0) - { - // TODO: ??? - } + 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... diff --git a/MigrationBase/VendorConverter.cs b/MigrationBase/VendorConverter.cs index 3df79ec8..5fc47e41 100644 --- a/MigrationBase/VendorConverter.cs +++ b/MigrationBase/VendorConverter.cs @@ -711,7 +711,15 @@ protected virtual bool AddCheckPointObject(CheckPointObject cpObject) } else { - Console.WriteLine("Check Point object type " + cpObject.GetType() + " not found!!"); + //this is warning only + if (_outputFormat == "text") + Console.WriteLine("Check Point object type " + cpObject.GetType() + " not found!!"); + else + { + JsonReport jsonReport = new JsonReport( + msg: "Check Point object type " + cpObject.GetType() + " not found!!"); + Console.WriteLine(jsonReport.PrintJson()); + } } return found; diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index da8cc4a4..933a7d2c 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -11,6 +11,7 @@ using PaloAltoMigration; using PanoramaPaloAltoMigration; using System.Text.RegularExpressions; +using CommonUtils; namespace SmartMove { @@ -27,7 +28,7 @@ public CommandLine(string[] args) } #region command line options - //–f “D:\SmartMove\Content\config.txt” + //–s “D:\SmartMove\Content\config.txt” private string configFileName { get; set; } public string ConfigFileName { @@ -135,7 +136,7 @@ public int CheckOptionsValidity(CommandLine commandLine) } if (String.IsNullOrEmpty(commandLine.ConfigFileName)) { - Console.WriteLine("Option -f is mandatory but not specified.", MessageTypes.Error); + Console.WriteLine("Option -s is mandatory but not specified.", MessageTypes.Error); Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } @@ -150,7 +151,7 @@ public int CheckOptionsValidity(CommandLine commandLine) { if (commandLine.ConvertUserConfiguration == true) { - Console.WriteLine("Option -u is not valid for vendor " + commandLine.Vendor + "!"); + Console.WriteLine("Option -l is not valid for vendor " + commandLine.Vendor + "!"); Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } @@ -167,7 +168,7 @@ public int CheckOptionsValidity(CommandLine commandLine) { if (commandLine.ConvertUserConfiguration == true && commandLine.LdapAccountUnit == null) { - Console.WriteLine("Value for option -u is not specified!"); + Console.WriteLine("Value for option -l is not specified!"); Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } @@ -322,8 +323,8 @@ public CommandLine Parse(string[] args) case "-f": case "--format": { - if (new List() { "text", "json" }.Contains(args[i+1].ToLower())) - FormatOutput = args[i+1]; + if (new List() { "text", "json" }.Contains(args[i + 1].ToLower())) + FormatOutput = args[i + 1]; else Console.WriteLine("Value for option format is not corrected! Allow only 'text' or 'json' ", MessageTypes.Error); break; @@ -348,8 +349,12 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Configuration file is not selected.", MessageTypes.Error); else - //TODO: json - Console.WriteLine(JsonConvert.SerializeObject(new A())); + { + JsonReport jsonReport = new JsonReport( + msg: "Configuration file is not selected.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } return; } @@ -358,8 +363,12 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Cannot find configuration file.", MessageTypes.Error); else - //TODO: json - Console.WriteLine("{\n msg: Cannot find configuration file.\n error: generic_err_object_not_found\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Cannot find configuration file.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } return; } @@ -368,8 +377,12 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Configuration file name is restricted to 20 characters at most.", MessageTypes.Error); else - //TODO: json - Console.WriteLine("{\n msg: Configuration file name is restricted to 20 characters at most.\n error: err_validation_failed\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Configuration file name is restricted to 20 characters at most.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } return; } @@ -378,8 +391,12 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Cannot find target folder for conversion output.", MessageTypes.Error); else - //TODO: json - Console.WriteLine("{\n msg: Cannot find target folder for conversion output.\n error: generic_err_object_not_found\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Cannot find target folder for conversion output.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } return; } @@ -423,6 +440,8 @@ public void DoMigration(CommandLine commandLine) { vendorParser.Parse(ciscoFile); } + + } catch (Exception ex) { @@ -433,8 +452,10 @@ public void DoMigration(CommandLine commandLine) } else { - //TODO: json - Console.WriteLine("{\n msg: \t Could not parse configuration file.\n error: err_cannot_convert_configuration_file\n}"); + JsonReport jsonReport = new JsonReport( + msg: "Could not parse configuration file.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); return; } } @@ -448,8 +469,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unspecified ASA version.\nCannot find ASA version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unspecified ASA version.\nCannot find ASA version for the selected configuration.\nThe configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unspecified ASA version. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } else if (vendorParser.MajorVersion < 8 || (vendorParser.MajorVersion == 8 && vendorParser.MinorVersion < 3)) @@ -457,8 +481,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unsupported ASA version (" + vendorParser.Version + "). This tool supports ASA 8.3 and above configuration files. The configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unsupported ASA version (" + vendorParser.Version + "). This tool supports ASA 8.3 and above configuration files. The configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unsupported ASA version (" + vendorParser.Version + "). This tool supports ASA 8.3 and above configuration files. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } break; @@ -469,8 +496,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unspecified SRX version.\nCannot find SRX version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unspecified SRX version. Cannot find SRX version for the selected configuration. The configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unspecified SRX version. Cannot find SRX version for the selected configuration. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } else if (vendorParser.MajorVersion < 12 || (vendorParser.MajorVersion == 12 && vendorParser.MinorVersion < 1)) @@ -478,8 +508,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unsupported SRX version (" + vendorParser.Version + ").\nThis tool supports SRX 12.1 and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unsupported SRX version (" + vendorParser.Version + "). This tool supports SRX 12.1 and above configuration files. The configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unsupported SRX version (" + vendorParser.Version + "). This tool supports SRX 12.1 and above configuration files. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } break; @@ -493,8 +526,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unspecified FortiGate version.\nCannot find FortiGate version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unspecified FortiGate version. Cannot find FortiGate version for the selected configuration. The configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unspecified FortiGate version. Cannot find FortiGate version for the selected configuration. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } else if (vendorParser.MajorVersion < 5) @@ -502,8 +538,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unsupported FortiGate version (" + vendorParser.Version + ").\nThis tool supports FortiGate 5.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unsupported FortiGate version (" + vendorParser.Version + "). This tool supports FortiGate 5.x and above configuration files. The configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unsupported FortiGate version (" + vendorParser.Version + "). This tool supports FortiGate 5.x and above configuration files. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } break; @@ -513,8 +552,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unspecified PaloAlto version.\nCannot find PaloAlto PAN-OS version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unspecified PaloAlto version. Cannot find PaloAlto PAN-OS version for the selected configuration. The configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unspecified PaloAlto version. Cannot find PaloAlto PAN-OS version for the selected configuration. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } else if (vendorParser.MajorVersion < 7) @@ -522,8 +564,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto PAN-OS 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto PAN-OS 7.x and above configuration files. The configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto PAN-OS 7.x and above configuration files. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } break; @@ -533,8 +578,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unspecified PaloAlto Panorama version.\nCannot find PaloAlto Panorama version for the selected configuration.\nThe configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unspecified PaloAlto Panorama version. Cannot find PaloAlto Panorama version for the selected configuration. The configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unspecified PaloAlto Panorama version. Cannot find PaloAlto Panorama version for the selected configuration. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } else if (vendorParser.MajorVersion < 7) @@ -542,8 +590,11 @@ public void DoMigration(CommandLine commandLine) if (FormatOutput == "text") Console.WriteLine("Unsupported PaloAlto version (" + vendorParser.Version + ").\nThis tool supports PaloAlto Panorama 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); else - //TODO: json - Console.WriteLine("{\n warning: Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto Panorama 7.x and above configuration files. The configuration may not parse correctly.\n}"); + { + JsonReport jsonReport = new JsonReport( + msg: "Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto Panorama 7.x and above configuration files. The configuration may not parse correctly."); + Console.WriteLine(jsonReport.PrintJson()); + } return; } break; @@ -604,14 +655,33 @@ public void DoMigration(CommandLine commandLine) try { - Console.WriteLine("Conversion is in progress..."); + Console.Write("Conversion is in progress..."); + //ProgressBar progress = new ProgressBar(); Dictionary results = vendorConverter.Convert(convertNat); - Console.WriteLine("Conversion is finished."); - if (results.ContainsKey("errors")) - Console.WriteLine("Errors: {0}", results["errors"]); - if (results.ContainsKey("warnings")) - Console.WriteLine("Warnings: {0}", results["warnings"]); - //TODO: json + /*for (int i = 0; i <= 100; i+=5) + { + progress.Report((double)i / 100); + Thread.Sleep(20); + } + progress.Report(100); + Console.WriteLine("Done.");*/ + + if (formatOutput.Equals("text")) + { + Console.WriteLine("Conversion finished."); + if (results.ContainsKey("errors")) + Console.WriteLine("Errors: {0}", results["errors"]); + if (results.ContainsKey("warnings")) + Console.WriteLine("Warnings: {0}", results["warnings"]); + } + else + { + TotalJsonReport jsonReport = new TotalJsonReport( + msg: "Conversion finished", + errs: results.ContainsKey("errors") ? results["errors"].ToString() : null, + warnings: results.ContainsKey("warnings") ? results["warnings"].ToString() : null); + Console.WriteLine(jsonReport.PrintJson()); + } } catch (Exception ex) @@ -626,15 +696,24 @@ public void DoMigration(CommandLine commandLine) "To assure the smooth conversion of your data, it is recommended to contact Check Point Professional Services by sending an e-mail to ps@checkpoint.com")); } else - //TODO: json - Console.WriteLine(String.Format("{\n msg: {0}\n error: {1}\n}", Environment.NewLine, "SmartMove is unable to convert the provided policy. Reason: Policy exceeds the maximum number of supported policy layers.", "generic_error")); + { + JsonReport jsonReport = new JsonReport( + msg: "SmartMove is unable to convert the provided policy. Reason: Policy exceeds the maximum number of supported policy layers.", + err: "generic_error"); + Console.WriteLine(jsonReport.PrintJson()); + } } else { if (FormatOutput == "text") Console.WriteLine(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); - /*else - Console.WriteLine(string.Format("{\n msg: {0}\n error: {1}\n}", Environment.NewLine, "Could not convert configuration file.", "generic_error"));*/ + else + { + JsonReport jsonReport = new JsonReport( + msg: "Could not convert configuration file.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } } return; } From d5d83aacf66e64339c8f1ac7f09dc8428438e72b Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Tue, 15 Jun 2021 11:52:34 +0300 Subject: [PATCH 07/12] *added checking for value ldap at the console *now the programm breaks if console commands was inputed with wrong values *added progress bar to console --- CiscoMigration/CiscoConverter.cs | 57 ++++++ CommonUtils/CommonUtils.csproj | 3 + CommonUtils/JsonReport.cs | 12 +- CommonUtils/ProgressBar.cs | 168 ++++++++++++++++ FortinetMigration/FortiGateConverter.cs | 249 +++++++++++++++--------- JuniperMigration/JuniperConverter.cs | 54 +++++ MigrationBase/VendorConverter.cs | 33 ++-- NetScreenMigration/ScreenOSConverter.cs | 49 +++++ PaloAltoMigration/PaloAltoConverter.cs | 43 ++++ PaloAltoMigration/PanoramaConverter.cs | 44 ++++- SmartMove/CommandLine.cs | 80 +++++--- SmartMove/SmartMove.csproj | 5 + SmartMove/packages.config | 1 + 13 files changed, 664 insertions(+), 134 deletions(-) create mode 100644 CommonUtils/ProgressBar.cs diff --git a/CiscoMigration/CiscoConverter.cs b/CiscoMigration/CiscoConverter.cs index d1e22518..4e87b352 100644 --- a/CiscoMigration/CiscoConverter.cs +++ b/CiscoMigration/CiscoConverter.cs @@ -26,6 +26,7 @@ limitations under the License. using Newtonsoft.Json; using System.Diagnostics; using System.Globalization; +using System.Threading; namespace CiscoMigration { @@ -4695,6 +4696,15 @@ public override void Initialize(VendorParser vendorParser, string vendorFilePath public override Dictionary Convert(bool convertNat) { + if (IsConsoleRunning) + Progress = new ProgressBar(); + + if (IsConsoleRunning) + { + Console.WriteLine("Converting obects ..."); + Progress.SetProgress(20); + Thread.Sleep(1000); + } RaiseConversionProgress(20, "Converting obects ..."); _cpObjects.Initialize(); // must be first!!! @@ -4714,16 +4724,43 @@ public override Dictionary Convert(bool convertNat) Add_or_Modify_InterfaceNetworkGroups(); Add_ServicesAndServiceGroups(); Add_TimeRanges(); + + if (IsConsoleRunning) + { + Console.WriteLine("Converting rules ..."); + Progress.SetProgress(30); + Thread.Sleep(1000); + } RaiseConversionProgress(30, "Converting rules ..."); Add_Package(); if (convertNat) { + if (IsConsoleRunning) + { + Console.WriteLine("Converting NAT rules ..."); + Progress.SetProgress(40); + Thread.Sleep(1000); + } RaiseConversionProgress(40, "Converting NAT rules ..."); Add_object_NAT(); Add_NAT_Rules(); + + if (IsConsoleRunning) + { + Console.WriteLine("Creating NAT rulebase ..."); + Progress.SetProgress(50); + Thread.Sleep(1000); + } RaiseConversionProgress(50, "Creating NAT rulebase ..."); CreateNATRulebase(); + + if (IsConsoleRunning) + { + Console.WriteLine("Creating Firewall rulebase ..."); + Progress.SetProgress(60); + Thread.Sleep(1000); + } RaiseConversionProgress(60, "Creating Firewall rulebase ..."); MatchNATRulesIntoFirewallPolicy(); } @@ -4731,8 +4768,21 @@ public override Dictionary Convert(bool convertNat) // This should be done here, after all objects are converted!!! EnforceObjectNameValidity(); + if (IsConsoleRunning) + { + Console.WriteLine("Optimizing Firewall rulebase ..."); + Progress.SetProgress(70); + Thread.Sleep(1000); + } RaiseConversionProgress(70, "Optimizing Firewall rulebase ..."); Add_Optimized_Package(); + + if (IsConsoleRunning) + { + Console.WriteLine("Generating CLI scripts ..."); + Progress.SetProgress(80); + Thread.Sleep(1000); + } RaiseConversionProgress(80, "Generating CLI scripts ..."); CreateObjectsScript(); CreatePackagesScript(); @@ -4747,6 +4797,13 @@ public override Dictionary Convert(bool convertNat) ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); CreateSmartConnector(); + + + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } return new Dictionary() { { "warnings", ConversionIncidentCategoriesCount } }; } diff --git a/CommonUtils/CommonUtils.csproj b/CommonUtils/CommonUtils.csproj index e4e21345..edfcf3fd 100644 --- a/CommonUtils/CommonUtils.csproj +++ b/CommonUtils/CommonUtils.csproj @@ -35,6 +35,7 @@ ..\packages\IPNetwork2.2.0.3\lib\net40\System.Net.IPNetwork.dll + @@ -44,7 +45,9 @@ + + diff --git a/CommonUtils/JsonReport.cs b/CommonUtils/JsonReport.cs index b58cc04f..21585480 100644 --- a/CommonUtils/JsonReport.cs +++ b/CommonUtils/JsonReport.cs @@ -50,9 +50,9 @@ public class TotalJsonReport [DataMember] public string msg { get; set; } //total count at the finish - [DataMember] + [DataMember(Name = "Conversion warnings")] public int warnings { get; set; } - [DataMember] + [DataMember(Name = "Conversion errors")] public int errors { get; set; } public TotalJsonReport() { @@ -62,8 +62,12 @@ public TotalJsonReport() { public TotalJsonReport(string msg, string errs, string warnings) : this() { this.msg = msg; - int errsCount = int.Parse(errs); - int warnCount = int.Parse(warnings); + int errsCount = 0; + int warnCount = 0; + if (errs != null) + errsCount = int.Parse(errs); + if (warnings != null) + warnCount = int.Parse(warnings); if (errsCount > 0) errors = errsCount; if (warnCount > 0) diff --git a/CommonUtils/ProgressBar.cs b/CommonUtils/ProgressBar.cs new file mode 100644 index 00000000..30c0a411 --- /dev/null +++ b/CommonUtils/ProgressBar.cs @@ -0,0 +1,168 @@ +using System; +using System.IO; +using System.Text; +using System.Threading; + +namespace CommonUtils +{ + public class ProgressBar : IDisposable + { + public float CurrentProgress => writer.CurrentProgress; + + private TextWriter OriginalWriter; + private ProgressWriter writer; + + public ProgressBar() + { + OriginalWriter = Console.Out; + writer = new ProgressWriter(OriginalWriter); + Console.SetOut(writer); + } + + public void Dispose() + { + Console.SetOut(OriginalWriter); + writer.ClearProgressBar(); + } + + public void SetProgress(float f) + { + writer.CurrentProgress = f; + writer.RedrawProgress(); + } + public void SetProgress(int i) + { + SetProgress((float)i); + } + + public void Increment(float f) + { + writer.CurrentProgress += f; + writer.RedrawProgress(); + } + + public void Increment(int i) + { + Increment((float)i); + } + + private class ProgressWriter : TextWriter + { + + public override Encoding Encoding => Encoding.UTF8; + public float CurrentProgress + { + get { return _currentProgress; } + set + { + _currentProgress = value; + if (_currentProgress > 100) + { + _currentProgress = 100; + } + else if (CurrentProgress < 0) + { + _currentProgress = 0; + } + } + } + + private float _currentProgress = 0; + private TextWriter consoleOut; + private const string ProgressTemplate = "[{0}] {1:n2}%"; + private const int AllocatedTemplateSpace = 11; + private object SyncLock = new object(); + public ProgressWriter(TextWriter _consoleOut) + { + consoleOut = _consoleOut; + RedrawProgress(); + } + + private void DrawProgressBar() + { + lock (SyncLock) + { + int avalibleSpace = Console.BufferWidth - AllocatedTemplateSpace; + int percentAmmount = (int)((float)avalibleSpace * (CurrentProgress / 100)); + var col = Console.ForegroundColor; + Console.ForegroundColor = ConsoleColor.White; + string progressBar = string.Concat(new string('=', percentAmmount), new string(' ', avalibleSpace - percentAmmount)); + consoleOut.Write(string.Format(ProgressTemplate, progressBar, CurrentProgress)); + Console.ForegroundColor = col; + } + } + + public void RedrawProgress() + { + lock (SyncLock) + { + int LastLineWidth = Console.CursorLeft; + var consoleH = Console.WindowTop + Console.WindowHeight - 1; + Console.SetCursorPosition(0, consoleH); + DrawProgressBar(); + Console.SetCursorPosition(LastLineWidth, consoleH - 1); + } + } + + private void ClearLineEnd() + { + lock (SyncLock) + { + int lineEndClear = Console.BufferWidth - Console.CursorLeft - 1; + consoleOut.Write(new string(' ', lineEndClear)); + } + } + + public void ClearProgressBar() + { + lock (SyncLock) + { + int LastLineWidth = Console.CursorLeft; + var consoleH = Console.WindowTop + Console.WindowHeight - 1; + Console.SetCursorPosition(0, consoleH); + ClearLineEnd(); + Console.SetCursorPosition(LastLineWidth, consoleH); + } + } + + public override void Write(char value) + { + lock (SyncLock) + { + consoleOut.Write(value); + } + } + + public override void Write(string value) + { + lock (SyncLock) + { + consoleOut.Write(value); + } + } + + public override void WriteLine(string value) + { + lock (SyncLock) + { + consoleOut.Write(value); + consoleOut.Write(Environment.NewLine); + ClearLineEnd(); + consoleOut.Write(Environment.NewLine); + RedrawProgress(); + } + } + + public override void WriteLine(string format, params object[] arg) + { + WriteLine(string.Format(format, arg)); + } + + public override void WriteLine(int i) + { + WriteLine(i.ToString()); + } + + } + } +} diff --git a/FortinetMigration/FortiGateConverter.cs b/FortinetMigration/FortiGateConverter.cs index 53323429..13bd918c 100644 --- a/FortinetMigration/FortiGateConverter.cs +++ b/FortinetMigration/FortiGateConverter.cs @@ -9,6 +9,7 @@ using System.Globalization; using System.Text.RegularExpressions; using System.Net; +using System.Threading; namespace FortiGateMigration { @@ -718,8 +719,14 @@ public override Dictionary Convert(bool convertNat) string targetFileNameMain = _vendorFileName; string targetFolderMain = _targetFolder; + if (IsConsoleRunning) + Progress = new ProgressBar(); + LDAP_Account_Unit = LDAPAccoutUnit.Trim(); + if (IsConsoleRunning) + Progress.SetProgress(5); + bool isVDom = ConvertVDom(targetFolderMain, _fortiGateParser.FgCommandsList, convertNat); if (!isVDom) //if configration file does not conatin any VDOM @@ -736,7 +743,20 @@ public override Dictionary Convert(bool convertNat) CleanCheckPointObjectsLists(); } + if (IsConsoleRunning) + { + Console.WriteLine("Optimizing Firewall rulebase ..."); + Progress.SetProgress(72); + Thread.Sleep(1000); + } RaiseConversionProgress(70, "Optimizing Firewall rulebase ..."); + + if (IsConsoleRunning) + { + Console.WriteLine("Generating CLI scripts ..."); + Progress.SetProgress(80); + Thread.Sleep(1000); + } RaiseConversionProgress(80, "Generating CLI scripts ..."); ChangeTargetFolder(targetFolderMain, targetFileNameMain); // chaning target folder path to folder contains config file @@ -755,12 +775,23 @@ public override Dictionary Convert(bool convertNat) ObjectsScriptFile = _targetFolder; PolicyScriptFile = _targetFolder; + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } return new Dictionary() { { "errors", ErrorsInConvertedPackage() }, { "warnings", WarningsInConvertedPackage() } }; } //Convertint VDOMs to each VDOM and then Convert each VDOM as simple Configuration public bool ConvertVDom(string targetFolderM, List fgCommandsList, bool convertNat) { + if (IsConsoleRunning) + { + Console.WriteLine("Checking if vdom is present..."); + Progress.SetProgress(10); + Thread.Sleep(1000); + } RaiseConversionProgress(10, "Checking if vdom is present..."); bool isVDom = false; @@ -803,6 +834,12 @@ public bool ConvertVDom(string targetFolderM, List fgCommandsList, bo //Init system Interfaces which is Global public void InitSystemInterfaces(List fgCommandsList) { + if (IsConsoleRunning) + { + Console.WriteLine("Init system interfaces..."); + Progress.SetProgress(20); + Thread.Sleep(1000); + } RaiseConversionProgress(20, "Init system interfaces..."); foreach (FgCommand fgCommand in fgCommandsList) @@ -882,7 +919,19 @@ public void InitSystemInterfaces(List fgCommandsList) //converting full configuration file or part which is related to VDOM public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List fgCommandsList, bool convertNat) { + if (IsConsoleRunning) + { + Console.WriteLine("Convert configuration..."); + Progress.SetProgress(35); + Thread.Sleep(1000); + } RaiseConversionProgress(35, "Convert configuration..."); + if (IsConsoleRunning) + { + Console.WriteLine("Convert objects..."); + Progress.SetProgress(40); + Thread.Sleep(1000); + } RaiseConversionProgress(40, "Convert objects..."); _cpObjects.Initialize(); // must be first!!! CleanCheckPointObjectsLists(); // must be first!!! @@ -1072,15 +1121,15 @@ public void AddRoutesStatic(List fgCommandsList) foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) { - if(fgCommandS.GetType() == typeof(FgCommand_Set)) + if (fgCommandS.GetType() == typeof(FgCommand_Set)) { FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - if(fgCommandSet.Field.Equals("dst")) + if (fgCommandSet.Field.Equals("dst")) { string[] destination = fgCommandSet.Value.Trim('"').Trim().Split(new string[] { " " }, StringSplitOptions.None).ToArray(); - if(destination.Count() == 2) + if (destination.Count() == 2) { fgStaticRoute.Network = destination[0]; fgStaticRoute.Mask = destination[1]; @@ -1090,7 +1139,7 @@ public void AddRoutesStatic(List fgCommandsList) { fgStaticRoute.Gateway = fgCommandSet.Value.Trim('"').Trim(); } - if(fgCommandSet.Field.Equals("device")) + if (fgCommandSet.Field.Equals("device")) { fgStaticRoute.Device = fgCommandSet.Value.Trim('"').Trim(); } @@ -1120,12 +1169,12 @@ public void AddRoutesStatic(List fgCommandsList) public void CheckDynamicRoutesRip(List fgCommandsList) { - foreach(FgCommand fgCommandC in fgCommandsList) + foreach (FgCommand fgCommandC in fgCommandsList) { - if(fgCommandC.GetType() == typeof(FgCommand_Config)) + if (fgCommandC.GetType() == typeof(FgCommand_Config)) { FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommandC; - if(fgCommandConfig.ObjectName.Equals("interface")) + if (fgCommandConfig.ObjectName.Equals("interface")) { _localFgDynRoutesEnable = true; } @@ -1150,12 +1199,12 @@ public void CheckDynamicRoutesRipNg(List fgCommandsList) public void CheckDynamicRoutesOspf(List fgCommandsList) { - foreach(FgCommand fgCommandS in fgCommandsList) + foreach (FgCommand fgCommandS in fgCommandsList) { - if(fgCommandS.GetType() == typeof(FgCommand_Set)) + if (fgCommandS.GetType() == typeof(FgCommand_Set)) { FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - if(fgCommandSet.Field.Equals("router-id")) + if (fgCommandSet.Field.Equals("router-id")) { _localFgDynRoutesEnable = true; } @@ -1860,7 +1909,7 @@ public void AddFirewallScheduleGroups(List fgCommandsList) public void AddFirewallScheduleGroupsRecurs(string cpTimeGrpName, Dictionary checkingTimeGrps) { List errorsList = new List(); - + CheckPoint_TimeGroup cpTimeGrp = checkingTimeGrps[cpTimeGrpName]; checkingTimeGrps.Remove(cpTimeGrpName); @@ -1868,7 +1917,7 @@ public void AddFirewallScheduleGroupsRecurs(string cpTimeGrpName, Dictionary fgCommandsList) foreach (string zoneInterface in zoneInterfaces) { - if(_interfacesMapperFgCp.ContainsKey(zoneInterface)) + if (_interfacesMapperFgCp.ContainsKey(zoneInterface)) { List cpObjsList = _interfacesMapperFgCp[zoneInterface]; foreach (CheckPoint_Host cpObj in cpObjsList) @@ -2058,7 +2107,7 @@ public void AddUserGroup(List fgCommandsList) FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; bool isFSSOService = false; - + string membersStr = ""; foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) @@ -2133,7 +2182,7 @@ public void AddUserGroup(List fgCommandsList) public void Add_ConfigFirewallAddress(List fgCommandsList) { - foreach(FgCommand fgCommand in fgCommandsList) + foreach (FgCommand fgCommand in fgCommandsList) { if (fgCommand.GetType() == typeof(FgCommand_Edit)) { @@ -2433,16 +2482,16 @@ public void AddFirewallVip(List fgCommandsList) } break; case "icmp": - string type = "99"; - - bool isFound = false; - string cpServiceName = _cpObjects.GetKnownServiceName("ICMP_" + type, out isFound); - - CheckPointObject cpObj = _cpObjects.GetObject(cpServiceName); - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameVipE, cpObj); - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameVipM, cpObj); - break; + string type = "99"; + + bool isFound = false; + string cpServiceName = _cpObjects.GetKnownServiceName("ICMP_" + type, out isFound); + + CheckPointObject cpObj = _cpObjects.GetObject(cpServiceName); + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameVipE, cpObj); + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameVipM, cpObj); + break; } } } @@ -2628,7 +2677,7 @@ public void Add_AddressGroups(List fgCommandsList) public void Add_AddressGroupsRecurs(string cpAddrGrpName, Dictionary checkingAddrGrps) { List errorsList = new List(); - + CheckPoint_NetworkGroup cpAddrGrp = checkingAddrGrps[cpAddrGrpName]; checkingAddrGrps.Remove(cpAddrGrpName); @@ -2636,7 +2685,7 @@ public void Add_AddressGroupsRecurs(string cpAddrGrpName, Dictionary fgCommandsList, bool convertNat) { + if (IsConsoleRunning) { + Console.WriteLine("Convert policy..."); + Progress.SetProgress(70); + Thread.Sleep(1000); + } RaiseConversionProgress(70, "Convert policy..."); var cpPackage = new CheckPoint_Package(); @@ -2718,11 +2772,11 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman //add sub policy layer //add rule from Intrazone - foreach(CheckPoint_Zone cpZoneIntra in _localIntrazonesList) + foreach (CheckPoint_Zone cpZoneIntra in _localIntrazonesList) { string warnMessage = CheckZoneForReservedWords(cpZoneIntra); - if(warnMessage != null) + if (warnMessage != null) { _warningsList.Add(warnMessage); } @@ -2773,8 +2827,8 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman cpRule.ConversionComments = "Matched rule " + fgCommand_Edit.Table; - string[] fgSrcIntfs = new string[]{}; - string[] fgDstIntfs = new string[]{}; + string[] fgSrcIntfs = new string[] { }; + string[] fgDstIntfs = new string[] { }; cpRule.Track = CheckPoint_Rule.TrackTypes.Log; @@ -2793,7 +2847,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman { FgCommand_Set fgCommand_Set = (FgCommand_Set)fgCommandS; - if(fgCommand_Set.Field.Equals("name")) + if (fgCommand_Set.Field.Equals("name")) { cpRule.Name = GetSafeName(fgCommand_Set.Value); } @@ -2812,17 +2866,17 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman { cpRule.Action = CheckPoint_Rule.ActionType.Accept; } - + if (fgCommand_Set.Field.Equals("srcintf")) { fgSrcIntfs = fgCommand_Set.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - if(Array.IndexOf(fgSrcIntfs.Select(s => s.ToLowerInvariant()).ToArray(), "any") > -1) + if (Array.IndexOf(fgSrcIntfs.Select(s => s.ToLowerInvariant()).ToArray(), "any") > -1) { isIntfContainsAny = true; } } - + if (fgCommand_Set.Field.Equals("dstintf")) { fgDstIntfs = fgCommand_Set.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); @@ -2848,7 +2902,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman bool isAdded = false; - string[] fgPrefixes = new string[] + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_address, FG_PREFIX_KEY_firewall_addrgrp, @@ -2874,7 +2928,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman } } - if(!isAdded) + if (!isAdded) { errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'srcaddr' field with non-existing reference to: " + name + " and was not created."); } @@ -2898,7 +2952,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman bool isAdded = false; - string[] fgPrefixes = new string[] + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_address, FG_PREFIX_KEY_firewall_addrgrp, @@ -2924,7 +2978,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman } } - if(!isAdded) + if (!isAdded) { errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'dstaddr' field with non-existing reference to: " + name + " and was not created."); } @@ -2956,7 +3010,8 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman if (_localMapperFgCp.ContainsKey(fgPrefix + fgScheduleRule)) { List cpObjsList = _localMapperFgCp[fgPrefix + fgScheduleRule]; - foreach(CheckPointObject cpObj in cpObjsList) { + foreach (CheckPointObject cpObj in cpObjsList) + { cpRule.Time.Add(cpObj); if (OptimizeConf) { @@ -2967,7 +3022,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman } } - if(!isAdded) + if (!isAdded) { errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'schedule' field with unrecognized value: " + fgScheduleRule + " and was not created"); } @@ -3077,7 +3132,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman { fgSrcIntfsList.AddRange(_localMapperFgCp[FG_PREFIX_KEY_system_zone + fgSrcIntf]); } - else if(extraZonesMap.ContainsKey(FG_PREFIX_KEY_system_zone + fgSrcIntf)) + else if (extraZonesMap.ContainsKey(FG_PREFIX_KEY_system_zone + fgSrcIntf)) { fgSrcIntfsList.Add(extraZonesMap[FG_PREFIX_KEY_system_zone + fgSrcIntf]); } @@ -3087,7 +3142,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman cpZoneSrc.Name = GetSafeName(fgSrcIntf_Appendix + fgSrcIntf); string warnMessage = CheckZoneForReservedWords(cpZoneSrc); - if(warnMessage != null) + if (warnMessage != null) { extraZonesWarnMsgsList.Add(warnMessage); } @@ -3115,7 +3170,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman { fgDstIntfsList.AddRange(_localMapperFgCp[FG_PREFIX_KEY_system_zone + fgDstIntf]); } - else if(extraZonesMap.ContainsKey(FG_PREFIX_KEY_system_zone + fgDstIntf)) + else if (extraZonesMap.ContainsKey(FG_PREFIX_KEY_system_zone + fgDstIntf)) { fgDstIntfsList.Add(extraZonesMap[FG_PREFIX_KEY_system_zone + fgDstIntf]); } @@ -3187,7 +3242,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman realRulesList.Add(cpRule); _rulesInConvertedPackage += 1; - + if (cpRuleUG != null) { rootLayer.Rules.Add(cpRuleUG); @@ -3199,7 +3254,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman //NAT conversion reagrding design which is described in other doc - if(convertNat) + if (convertNat) { int counterNatRules = -1; @@ -3207,12 +3262,12 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman { if (isNatEnabled) { - if(_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_grp + fgDstAddr)) + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_grp + fgDstAddr)) { List cpVipGrpsList = _localMapperFgCp[FG_PREFIX_KEY_firewall_vip_grp + fgDstAddr]; foreach (CheckPointObject cpVipGrpI in cpVipGrpsList) { - if(cpVipGrpI.GetType() == typeof(CheckPoint_NetworkGroup)) + if (cpVipGrpI.GetType() == typeof(CheckPoint_NetworkGroup)) { CheckPoint_NetworkGroup cpVipGrp = (CheckPoint_NetworkGroup)cpVipGrpI; @@ -3220,7 +3275,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman foreach (string cpVipI in cpVipMembersOrig) { - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + cpVipI) || + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + cpVipI) || _localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + cpVipI)) { counterNatRules = AddNatRuleVipNatEnable(fgCommand_Edit, cpVipI, counterNatRules); @@ -3229,7 +3284,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman } } } - else if(_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + fgDstAddr) || + else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + fgDstAddr) || _localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + fgDstAddr)) { counterNatRules = AddNatRuleVipNatEnable(fgCommand_Edit, fgDstAddr, counterNatRules); @@ -3278,8 +3333,8 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman } else { - - foreach(string error in errorsList) + + foreach (string error in errorsList) { _errorsList.Add(error); } @@ -3396,7 +3451,7 @@ public List GetFgDstAddrsAsVipExtIpList(string fgDstAddr) public List GetFgDstAddrsAsVipMappedIpList(string fgDstAddr) { List fgDstAddrsList = new List(); - + if (fgDstAddr.ToLower().Equals("all")) { fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); @@ -3478,10 +3533,10 @@ public List GetFgDstAddrToOSAsVipMapIpList(string fgDstAddr) public List GetFgServicesList(FgCommand_Set fgCommandSet) { - List fgServicesList = new List(); + List fgServicesList = new List(); List fgServicesNames = fgCommandSet.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToList(); - for(int i = 0; i < fgServicesNames.Count; i++) + for (int i = 0; i < fgServicesNames.Count; i++) { string fgServiceName = fgServicesNames[i]; @@ -3507,8 +3562,8 @@ public List GetFgServicesList(FgCommand_Set fgCommandSet) //--- // predefined CheckPoint services are not skipped. Sorry, current API does not allow to do that!!!!!!!!!!!!!!! //--- - if ((cpObj.GetType() == typeof(CheckPoint_IcmpService)) || - (cpObj.GetType() == typeof(CheckPoint_SctpService)) || + if ((cpObj.GetType() == typeof(CheckPoint_IcmpService)) || + (cpObj.GetType() == typeof(CheckPoint_SctpService)) || (cpObj.GetType() == typeof(CheckPoint_OtherService))) { continue; @@ -3583,17 +3638,17 @@ public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int } if (fgCommandSet.Field.Equals("dstintf")) { - if(_interfacesMapperFgCp.ContainsKey(fgCommandSet.Value.Trim('"'))) + if (_interfacesMapperFgCp.ContainsKey(fgCommandSet.Value.Trim('"'))) { fgDstIntfsList.AddRange(_interfacesMapperFgCp[fgCommandSet.Value.Trim('"')]); } - else if(_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_system_zone_host + fgCommandSet.Value.Trim('"'))) //if FG dstintf is Zone + else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_system_zone_host + fgCommandSet.Value.Trim('"'))) //if FG dstintf is Zone { if (fgDstAddr.Equals("all")) { continue; //don't process "all" for FG dstaddr because we can't route for "all" addresses } - if(fgDstAddrsList.Count != 1) + if (fgDstAddrsList.Count != 1) { continue; //don't process "multi" FG objects } @@ -3602,7 +3657,7 @@ public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int string fgDstAddrChecking = null; CheckPointObject checkPointObject = fgDstAddrsList[0]; - if(checkPointObject.GetType() == typeof(CheckPoint_Range)) + if (checkPointObject.GetType() == typeof(CheckPoint_Range)) { fgDstAddrChecking = ((CheckPoint_Range)checkPointObject).RangeFrom; } @@ -3622,7 +3677,7 @@ public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int //get FG Interface(s) object(s) for checked Zone List cpObjsList = _localMapperFgCp[FG_PREFIX_KEY_system_zone_host + fgCommandSet.Value.Trim('"')]; //if Zone contains only one Interface : it is simple because dstaddr will be route via that Interface - if(cpObjsList.Count == 1) + if (cpObjsList.Count == 1) { fgDstIntfsList.AddRange(cpObjsList); } @@ -3630,7 +3685,7 @@ public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int // 1) if dynamic routing is disable // 2) to check which Interface contains network for destaddr // 3) if noone Interface contains network for dstaddr, then we should to use interface with default routing (if default routing exists for some Interface) - else if(cpObjsList.Count > 1 && !_localFgDynRoutesEnable) + else if (cpObjsList.Count > 1 && !_localFgDynRoutesEnable) { string intfName = null; int netCidr = -1; @@ -3642,7 +3697,7 @@ public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int { FgInterface interfaceFg = _interfacesFgDict[interfaceNameFg]; IPNetwork ipnetwork = IPNetwork.Parse(interfaceFg.Ip, interfaceFg.Mask); - if(IPNetwork.Contains(ipnetwork, ipaddress) && netCidr < ipnetwork.Cidr) //check if interface from Zone contains dstaddr network + if (IPNetwork.Contains(ipnetwork, ipaddress) && netCidr < ipnetwork.Cidr) //check if interface from Zone contains dstaddr network { intfName = interfaceNameFg; netCidr = ipnetwork.Cidr; @@ -3653,7 +3708,7 @@ public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int { foreach (FgStaticRoute fgStaticRoute in _localFgRoutesDict[interfaceNameFg]) { - if(fgStaticRoute.Network.Equals("0.0.0.0") && intfNameDefault == null) + if (fgStaticRoute.Network.Equals("0.0.0.0") && intfNameDefault == null) { intfNameDefault = fgStaticRoute.Device; continue; @@ -3671,9 +3726,9 @@ public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int { intfName = intfNameDefault; } - if(intfName != null) + if (intfName != null) { - if(_interfacesMapperFgCp.ContainsKey(intfName)) + if (_interfacesMapperFgCp.ContainsKey(intfName)) { fgDstIntfsList.AddRange(_interfacesMapperFgCp[intfName]); } @@ -3687,7 +3742,7 @@ public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int fgSrcAddrsList.AddRange(GetFgSrcAddrsList(fgCommandSet)); } - if(fgCommandSet.Field.Equals("comments")) + if (fgCommandSet.Field.Equals("comments")) { cpNatRuleComments = fgCommandSet.Value.Trim('"'); } @@ -3703,7 +3758,7 @@ public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) { //don't create NAT Rule for Domain objects - if(cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) + if (cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) { _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); continue; @@ -4062,7 +4117,7 @@ public int AddNatRuleVipNatEnable(FgCommand_Edit fgCommandEdit, string fgDstAddr } } - if(isIpPoolEnabled) + if (isIpPoolEnabled) { foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) { @@ -4412,7 +4467,8 @@ public int AddNatRuleVipNatDisable(FgCommand_Edit fgCommandEdit, string fgDstAdd } } } - else { + else + { foreach (CheckPointObject cpObjSrv in fgServicesList) { CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); @@ -4520,15 +4576,15 @@ public string CheckZoneForReservedWords(CheckPoint_Zone inZone) "orange", "red", "sienna", "yellow", "dark", "light", "medium" }; - foreach(string inZoneNamePart in inZoneNameParts) + foreach (string inZoneNamePart in inZoneNameParts) { - if(reservedWords.Contains(inZoneNamePart)) + if (reservedWords.Contains(inZoneNamePart)) { inZoneNameNew += "_" + inZoneNamePart; } else { - if(!inZoneNameNew.Equals("")) + if (!inZoneNameNew.Equals("")) { inZoneNameNew += "-"; } @@ -4537,7 +4593,7 @@ public string CheckZoneForReservedWords(CheckPoint_Zone inZone) } } - if(!inZone.Name.Equals(inZoneNameNew)) + if (!inZone.Name.Equals(inZoneNameNew)) { retMessage = inZone.Name + " zone was renamed to " + inZoneNameNew + " for solving 'reserved words' issue."; inZone.Name = inZoneNameNew; @@ -4559,16 +4615,16 @@ public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObj } //check the name of Object - if(cpObject.GetType() == typeof(CheckPoint_TcpService)) + if (cpObject.GetType() == typeof(CheckPoint_TcpService)) { - if(!char.IsLetter(cpObject.Name, 0)) + if (!char.IsLetter(cpObject.Name, 0)) { string newName = "TCP_" + cpObject.Name; _warningsList.Add(cpObject.Name + " tcp-service was renamed to " + newName); cpObject.Name = newName; } } - else if(cpObject.GetType() == typeof(CheckPoint_UdpService)) + else if (cpObject.GetType() == typeof(CheckPoint_UdpService)) { if (!char.IsLetter(cpObject.Name, 0)) { @@ -4577,16 +4633,16 @@ public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObj cpObject.Name = newName; } } - else if(cpObject.GetType() == typeof(CheckPoint_SctpService)) + else if (cpObject.GetType() == typeof(CheckPoint_SctpService)) { - if(!char.IsLetter(cpObject.Name, 0)) + if (!char.IsLetter(cpObject.Name, 0)) { string newName = "SCTP_" + cpObject.Name; _warningsList.Add(cpObject.Name + " sctp-service was renamed to " + newName); cpObject.Name = newName; } } - else if(cpObject.GetType() == typeof(CheckPoint_IcmpService)) + else if (cpObject.GetType() == typeof(CheckPoint_IcmpService)) { if (!char.IsLetter(cpObject.Name, 0)) { @@ -4604,7 +4660,7 @@ public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObj cpObject.Name = newName; } } - else if(cpObject.GetType() == typeof(CheckPoint_Time)) + else if (cpObject.GetType() == typeof(CheckPoint_Time)) { string cpTimeName = cpObject.Name; @@ -4619,7 +4675,7 @@ public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObj cpObject.Name = cpTimeName; } } - else if(cpObject.GetType() == typeof(CheckPoint_TimeGroup)) + else if (cpObject.GetType() == typeof(CheckPoint_TimeGroup)) { string cpTimeGrpName = cpObject.Name; @@ -4628,7 +4684,7 @@ public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObj cpTimeGrpName = cpTimeGrpName.Substring(0, 6) + "_c" + _timeGroupCutterCounter++; } - if(!cpTimeGrpName.Equals(cpObject.Name)) + if (!cpTimeGrpName.Equals(cpObject.Name)) { _warningsList.Add(cpObject.Name + " time group object was renamed to " + cpTimeGrpName); cpObject.Name = cpTimeGrpName; @@ -4660,7 +4716,7 @@ public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObj } } - if(!cpObject.Name.Equals(cpObjectName)) + if (!cpObject.Name.Equals(cpObjectName)) { _warningsList.Add(cpObject.Name + " object was renamed to " + cpObjectName + " for solving duplicate names issue."); cpObject.Name = cpObjectName; @@ -4672,7 +4728,7 @@ public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObj } #endregion - + public static string GetSafeName(string name) { if (name != null && !name.Trim().Equals("")) @@ -4691,14 +4747,14 @@ public List GetVipGroupMembers(string vipGrpName) List vipGrpMembers = _localFgVipGrpsDict[vipGrpName]; - foreach(string vipGrpMember in vipGrpMembers) + foreach (string vipGrpMember in vipGrpMembers) { - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + vipGrpMember) || + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + vipGrpMember) || _localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + vipGrpMember)) { retList.Add(vipGrpMember); } - else if(_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_grp + vipGrpMember)) + else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_grp + vipGrpMember)) { retList.AddRange(GetVipGroupMembers(vipGrpMember)); } @@ -4729,4 +4785,15 @@ public class FgStaticRoute public string Gateway { get; set; } public string Device { get; set; } } + + public class FgJsonOutputReportsList + { + public string header; + public Dictionary reports; + + public FgJsonOutputReportsList() + { + reports = new Dictionary(); + } + } } diff --git a/JuniperMigration/JuniperConverter.cs b/JuniperMigration/JuniperConverter.cs index d115299b..1c1a2483 100644 --- a/JuniperMigration/JuniperConverter.cs +++ b/JuniperMigration/JuniperConverter.cs @@ -25,6 +25,7 @@ limitations under the License. using CheckPointObjects; using CommonUtils; using MigrationBase; +using System.Threading; namespace JuniperMigration { @@ -3747,6 +3748,15 @@ public override void Initialize(VendorParser vendorParser, string vendorFilePath public override Dictionary Convert(bool convertNat) { + if (IsConsoleRunning) + Progress = new ProgressBar(); + + if (IsConsoleRunning) + { + Console.WriteLine("Converting obects ..."); + Progress.SetProgress(20); + Thread.Sleep(1000); + } RaiseConversionProgress(20, "Converting obects ..."); _cpObjects.Initialize(); // must be first!!! @@ -3761,27 +3771,65 @@ public override Dictionary Convert(bool convertNat) Add_Zones(); // must be called AFTER handling all network stuff!!! Add_ServiceObjects(); + if (IsConsoleRunning) + { + Console.WriteLine("Converting rules ..."); + Progress.SetProgress(30); + Thread.Sleep(1000); + } RaiseConversionProgress(30, "Converting rules ..."); Add_Package(); if (convertNat) { + if (IsConsoleRunning) + { + Console.WriteLine("Converting NAT rules ..."); + Progress.SetProgress(40); + Thread.Sleep(1000); + } RaiseConversionProgress(40, "Converting NAT rules ..."); Add_Static_NAT(); Add_Destination_NAT(); Add_Source_NAT(); + + if (IsConsoleRunning) + { + Console.WriteLine("Creating NAT rulebase ..."); + Progress.SetProgress(50); + Thread.Sleep(1000); + } RaiseConversionProgress(50, "Creating NAT rulebase ..."); CreateNATRulebase(); + + if (IsConsoleRunning) + { + Console.WriteLine("Creating Firewall rulebase ..."); + Progress.SetProgress(60); + Thread.Sleep(1000); + } RaiseConversionProgress(60, "Creating Firewall rulebase ..."); MatchNATRulesIntoFirewallPolicy(); } // This should be done here, after all objects are converted!!! + if (IsConsoleRunning) + { + Console.WriteLine("Validating converted objects ..."); + Progress.SetProgress(70); + Thread.Sleep(1000); + } RaiseConversionProgress(70, "Validating converted objects ..."); EnforceObjectNameValidity(); ReplaceJuniperApplicationsWithEquivalentCheckpointServices(); ReplaceJuniperInvalidApplicationsReferences(); + if (IsConsoleRunning) + { + Console.WriteLine("Generating CLI scripts ..."); + Progress.SetProgress(80); + Thread.Sleep(1000); + } RaiseConversionProgress(80, "Generating CLI scripts ..."); CreateObjectsScript(); CreatePackagesScript(); @@ -3796,6 +3844,12 @@ public override Dictionary Convert(bool convertNat) ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); CreateSmartConnector(); + + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } return new Dictionary() { { "warnings", ConversionIncidentCategoriesCount } }; } diff --git a/MigrationBase/VendorConverter.cs b/MigrationBase/VendorConverter.cs index 5fc47e41..36d9152f 100644 --- a/MigrationBase/VendorConverter.cs +++ b/MigrationBase/VendorConverter.cs @@ -23,6 +23,7 @@ limitations under the License. using System.Linq; using System.Text; using System.Text.RegularExpressions; +using System.Threading; using CheckPointObjects; using CommonUtils; using Newtonsoft.Json; @@ -68,6 +69,7 @@ public abstract class VendorConverter protected string _policyPackageOptimizedName; protected string _outputFormat; //txt or json protected bool _hasNATConversionIncident = false; + protected bool _calledFromConsole = false; protected CheckPointObjectsRepository _cpObjects = new CheckPointObjectsRepository(); @@ -115,6 +117,19 @@ 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; + } + set + { + _calledFromConsole = value; + } + } + + //console progressbar + public ProgressBar Progress { get; set; } = null; #endregion @@ -709,18 +724,6 @@ protected virtual bool AddCheckPointObject(CheckPointObject cpObject) cpObject.ConversionIncidentType = ConversionIncidentType.ManualActionRequired; } } - else - { - //this is warning only - if (_outputFormat == "text") - Console.WriteLine("Check Point object type " + cpObject.GetType() + " not found!!"); - else - { - JsonReport jsonReport = new JsonReport( - msg: "Check Point object type " + cpObject.GetType() + " not found!!"); - Console.WriteLine(jsonReport.PrintJson()); - } - } return found; } @@ -2017,6 +2020,12 @@ public void CreateSmartConnector() if (isGeneratingSC) { + if (IsConsoleRunning) + { + Console.WriteLine("Generating Smart Connector ..."); + Progress.SetProgress(90); + Thread.Sleep(1000); + } RaiseConversionProgress(90, "Generating Smart Connector ..."); string cpObjectsJsonFN = "cp_objects.json"; string cpObjectsJsonFP = _targetFolder + Path.DirectorySeparatorChar + cpObjectsJsonFN; diff --git a/NetScreenMigration/ScreenOSConverter.cs b/NetScreenMigration/ScreenOSConverter.cs index 86e1e5d8..857e70c0 100644 --- a/NetScreenMigration/ScreenOSConverter.cs +++ b/NetScreenMigration/ScreenOSConverter.cs @@ -18,11 +18,13 @@ limitations under the License. using CheckPointObjects; using CommonUtils; using MigrationBase; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; +using System.Threading; namespace NetScreenMigration { @@ -3540,6 +3542,15 @@ public override void Initialize(VendorParser vendorParser, string vendorFilePath public override Dictionary Convert(bool convertNat = false) { + if (IsConsoleRunning) + Progress = new ProgressBar(); + + if (IsConsoleRunning) + { + Console.WriteLine("Converting obects ..."); + Progress.SetProgress(20); + Thread.Sleep(1000); + } RaiseConversionProgress(20, "Converting obects ..."); _cpObjects.Initialize(); // must be first!!! @@ -3558,6 +3569,13 @@ public override Dictionary Convert(bool convertNat = false) Add_InterfacesAndRoutes(); Add_or_Modify_InterfaceNetworkGroups(); Add_ZonesNetworkGroups(); + + if (IsConsoleRunning) + { + Console.WriteLine("Converting rules ..."); + Progress.SetProgress(30); + Thread.Sleep(1000); + } RaiseConversionProgress(30, "Converting rules ..."); Convert_policies(); @@ -3567,6 +3585,12 @@ public override Dictionary Convert(bool convertNat = false) } else { + if (IsConsoleRunning) + { + Console.WriteLine("Converting NAT rules ..."); + Progress.SetProgress(40); + Thread.Sleep(1000); + } RaiseConversionProgress(40, "Converting NAT rules ..."); Add_Mip_Nat(); Add_Vip_Nat(); @@ -3574,13 +3598,32 @@ public override Dictionary Convert(bool convertNat = false) Add_PolicyBasedDestNat(); Add_PolicyBasedSrcDestNat(); Add_InterfaceBasedLegacyNat(); + + if (IsConsoleRunning) + { + Console.WriteLine("Creating Firewall rulebase ..."); + Progress.SetProgress(60); + Thread.Sleep(1000); + } RaiseConversionProgress(60, "Creating Firewall rulebase ..."); Add_NatPolicy2RegularPolicy(); } + if (IsConsoleRunning) + { + Console.WriteLine("Validating converted objects ..."); + Progress.SetProgress(70); + Thread.Sleep(1000); + } RaiseConversionProgress(70, "Validating converted objects ..."); EnforceObjectNameValidity(); + if (IsConsoleRunning) + { + Console.WriteLine("Generating CLI scripts ..."); + Progress.SetProgress(80); + Thread.Sleep(1000); + } RaiseConversionProgress(80, "Generating CLI scripts ..."); CreateObjectsHtml(); CreateObjectsScript(); @@ -3595,6 +3638,12 @@ public override Dictionary Convert(bool convertNat = false) ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); CreateSmartConnector(); + + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } return new Dictionary() { { "warnings", ConversionIncidentCategoriesCount } }; } diff --git a/PaloAltoMigration/PaloAltoConverter.cs b/PaloAltoMigration/PaloAltoConverter.cs index 61e6a8ba..28586756 100644 --- a/PaloAltoMigration/PaloAltoConverter.cs +++ b/PaloAltoMigration/PaloAltoConverter.cs @@ -9,6 +9,7 @@ using System.Net; using System.Text; using System.Text.RegularExpressions; +using System.Threading; namespace PaloAltoMigration { @@ -764,9 +765,13 @@ protected override bool AddCheckPointObject(CheckPointObject cpObject) public override Dictionary Convert(bool convertNat) { + string targetFileNameMain = _vendorFileName; string targetFolderMain = _targetFolder; + if (IsConsoleRunning) + Progress = new ProgressBar(); + PA_Config paConfig = _paParser.Config; _isNatConverted = convertNat; @@ -880,7 +885,20 @@ public override Dictionary Convert(bool convertNat) } } + if (IsConsoleRunning) + { + Console.WriteLine("Optimizing Firewall rulebase ..."); + Progress.SetProgress(70); + Thread.Sleep(1000); + } RaiseConversionProgress(70, "Optimizing Firewall rulebase ..."); + + if (IsConsoleRunning) + { + Console.WriteLine("Generating CLI scripts ..."); + Progress.SetProgress(80); + Thread.Sleep(1000); + } RaiseConversionProgress(80, "Generating CLI scripts ..."); VendorHtmlFile = _vendorFilePath; @@ -888,6 +906,12 @@ public override Dictionary Convert(bool convertNat) ObjectsScriptFile = _targetFolder; PolicyScriptFile = _targetFolder; + + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } return new Dictionary() { { "errors", ErrorsInConvertedPackage() }, { "warnings", WarningsInConvertedPackage() } }; } @@ -902,7 +926,20 @@ public void ConvertPaVsysEntry(string targetFolderNew, string targetFileNameNew, Dictionary s_cpAppGroupsDict, Dictionary> s_cpSchedulesDict) { + if (IsConsoleRunning) + { + Console.WriteLine("Convert configuration..."); + Progress.SetProgress(35); + Thread.Sleep(1000); + } RaiseConversionProgress(35, "Convert configuration..."); + + if (IsConsoleRunning) + { + Console.WriteLine("Convert objects..."); + Progress.SetProgress(40); + Thread.Sleep(1000); + } RaiseConversionProgress(40, "Convert objects..."); _cpObjects.Initialize(); // must be first!!! @@ -954,6 +991,12 @@ public void ConvertPaVsysEntry(string targetFolderNew, string targetFileNameNew, Dictionary cpAccessRolesDict = new Dictionary(); + if (IsConsoleRunning) + { + Console.WriteLine("Convert policy..."); + Progress.SetProgress(60); + Thread.Sleep(1000); + } RaiseConversionProgress(60, "Convert policy..."); ConvertSecurityPolicy(paVsysEntry, cpZonesDict, diff --git a/PaloAltoMigration/PanoramaConverter.cs b/PaloAltoMigration/PanoramaConverter.cs index 82ef6039..9a2100e7 100644 --- a/PaloAltoMigration/PanoramaConverter.cs +++ b/PaloAltoMigration/PanoramaConverter.cs @@ -11,6 +11,7 @@ using System.Text.RegularExpressions; using PaloAltoMigration; using System.Security.Cryptography.X509Certificates; +using System.Threading; namespace PanoramaPaloAltoMigration { @@ -856,6 +857,9 @@ public override Dictionary Convert(bool convertNat) string targetFileNameMain = _vendorFileName; string targetFolderMain = _targetFolder; + if (IsConsoleRunning) + Progress = new ProgressBar(); + Panorama_Config paConfig = _paParser.Config; //call method to get divice-group and zones correlation @@ -1032,7 +1036,20 @@ public override Dictionary Convert(bool convertNat) } } + if (IsConsoleRunning) + { + Console.WriteLine("Optimizing Firewall rulebase ..."); + Progress.SetProgress(70); + Thread.Sleep(1000); + } RaiseConversionProgress(70, "Optimizing Firewall rulebase ..."); + + if (IsConsoleRunning) + { + Console.WriteLine("Generating CLI scripts ..."); + Progress.SetProgress(80); + Thread.Sleep(1000); + } RaiseConversionProgress(80, "Generating CLI scripts ..."); VendorHtmlFile = _vendorFilePath; @@ -1040,6 +1057,11 @@ public override Dictionary Convert(bool convertNat) ObjectsScriptFile = _targetFolder; PolicyScriptFile = _targetFolder; + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } return new Dictionary() { { "errors", ErrorsInConvertedPackage() }, { "warnings", WarningsInConvertedPackage() } }; } @@ -1091,8 +1113,22 @@ public void ConvertPaDeviceGroupEntry(string targetFolderNew, string targetFileN List devicesGroupList, Dictionary _devicesUIDDict ) - { + { + + if (IsConsoleRunning) + { + Console.WriteLine("Convert configuration..."); + Progress.SetProgress(35); + Thread.Sleep(1000); + } RaiseConversionProgress(35, "Convert configuration..."); + + if (IsConsoleRunning) + { + Console.WriteLine("Convert objects..."); + Progress.SetProgress(40); + Thread.Sleep(1000); + } RaiseConversionProgress(40, "Convert objects..."); _cpObjects.Initialize(); // must be first!!! @@ -1149,6 +1185,12 @@ Dictionary _devicesUIDDict Dictionary cpAccessRolesDict = new Dictionary(); + if (IsConsoleRunning) + { + Console.WriteLine("Convert policy..."); + Progress.SetProgress(60); + Thread.Sleep(1000); + } RaiseConversionProgress(60, "Convert policy..."); ConvertSecurityPolicy(paDeviceGroupEntry, cpZonesDict, diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index 933a7d2c..20426077 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -12,6 +12,7 @@ using PanoramaPaloAltoMigration; using System.Text.RegularExpressions; using CommonUtils; +using System.Threading; namespace SmartMove { @@ -96,6 +97,8 @@ public string FormatOutput get { return formatOutput; } set { formatOutput = value; } } + + private bool _successCommands = true; #endregion public int DisplayHelp() @@ -236,6 +239,7 @@ public CommandLine Parse(string[] args) //not default value, just for disabling null reference exception during conversion LdapAccountUnit = string.Empty; + for (int i = 0; i < args.Length; i++) { switch (args[i]) @@ -260,6 +264,7 @@ public CommandLine Parse(string[] args) } else { + _successCommands = false; Console.WriteLine("Value for mandatory option -s is not specified! ", MessageTypes.Error); } @@ -271,7 +276,10 @@ public CommandLine Parse(string[] args) if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) this.vendor = args[i + 1]; else + { Console.WriteLine("Value for mandatory option -v is not specified! ", MessageTypes.Error); + _successCommands = false; + } break; } case "-t": @@ -280,7 +288,10 @@ public CommandLine Parse(string[] args) if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) this.targetFolder = args[i + 1]; else + { + _successCommands = false; Console.WriteLine("Value for target folder option -t is not specified. Default value will be set!", MessageTypes.Error); + } break; } case "-d": @@ -289,7 +300,10 @@ public CommandLine Parse(string[] args) if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) this.domain = args[i + 1]; else + { + _successCommands = false; Console.WriteLine("Value for option -d is not specified! ", MessageTypes.Error); + } break; } case "-n": @@ -301,12 +315,23 @@ public CommandLine Parse(string[] args) case "-l": case "--ldap": { - if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) + if (args[i] == args.Last()) { + _successCommands = false; + Console.WriteLine("Value for option -l is not specified! ", MessageTypes.Error); + } + else if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) + { + if (args[i + 1].Contains(' ') || args[i + 1].Length == 0) + { + Console.WriteLine("Value for option -l is not corrected! Spaces and empty string not allowed ", MessageTypes.Error); + _successCommands = false; + } + this.ldapAccountUnit = args[i + 1]; this.ConvertUserConfiguration = true; } - else + else { this.ConvertUserConfiguration = true; //Console.WriteLine("Value for option -u is not specified! ", MessageTypes.Error); @@ -326,7 +351,10 @@ public CommandLine Parse(string[] args) if (new List() { "text", "json" }.Contains(args[i + 1].ToLower())) FormatOutput = args[i + 1]; else + { + _successCommands = false; Console.WriteLine("Value for option format is not corrected! Allow only 'text' or 'json' ", MessageTypes.Error); + } break; } } @@ -340,6 +368,8 @@ public CommandLine Parse(string[] args) */ public void DoMigration(CommandLine commandLine) { + if (!_successCommands) + return; string fileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName); //Console.WriteLine("File name: " + fileName); @@ -429,7 +459,7 @@ public void DoMigration(CommandLine commandLine) try { string ciscoFile = commandLine.ConfigFileName; - Console.WriteLine("Parsing configuration file..."); + Console.Write("Parsing configuration file..."); if (commandLine.Vendor.Equals("Panorama")) { @@ -441,21 +471,22 @@ public void DoMigration(CommandLine commandLine) vendorParser.Parse(ciscoFile); } + Console.WriteLine("Done."); } catch (Exception ex) { if (FormatOutput == "text") { - Console.WriteLine(string.Format("Could not parse configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + Console.WriteLine(string.Format("\nCould not parse configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); return; } else { JsonReport jsonReport = new JsonReport( msg: "Could not parse configuration file.", - err: "err_cannot_convert_configuration_file"); - Console.WriteLine(jsonReport.PrintJson()); + err: "err_cannot_parse_configuration_file"); + Console.WriteLine("\n" + jsonReport.PrintJson()); return; } } @@ -471,7 +502,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unspecified ASA version. The configuration may not parse correctly."); + msg: "Unspecified ASA version. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -483,7 +514,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unsupported ASA version (" + vendorParser.Version + "). This tool supports ASA 8.3 and above configuration files. The configuration may not parse correctly."); + msg: "Unsupported ASA version (" + vendorParser.Version + "). This tool supports ASA 8.3 and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -498,7 +529,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unspecified SRX version. Cannot find SRX version for the selected configuration. The configuration may not parse correctly."); + msg: "Unspecified SRX version. Cannot find SRX version for the selected configuration. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -510,7 +541,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unsupported SRX version (" + vendorParser.Version + "). This tool supports SRX 12.1 and above configuration files. The configuration may not parse correctly."); + msg: "Unsupported SRX version (" + vendorParser.Version + "). This tool supports SRX 12.1 and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -528,7 +559,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unspecified FortiGate version. Cannot find FortiGate version for the selected configuration. The configuration may not parse correctly."); + msg: "Unspecified FortiGate version. Cannot find FortiGate version for the selected configuration. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -540,7 +571,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unsupported FortiGate version (" + vendorParser.Version + "). This tool supports FortiGate 5.x and above configuration files. The configuration may not parse correctly."); + msg: "Unsupported FortiGate version (" + vendorParser.Version + "). This tool supports FortiGate 5.x and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -554,7 +585,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unspecified PaloAlto version. Cannot find PaloAlto PAN-OS version for the selected configuration. The configuration may not parse correctly."); + msg: "Unspecified PaloAlto version. Cannot find PaloAlto PAN-OS version for the selected configuration. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -566,7 +597,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto PAN-OS 7.x and above configuration files. The configuration may not parse correctly."); + msg: "Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto PAN-OS 7.x and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -580,7 +611,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unspecified PaloAlto Panorama version. Cannot find PaloAlto Panorama version for the selected configuration. The configuration may not parse correctly."); + msg: "Unspecified PaloAlto Panorama version. Cannot find PaloAlto Panorama version for the selected configuration. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -592,7 +623,7 @@ public void DoMigration(CommandLine commandLine) else { JsonReport jsonReport = new JsonReport( - msg: "Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto Panorama 7.x and above configuration files. The configuration may not parse correctly."); + msg: "Unsupported PaloAlto version (" + vendorParser.Version + "). This tool supports PaloAlto Panorama 7.x and above configuration files. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); Console.WriteLine(jsonReport.PrintJson()); } return; @@ -652,19 +683,12 @@ public void DoMigration(CommandLine commandLine) } vendorConverter.Initialize(vendorParser, commandLine.ConfigFileName, toolVersion, targetFolder, commandLine.Domain, commandLine.formatOutput); + vendorConverter.IsConsoleRunning = true; try { - Console.Write("Conversion is in progress..."); - //ProgressBar progress = new ProgressBar(); + Console.WriteLine("Conversion started..."); Dictionary results = vendorConverter.Convert(convertNat); - /*for (int i = 0; i <= 100; i+=5) - { - progress.Report((double)i / 100); - Thread.Sleep(20); - } - progress.Report(100); - Console.WriteLine("Done.");*/ if (formatOutput.Equals("text")) { @@ -706,7 +730,7 @@ public void DoMigration(CommandLine commandLine) else { if (FormatOutput == "text") - Console.WriteLine(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + Console.WriteLine("Could not convert configuration file.", MessageTypes.Error); else { JsonReport jsonReport = new JsonReport( @@ -717,6 +741,10 @@ public void DoMigration(CommandLine commandLine) } return; } + finally + { + vendorConverter.Progress.Dispose(); + } vendorConverter.ExportConfigurationAsHtml(); vendorConverter.ExportPolicyPackagesAsHtml(); diff --git a/SmartMove/SmartMove.csproj b/SmartMove/SmartMove.csproj index 5c2b3e1f..8ddf9575 100644 --- a/SmartMove/SmartMove.csproj +++ b/SmartMove/SmartMove.csproj @@ -61,6 +61,7 @@ + ..\packages\System.Windows.Interactivity.WPF.2.0.20525\lib\net40\System.Windows.Interactivity.dll @@ -163,6 +164,10 @@ {2221dbe4-0775-4bbd-9cbc-33a20e0a09e7} CiscoMigration + + {9FF1087A-C314-4B6B-85B6-9BA5B4F14F48} + CommonUtils + {3fa93a97-b484-48ca-a9ea-89fa2e3a6ae3} FortiGateMigration diff --git a/SmartMove/packages.config b/SmartMove/packages.config index 1f01b947..02e8275b 100644 --- a/SmartMove/packages.config +++ b/SmartMove/packages.config @@ -1,4 +1,5 @@  + \ No newline at end of file From f88ab828f5794e1e89047aea7c55ecf422c3643b Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Tue, 15 Jun 2021 14:22:05 +0300 Subject: [PATCH 08/12] Panorama and FortiNet now calculate common errors and warnings during conversion --- FortinetMigration/FortiGateConverter.cs | 8 ++++---- PaloAltoMigration/PanoramaConverter.cs | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/FortinetMigration/FortiGateConverter.cs b/FortinetMigration/FortiGateConverter.cs index 13bd918c..e76e1979 100644 --- a/FortinetMigration/FortiGateConverter.cs +++ b/FortinetMigration/FortiGateConverter.cs @@ -736,8 +736,8 @@ public override Dictionary Convert(bool convertNat) } else //if configuration file contains some VDOM then we can not count Errors, Warnings, Rules and NATs { - _warningsConvertedPackage = -1; - _errorsConvertedPackage = -1; + //_warningsConvertedPackage = -1; + //_errorsConvertedPackage = -1; _rulesInConvertedPackage = -1; _rulesInNatLayer = -1; CleanCheckPointObjectsLists(); @@ -1076,8 +1076,8 @@ public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List ExportNatLayerAsHtml(); ExportPolicyPackagesAsHtmlConfig(); - _warningsConvertedPackage = _warningsList.Count; - _errorsConvertedPackage = _errorsList.Count; + _warningsConvertedPackage += _warningsList.Count; + _errorsConvertedPackage += _errorsList.Count; CreateSmartConnector(); diff --git a/PaloAltoMigration/PanoramaConverter.cs b/PaloAltoMigration/PanoramaConverter.cs index 9a2100e7..bef79575 100644 --- a/PaloAltoMigration/PanoramaConverter.cs +++ b/PaloAltoMigration/PanoramaConverter.cs @@ -1015,8 +1015,8 @@ public override Dictionary Convert(bool convertNat) s_cpNetGroupsDict = s_cpNetGroupsDict.Concat(s_cpNetGroupsDict_Global.Where(x => !s_cpNetGroupsDict.ContainsKey(x.Key))).ToDictionary(x => x.Key, x => x.Value); } - _warningsConvertedPackage = -1; - _errorsConvertedPackage = -1; + //_warningsConvertedPackage = -1; + //_errorsConvertedPackage = -1; _rulesInConvertedPackage = -1; _rulesInNatLayer = -1; CleanCheckPointObjectsLists(); @@ -1241,8 +1241,8 @@ Dictionary _devicesUIDDict ExportNatLayerAsHtml(); - _warningsConvertedPackage = _warningsList.Count; - _errorsConvertedPackage = _errorsList.Count; + _warningsConvertedPackage += _warningsList.Count; + _errorsConvertedPackage += _errorsList.Count; CreateSmartConnector(); From d3b7e86a38289b9194f1e9d508a7117b80904c20 Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Tue, 15 Jun 2021 15:36:58 +0300 Subject: [PATCH 09/12] fix bug with ckipping NAT rules --- SmartMove/CommandLine.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index 20426077..57e434e1 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -309,7 +309,22 @@ public CommandLine Parse(string[] args) case "-n": case "--nat": { - this.convertNat = true; + if (args[i] == args.Last()) + { + _successCommands = false; + Console.WriteLine("Value for option -n is not specified! ", MessageTypes.Error); + } + else if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) + { + bool nat; + if (!bool.TryParse(args[i + 1], out nat)) + { + Console.WriteLine("Value for option -n is not corrected! Only true or false allowed ", MessageTypes.Error); + _successCommands = false; + } + + this.convertNat = nat; + } break; } case "-l": From 206b14a5af31562a8ec54c436b03787b196a7fff Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Tue, 15 Jun 2021 16:02:02 +0300 Subject: [PATCH 10/12] remove console logs from vendors (ConversionIncidents) --- CiscoMigration/CiscoCommands.cs | 23 -------------- CiscoMigration/CiscoConverter.cs | 17 ---------- FortinetMigration/FortiGateConverter.cs | 1 + JuniperMigration/JuniperConverter.cs | 2 -- JuniperMigration/JuniperObjects.cs | 41 ------------------------- 5 files changed, 1 insertion(+), 83 deletions(-) diff --git a/CiscoMigration/CiscoCommands.cs b/CiscoMigration/CiscoCommands.cs index 35d2d6b5..8925df94 100644 --- a/CiscoMigration/CiscoCommands.cs +++ b/CiscoMigration/CiscoCommands.cs @@ -438,7 +438,6 @@ private void ParseNetworks() { ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "An Object (network) can only hold one fqdn, host, range or subnet"; - Console.WriteLine(ConversionIncidentMessage); } } @@ -502,7 +501,6 @@ private void ParseServices() { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Unrecognized service protocol (" + ServiceProtocol + ")"; - Console.WriteLine(ConversionIncidentMessage); } break; } @@ -513,7 +511,6 @@ private void ParseServices() { ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "An Object (service) can only hold one service"; - Console.WriteLine(ConversionIncidentMessage); } } } @@ -546,7 +543,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Invalid host IP address (" + HostAddress + "). Using IP 1.1.1.1."; - Console.WriteLine(ConversionIncidentMessage); HostAddress = "1.1.1.1"; } @@ -578,7 +574,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Invalid IP subnet (" + Network + "/" + Netmask + "). Using IP subnet 1.1.1.0/255.255.255.0."; - Console.WriteLine(ConversionIncidentMessage); Network = "1.1.1.0"; Netmask = "255.255.255.0"; @@ -602,7 +597,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Invalid range starting IP address (" + RangeFrom + "). Using IP 0.0.0.0."; - Console.WriteLine(ConversionIncidentMessage); RangeFrom = "0.0.0.0"; } @@ -612,7 +606,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Invalid range ending IP address (" + RangeTo + "). Using IP 255.255.255.255."; - Console.WriteLine(ConversionIncidentMessage); RangeTo = "255.255.255.255"; } @@ -685,7 +678,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti // "service tcp source eq ssh destination eq ssh" ---> wrong!!! ---> ignore source!!! ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "Cannot convert a service defined as both source service and destination service. Ignoring source service."; - Console.WriteLine(ConversionIncidentMessage); IsDestination = true; Operator = command.GetParam(nextParamId + 1); @@ -724,7 +716,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Unrecognized service protocol (" + Protocol + ")"; - Console.WriteLine(ConversionIncidentMessage); } break; } @@ -767,7 +758,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Invalid IP address (" + IpAddress + "). Using IP 1.1.1.1."; - Console.WriteLine(ConversionIncidentMessage); IpAddress = "1.1.1.1"; } @@ -796,7 +786,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Invalid IP subnet (" + IpAddress + "/" + Netmask + "). Using IP subnet 1.1.1.0/255.255.255.0."; - Console.WriteLine(ConversionIncidentMessage); IpAddress = "1.1.1.0"; Netmask = "255.255.255.0"; @@ -921,7 +910,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti // "service-object tcp source eq ssh destination eq ssh" ---> wrong!!! ---> ignore source!!! ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "Cannot convert a service defined as both source service and destination service. Ignoring source service."; - Console.WriteLine(ConversionIncidentMessage); IsDestination = true; Operator = command.GetParam(nextParamId + 1); @@ -960,7 +948,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Unrecognized service protocol (" + Protocol + ")"; - Console.WriteLine(ConversionIncidentMessage); } break; } @@ -1456,7 +1443,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Invalid IP subnet (" + IpAddress + "/" + Netmask + ")."; - Console.WriteLine(ConversionIncidentMessage); } break; } @@ -1520,7 +1506,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Cannot resolve route destination IP address (" + command.GetParam(2) + "). Using IP 1.1.1.1."; - Console.WriteLine(ConversionIncidentMessage); DestinationIp = "1.1.1.1"; DestinationNetmask = "255.255.255.255"; @@ -1530,7 +1515,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Invalid IP address (" + DestinationIp + "). Using IP 1.1.1.1."; - Console.WriteLine(ConversionIncidentMessage); DestinationIp = "1.1.1.1"; DestinationNetmask = "255.255.255.255"; @@ -1717,7 +1701,6 @@ private void ParseObjectNatCommand(CiscoCommand command, CiscoCommand prevComman ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Unrecognized service protocol (" + ServiceProtocol + ")"; - Console.WriteLine(ConversionIncidentMessage); } } break; @@ -1738,7 +1721,6 @@ private void ParseObjectNatCommand(CiscoCommand command, CiscoCommand prevComman { ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "Interface fall-back for dynamic object NAT is not supported"; - Console.WriteLine(ConversionIncidentMessage); } break; } @@ -1786,7 +1768,6 @@ private void ParseRegularNatCommand(CiscoCommand command, CiscoCommand prevComma { ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "Not handling NAT with dynamic destination"; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -1805,7 +1786,6 @@ private void ParseRegularNatCommand(CiscoCommand command, CiscoCommand prevComma { ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "Not handling NAT with dynamic source"; - Console.WriteLine(ConversionIncidentMessage); } } } @@ -1847,7 +1827,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti break; default: - Console.WriteLine("Error: unknown access-group traffic direction (" + command.GetParam(2) + ")."); break; } @@ -1855,7 +1834,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti { ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "Outbound ACLs will not be converted"; - Console.WriteLine(ConversionIncidentMessage); } } } @@ -2343,7 +2321,6 @@ public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dicti ProtocolReference = strProtocol; ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Unrecognized service protocol (" + strProtocol + ")"; - Console.WriteLine(ConversionIncidentMessage); } break; } diff --git a/CiscoMigration/CiscoConverter.cs b/CiscoMigration/CiscoConverter.cs index 4e87b352..1f49b275 100644 --- a/CiscoMigration/CiscoConverter.cs +++ b/CiscoMigration/CiscoConverter.cs @@ -93,7 +93,6 @@ public string AutoGeneratedName() return "network_" + IpAddress + "_" + MaskPrefix; } - Console.WriteLine("Error: unrecognized network object - Ip={0}, Mask={1}", IpAddress, NetMask); return "_Err_in_network-line_" + CiscoCommandId; } @@ -107,7 +106,6 @@ public string AutoGeneratedNetworkName() return "network_" + IpAddress + "_" + MaskPrefix; } - Console.WriteLine("Error: unrecognized network object - Ip={0}, Mask={1}, Prefix={2}", IpAddress, NetMask, MaskPrefix); return "_Err_in_network-line_" + CiscoCommandId; } @@ -184,10 +182,6 @@ public static ProtocolType ProtocolStringToProtocolType(ref string sProtocol) protocol = ProtocolType.KnownOtherIpProtocol; sProtocol = serviceName; } - else - { - Console.WriteLine("Error: Unrecognized service protocol '{0}'", sProtocol); - } break; } @@ -222,10 +216,6 @@ public static string AutoGeneratedName(CheckPointObjectsRepository cpObjects, st break; default: - if (!string.IsNullOrEmpty(sPortOperator)) - { - Console.WriteLine("Error: unsupported port operator '{0}'", sPortOperator); - } break; } @@ -308,7 +298,6 @@ public static string AutoGeneratedName(CheckPointObjectsRepository cpObjects, Pr } else { - Console.WriteLine("Error: unsupported port operator '{0}' for protocol IP", portOperator); name = "_Err_in_service-line_" + ciscoCommandId; } return name; @@ -319,7 +308,6 @@ public static string AutoGeneratedName(CheckPointObjectsRepository cpObjects, Pr return serviceFound ? name : sPort; case ProtocolType.NA: - Console.WriteLine("Error: Unrecognized service protocol"); return "_Err_in_service-line_" + ciscoCommandId; } @@ -428,10 +416,6 @@ public static CheckPointObject CreateServiceObj(CheckPointObjectsRepository cpOb break; case ProtocolType.Ip: - if (portOperator != TcpUdpPortOperatorType.All) - { - Console.WriteLine("Error: Service protocol is 'IP', but the service is not 'any'"); - } // Skip, a predefined "any" object is used!!! break; @@ -449,7 +433,6 @@ public static CheckPointObject CreateServiceObj(CheckPointObjectsRepository cpOb break; case ProtocolType.NA: - Console.WriteLine("Error: Service protocol is 'NA'"); break; } diff --git a/FortinetMigration/FortiGateConverter.cs b/FortinetMigration/FortiGateConverter.cs index e76e1979..400277d9 100644 --- a/FortinetMigration/FortiGateConverter.cs +++ b/FortinetMigration/FortiGateConverter.cs @@ -921,6 +921,7 @@ public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List { if (IsConsoleRunning) { + Console.WriteLine("Convert configuration for VDOM " + targetFileNameNew); Console.WriteLine("Convert configuration..."); Progress.SetProgress(35); Thread.Sleep(1000); diff --git a/JuniperMigration/JuniperConverter.cs b/JuniperMigration/JuniperConverter.cs index 1c1a2483..bfdfd4ed 100644 --- a/JuniperMigration/JuniperConverter.cs +++ b/JuniperMigration/JuniperConverter.cs @@ -95,7 +95,6 @@ public static CheckPointObject CreateServiceObj(CheckPointObjectsRepository cpOb break; default: - Console.WriteLine("Error: Unknown service protocol '{0}'", sProtocol); return null; } @@ -3048,7 +3047,6 @@ private void MatchNATRulesIntoFirewallPolicy() var parentLayerRuleZone = (CheckPoint_Zone)cpParentRule.Source[0]; if (parentLayerRuleZone == null) { - Console.WriteLine("Ooopppsssss..............."); // shouldn't happen... continue; } diff --git a/JuniperMigration/JuniperObjects.cs b/JuniperMigration/JuniperObjects.cs index 2e97fb8a..6ad52208 100644 --- a/JuniperMigration/JuniperObjects.cs +++ b/JuniperMigration/JuniperObjects.cs @@ -115,7 +115,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing dns name for fqdn object."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -142,7 +141,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing IP address for host object. Using IP 1.1.1.1."; - Console.WriteLine(ConversionIncidentMessage); IpAddress = "1.1.1.1"; return; } @@ -154,7 +152,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IP address '{0}' for host object. Using IP 1.1.1.1.", IpAddress); - Console.WriteLine(ConversionIncidentMessage); IpAddress = "1.1.1.1"; } } @@ -187,7 +184,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IP address '{0}' for network object. Using subnet 1.1.1.0/255.255.255.0.", IpAddress); - Console.WriteLine(ConversionIncidentMessage); IpAddress = "1.1.1.0"; Netmask = "255.255.255.0"; return; @@ -198,7 +194,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Wildcard address is not supported: {0}. Using subnet 1.1.1.0/255.255.255.0.", ipPrefixNode.Value); - Console.WriteLine(ConversionIncidentMessage); IpAddress = "1.1.1.0"; Netmask = "255.255.255.0"; return; @@ -239,7 +234,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid starting IP range '{0}' for range object. Using IP 0.0.0.0.", RangeFrom); - Console.WriteLine(ConversionIncidentMessage); RangeFrom = "0.0.0.0"; } } @@ -257,7 +251,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid ending IP range '{0}' for range object. Using IP 255.255.255.255.", RangeTo); - Console.WriteLine(ConversionIncidentMessage); RangeTo = "255.255.255.255"; } } @@ -331,7 +324,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing IPv4 address for interface object."; - Console.WriteLine(ConversionIncidentMessage); continue; } @@ -340,7 +332,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for interface object.", ipNode.Value); - Console.WriteLine(ConversionIncidentMessage); continue; } @@ -380,13 +371,11 @@ public override void Parse(XElement objectNode, string zoneName) MainIpAddress = firstpAddress; ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = string.Format("Cannot resolve primary nor preferred IP address for interface object. Using a first IP address as a main address."); - Console.WriteLine(ConversionIncidentMessage); } else { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Cannot resolve a main IP address for interface object."); - Console.WriteLine(ConversionIncidentMessage); } } } @@ -408,7 +397,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing IPv4 address for route object. Using IP 1.1.1.1."; - Console.WriteLine(ConversionIncidentMessage); IpAddress = "1.1.1.1"; Netmask = "255.255.255.255"; return; @@ -419,7 +407,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for route object. Using IP 1.1.1.1.", ipNode.Value); - Console.WriteLine(ConversionIncidentMessage); IpAddress = "1.1.1.1"; Netmask = "255.255.255.255"; return; @@ -439,7 +426,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = string.Format("Invalid next hop '{0}' for route object.", nextHopNode.Value); - Console.WriteLine(ConversionIncidentMessage); return; } } @@ -453,7 +439,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = string.Format("Invalid qualified next hop '{0}' for route object.", qualifiedNextHopNode.Value); - Console.WriteLine(ConversionIncidentMessage); return; } } @@ -461,7 +446,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "Missing next hop address for route object."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -527,7 +511,6 @@ private void ParseInternal(XElement objectNode, bool autoGenerateName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing protocol for application object."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -558,7 +541,6 @@ private void ParseInternal(XElement objectNode, bool autoGenerateName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing destination port for application object."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -640,7 +622,6 @@ private void ParseInternal(XElement objectNode, bool autoGenerateName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Unrecognized protocol '{0}' for application object.", Protocol); - Console.WriteLine(ConversionIncidentMessage); } break; } @@ -675,7 +656,6 @@ private void ParseInactivityTimeout(XElement timeoutNode) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid inactivity-timeout '{0}' for application object.", timeout); - Console.WriteLine(ConversionIncidentMessage); } } } @@ -794,7 +774,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing match information for policy rule object."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -803,7 +782,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing action information for policy rule object."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -930,7 +908,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing source zone name for policy object."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -939,7 +916,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing destination zone name for policy object."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -969,7 +945,6 @@ protected PoolAddress ParseAddress(XElement addressNode, bool isSourceNat) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing IPv4 address for NAT pool object."; - Console.WriteLine(ConversionIncidentMessage); return null; } @@ -978,7 +953,6 @@ protected PoolAddress ParseAddress(XElement addressNode, bool isSourceNat) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for NAT pool object.", ipNode.Value); - Console.WriteLine(ConversionIncidentMessage); return null; } @@ -1008,7 +982,6 @@ protected PoolAddress ParseAddress(XElement addressNode, bool isSourceNat) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid ending IP range '{0}' for destination NAT pool object. Using IP 255.255.255.255.", rangeToNode.Value); - Console.WriteLine(ConversionIncidentMessage); address.RangeTo = "255.255.255.255"; } else @@ -1018,7 +991,6 @@ protected PoolAddress ParseAddress(XElement addressNode, bool isSourceNat) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid ending IP range '{0}' for destination NAT pool object. Using IP 255.255.255.255.", rangeToNode.Value); - Console.WriteLine(ConversionIncidentMessage); address.RangeTo = "255.255.255.255"; } else @@ -1064,7 +1036,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for source NAT pool's host address object.", hostAddressBaseNode.Value); - Console.WriteLine(ConversionIncidentMessage); } } @@ -1164,7 +1135,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for source NAT rule's source address object.", sourceAddressNode.Value); - Console.WriteLine(ConversionIncidentMessage); } else { @@ -1195,7 +1165,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for source NAT rule's destination address object.", destAddressNode.Value); - Console.WriteLine(ConversionIncidentMessage); } else { @@ -1290,7 +1259,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for destination NAT rule's source address object.", sourceAddressNode.Value); - Console.WriteLine(ConversionIncidentMessage); } else { @@ -1315,7 +1283,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for destination NAT rule's destination address object.", destAddressNode.Value); - Console.WriteLine(ConversionIncidentMessage); } else { @@ -1405,7 +1372,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for static NAT rule's source address object.", sourceAddressNode.Value); - Console.WriteLine(ConversionIncidentMessage); } else { @@ -1440,7 +1406,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for static NAT rule's destination address object.", destAddressNode.Value); - Console.WriteLine(ConversionIncidentMessage); } else { @@ -1469,7 +1434,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = string.Format("Invalid IPv4 address '{0}' for static NAT rule's prefix object.", prefixNode.Value); - Console.WriteLine(ConversionIncidentMessage); } else { @@ -1546,7 +1510,6 @@ public override void Parse(XElement objectNode, string zoneName) IsRoutingInstanceDefined = true; ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "Not converting source NAT policy object which specifies a routing instance as a source or destination of the traffic."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -1578,7 +1541,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing a source of the traffic for source NAT policy object."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -1604,7 +1566,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing a destination of the traffic for source NAT policy object."; - Console.WriteLine(ConversionIncidentMessage); } } } @@ -1662,7 +1623,6 @@ public override void Parse(XElement objectNode, string zoneName) IsRoutingInstanceDefined = true; ConversionIncidentType = ConversionIncidentType.Informative; ConversionIncidentMessage = "Not converting static NAT policy object which specifies a routing instance as a source of the traffic."; - Console.WriteLine(ConversionIncidentMessage); return; } @@ -1694,7 +1654,6 @@ public override void Parse(XElement objectNode, string zoneName) { ConversionIncidentType = ConversionIncidentType.ManualActionRequired; ConversionIncidentMessage = "Missing a source of the traffic for static NAT policy object."; - Console.WriteLine(ConversionIncidentMessage); } } } From 3f685f23560fb0a708767a07ed39a0a4e29047db Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Tue, 15 Jun 2021 16:09:12 +0300 Subject: [PATCH 11/12] remove ConversionIncident message from console --- JuniperMigration/JuniperParser.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/JuniperMigration/JuniperParser.cs b/JuniperMigration/JuniperParser.cs index 7170ac09..40cad076 100644 --- a/JuniperMigration/JuniperParser.cs +++ b/JuniperMigration/JuniperParser.cs @@ -185,7 +185,6 @@ private bool ParseAddressBooks(XElement configNode) else if (addressBookName != JuniperObject.GlobalZoneName) { // Found non global address-book without a zone attached!!! - Console.WriteLine("Found non global address-book without a zone attached: {0}", addressBookName); continue; } From 7256b71af3c66f9bef2cadbd47de1fe6ef599490 Mon Sep 17 00:00:00 2001 From: EnotRoma Date: Tue, 15 Jun 2021 16:54:47 +0300 Subject: [PATCH 12/12] fix bugs with empty flags -k, -f, -d --- SmartMove/CommandLine.cs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index 57e434e1..b655df56 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -297,7 +297,12 @@ public CommandLine Parse(string[] args) case "-d": case "--domain": { - if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) + if (args[i] == args.Last()) + { + _successCommands = false; + Console.WriteLine("Value for option -d is not specified! ", MessageTypes.Error); + } + else if(args[i] != args.Last() && !args[i + 1].StartsWith("-")) this.domain = args[i + 1]; else { @@ -357,13 +362,33 @@ public CommandLine Parse(string[] args) case "-k": case "--skip": { - this.dontImportUnusedObjects = true; + if (args[i] == args.Last()) + { + _successCommands = false; + Console.WriteLine("Value for option -k is not specified! ", MessageTypes.Error); + } + else if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) + { + bool dontImportUnusedObjectsFlag; + if (!bool.TryParse(args[i + 1], out dontImportUnusedObjectsFlag)) + { + Console.WriteLine("Value for option -k is not corrected! Only true or false allowed ", MessageTypes.Error); + _successCommands = false; + } + + this.dontImportUnusedObjects = dontImportUnusedObjectsFlag; + } break; } case "-f": case "--format": { - if (new List() { "text", "json" }.Contains(args[i + 1].ToLower())) + if (args[i] == args.Last()) + { + _successCommands = false; + Console.WriteLine("Value for option -f is not specified! ", MessageTypes.Error); + } + else if(new List() { "text", "json" }.Contains(args[i + 1].ToLower())) FormatOutput = args[i + 1]; else {