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 00b23789..1f49b275 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 { @@ -92,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; } @@ -106,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; } @@ -183,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; } @@ -221,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; } @@ -307,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; @@ -318,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; } @@ -427,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; @@ -448,7 +433,6 @@ public static CheckPointObject CreateServiceObj(CheckPointObjectsRepository cpOb break; case ProtocolType.NA: - Console.WriteLine("Error: Service protocol is 'NA'"); break; } @@ -522,6 +506,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 +4507,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,19 +4665,29 @@ 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) { + 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!!! @@ -4715,16 +4707,43 @@ public override void 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(); } @@ -4732,8 +4751,21 @@ public override void 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(); @@ -4748,6 +4780,14 @@ public override void Convert(bool convertNat) ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); CreateSmartConnector(); + + + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } + return new Dictionary() { { "warnings", ConversionIncidentCategoriesCount } }; } public override int RulesInConvertedPackage() 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 new file mode 100644 index 00000000..21585480 --- /dev/null +++ b/CommonUtils/JsonReport.cs @@ -0,0 +1,87 @@ +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(Name = "Conversion warnings")] + public int warnings { get; set; } + [DataMember(Name = "Conversion errors")] + 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 = 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) + 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/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 83de468f..400277d9 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 { @@ -19,6 +20,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 +33,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 +85,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 +480,7 @@ public string BuildInspectedRuleInfo(string fortiClassMapName) public void CreateCatalogObjects() { string filename = this.ObjectsHtmlFile; - + using (var file = new StreamWriter(filename, false)) { file.WriteLine(""); @@ -624,10 +627,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 +657,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,13 +714,19 @@ 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; + 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 @@ -710,14 +736,27 @@ public override void 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(); } + 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 @@ -732,14 +771,27 @@ public override void Convert(bool convertNat) } VendorHtmlFile = _vendorFilePath; - + 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; @@ -782,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) @@ -861,7 +919,20 @@ 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 for VDOM " + targetFileNameNew); + 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!!! @@ -890,7 +961,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 +969,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 +1005,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 +1071,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; - + _warningsConvertedPackage += _warningsList.Count; + _errorsConvertedPackage += _errorsList.Count; + CreateSmartConnector(); // to clean; must be the last!!! @@ -1038,7 +1109,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; @@ -1051,15 +1122,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]; @@ -1069,7 +1140,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(); } @@ -1099,12 +1170,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; } @@ -1129,12 +1200,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; } @@ -1839,7 +1910,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); @@ -1847,7 +1918,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) @@ -2037,7 +2108,7 @@ public void AddUserGroup(List fgCommandsList) FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; bool isFSSOService = false; - + string membersStr = ""; foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) @@ -2112,7 +2183,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)) { @@ -2412,16 +2483,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; } } } @@ -2607,7 +2678,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); @@ -2615,7 +2686,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(); @@ -2697,11 +2773,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); } @@ -2752,8 +2828,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; @@ -2772,7 +2848,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); } @@ -2791,17 +2867,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(); @@ -2827,7 +2903,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, @@ -2853,7 +2929,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."); } @@ -2877,7 +2953,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, @@ -2903,7 +2979,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."); } @@ -2935,7 +3011,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) { @@ -2946,7 +3023,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"); } @@ -3056,7 +3133,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]); } @@ -3066,7 +3143,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); } @@ -3094,7 +3171,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]); } @@ -3166,7 +3243,7 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman realRulesList.Add(cpRule); _rulesInConvertedPackage += 1; - + if (cpRuleUG != null) { rootLayer.Rules.Add(cpRuleUG); @@ -3178,7 +3255,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; @@ -3186,12 +3263,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; @@ -3199,7 +3276,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); @@ -3208,7 +3285,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); @@ -3257,8 +3334,8 @@ public void Add_ParentLayer(CheckPoint_Package package, List fgComman } else { - - foreach(string error in errorsList) + + foreach (string error in errorsList) { _errorsList.Add(error); } @@ -3375,7 +3452,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)); @@ -3457,10 +3534,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]; @@ -3486,8 +3563,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; @@ -3562,17 +3639,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 } @@ -3581,7 +3658,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; } @@ -3601,7 +3678,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); } @@ -3609,7 +3686,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; @@ -3621,7 +3698,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; @@ -3632,7 +3709,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; @@ -3650,9 +3727,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]); } @@ -3666,7 +3743,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('"'); } @@ -3682,7 +3759,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; @@ -4041,7 +4118,7 @@ public int AddNatRuleVipNatEnable(FgCommand_Edit fgCommandEdit, string fgDstAddr } } - if(isIpPoolEnabled) + if (isIpPoolEnabled) { foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) { @@ -4391,7 +4468,8 @@ public int AddNatRuleVipNatDisable(FgCommand_Edit fgCommandEdit, string fgDstAdd } } } - else { + else + { foreach (CheckPointObject cpObjSrv in fgServicesList) { CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); @@ -4499,15 +4577,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 += "-"; } @@ -4516,7 +4594,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; @@ -4538,16 +4616,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)) { @@ -4556,16 +4634,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)) { @@ -4583,7 +4661,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; @@ -4598,7 +4676,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; @@ -4607,7 +4685,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; @@ -4639,7 +4717,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; @@ -4651,7 +4729,7 @@ public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObj } #endregion - + public static string GetSafeName(string name) { if (name != null && !name.Trim().Equals("")) @@ -4670,14 +4748,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)); } @@ -4708,4 +4786,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 18bd99d8..bfdfd4ed 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 { @@ -94,7 +95,6 @@ public static CheckPointObject CreateServiceObj(CheckPointObjectsRepository cpOb break; default: - Console.WriteLine("Error: Unknown service protocol '{0}'", sProtocol); return null; } @@ -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 @@ -3046,7 +3047,6 @@ private void MatchNATRulesIntoFirewallPolicy() var parentLayerRuleZone = (CheckPoint_Zone)cpParentRule.Source[0]; if (parentLayerRuleZone == null) { - Console.WriteLine("Ooopppsssss..............."); // shouldn't happen... continue; } @@ -3193,10 +3193,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... @@ -3735,19 +3732,29 @@ 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) { + 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!!! @@ -3762,27 +3769,65 @@ public override void 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(); @@ -3797,8 +3842,15 @@ public override void Convert(bool convertNat) ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); CreateSmartConnector(); + + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } + return new Dictionary() { { "warnings", ConversionIncidentCategoriesCount } }; } - + public override int RulesInConvertedPackage() { return _cpPackages[0].TotalRules(); 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); } } } 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; } diff --git a/MigrationBase/VendorConverter.cs b/MigrationBase/VendorConverter.cs index 5d6b6601..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; @@ -66,7 +67,9 @@ public abstract class VendorConverter protected string _domainName; protected string _policyPackageName; protected string _policyPackageOptimizedName; + protected string _outputFormat; //txt or json protected bool _hasNATConversionIncident = false; + protected bool _calledFromConsole = false; protected CheckPointObjectsRepository _cpObjects = new CheckPointObjectsRepository(); @@ -114,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 @@ -133,12 +149,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 +234,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(); @@ -707,10 +724,6 @@ protected virtual bool AddCheckPointObject(CheckPointObject cpObject) cpObject.ConversionIncidentType = ConversionIncidentType.ManualActionRequired; } } - else - { - Console.WriteLine("Check Point object type " + cpObject.GetType() + " not found!!"); - } return found; } @@ -2007,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 d30cc12b..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 { @@ -669,6 +671,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,19 +3529,28 @@ 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) { + 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!!! @@ -3545,6 +3569,13 @@ public override void 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(); @@ -3554,6 +3585,12 @@ public override void 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(); @@ -3561,13 +3598,32 @@ public override void 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(); @@ -3582,6 +3638,13 @@ public override void Convert(bool convertNat = false) ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); CreateSmartConnector(); + + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } + return new Dictionary() { { "warnings", ConversionIncidentCategoriesCount } }; } public override int RulesInConvertedPackage() diff --git a/PaloAltoMigration/PaloAltoConverter.cs b/PaloAltoMigration/PaloAltoConverter.cs index e1bb6e4e..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 { @@ -46,6 +47,8 @@ public class PaloAltoConverter : VendorConverter private Dictionary cpPredefServicesTypes = new Dictionary(); + private string outputFormat = ""; + #endregion #region Constants @@ -731,14 +734,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,11 +763,15 @@ 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; + if (IsConsoleRunning) + Progress = new ProgressBar(); + PA_Config paConfig = _paParser.Config; _isNatConverted = convertNat; @@ -877,13 +885,34 @@ public override void 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; ObjectsScriptFile = _targetFolder; PolicyScriptFile = _targetFolder; + + + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } + return new Dictionary() { { "errors", ErrorsInConvertedPackage() }, { "warnings", WarningsInConvertedPackage() } }; } public void ConvertPaVsysEntry(string targetFolderNew, string targetFileNameNew, PA_VsysEntry paVsysEntry, @@ -897,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!!! @@ -949,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 3010ec75..bef79575 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 { @@ -50,6 +51,8 @@ public class PanoramaConverter : VendorConverter private Dictionary cpPredefServicesTypes = new Dictionary(); + private string outputFormat = ""; + #endregion #region Constants @@ -745,14 +748,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,11 +852,14 @@ 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; + if (IsConsoleRunning) + Progress = new ProgressBar(); + Panorama_Config paConfig = _paParser.Config; //call method to get divice-group and zones correlation @@ -1008,8 +1015,8 @@ public override void 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(); @@ -1029,13 +1036,33 @@ public override void 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; ObjectsScriptFile = _targetFolder; PolicyScriptFile = _targetFolder; + + if (IsConsoleRunning) + { + Progress.SetProgress(100); + Progress.Dispose(); + } + return new Dictionary() { { "errors", ErrorsInConvertedPackage() }, { "warnings", WarningsInConvertedPackage() } }; } /// @@ -1086,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!!! @@ -1144,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, @@ -1194,8 +1241,8 @@ Dictionary _devicesUIDDict ExportNatLayerAsHtml(); - _warningsConvertedPackage = _warningsList.Count; - _errorsConvertedPackage = _errorsList.Count; + _warningsConvertedPackage += _warningsList.Count; + _errorsConvertedPackage += _errorsList.Count; CreateSmartConnector(); diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs index 725ea214..b655df56 100644 --- a/SmartMove/CommandLine.cs +++ b/SmartMove/CommandLine.cs @@ -11,6 +11,8 @@ using PaloAltoMigration; using PanoramaPaloAltoMigration; using System.Text.RegularExpressions; +using CommonUtils; +using System.Threading; namespace SmartMove { @@ -18,7 +20,7 @@ namespace SmartMove /// Represents command line logic /// class CommandLine - { + { private string[] arguments { get; set; } public CommandLine(string[] args) @@ -27,14 +29,14 @@ 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 { get { return configFileName; } set { configFileName = value; } } - + //–v CiscoASA private string vendor { get; set; } public string Vendor @@ -50,7 +52,7 @@ public string TargetFolder get { return targetFolder; } set { targetFolder = value; } } - + //-d domain private string domain { get; set; } public string Domain @@ -67,7 +69,7 @@ public bool ConvertNat set { convertNat = value; } } - //-u unit1 + //-l unit1 private string ldapAccountUnit { get; set; } public string LdapAccountUnit { @@ -81,32 +83,42 @@ 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; } + } + + private bool _successCommands = true; #endregion 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] [-k]"); 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" + "-i" + "\t" + "do not import unused objects (for FortiNet, PaloAlto and Panorama only)"); + 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" + @"(""-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" + "-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; } @@ -122,35 +134,35 @@ 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("Option -s is mandatory but not specified.", 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)) { 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 -l 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 -help\"", MessageTypes.Error); + 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; } @@ -159,8 +171,8 @@ 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("Value for option -l is not specified!"); + Console.WriteLine("For command help run \"SmartMove.exe -h or --help\"", MessageTypes.Error); return 0; } @@ -189,7 +201,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 +209,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 +221,10 @@ public string[] regenerateArgs(string commandLineString) { finalArgs.Add(item); } - + } - args = finalArgs.ToArray(); - + args = finalArgs.ToArray(); + return args; } @@ -220,85 +232,174 @@ public string[] regenerateArgs(string commandLineString) * Parses input options and writes its values to ComamndLine class fields */ public CommandLine Parse(string[] args) - { - for (int i = 0; i < args.Length; i++) - { + { + //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++) + { switch (args[i]) { - case "-f": + 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); - } + _successCommands = false; + Console.WriteLine("Value for mandatory option -s is not specified! ", MessageTypes.Error); + } break; } case "-v": + case "--vendor": { 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); + _successCommands = false; + } 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 + { + _successCommands = false; Console.WriteLine("Value for target folder option -t is not specified. Default value will be set!", MessageTypes.Error); + } break; } 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 + { + _successCommands = false; Console.WriteLine("Value for option -d is not specified! ", MessageTypes.Error); + } break; } 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 "-u": + 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); } - + + break; + } + case "-k": + case "--skip": + { + 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 "-i": + case "-f": + case "--format": { - this.dontImportUnusedObjects = true; + 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 + { + _successCommands = false; + Console.WriteLine("Value for option format is not corrected! Allow only 'text' or 'json' ", MessageTypes.Error); + } break; - } - } - } - return this; + } + } + } + return this; } /* @@ -307,39 +408,73 @@ public CommandLine Parse(string[] args) */ public void DoMigration(CommandLine commandLine) { - + if (!_successCommands) + return; + 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); + if (FormatOutput == "text") + Console.WriteLine("Configuration file is not selected.", MessageTypes.Error); + else + { + JsonReport jsonReport = new JsonReport( + msg: "Configuration file is not selected.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } 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 + { + JsonReport jsonReport = new JsonReport( + msg: "Cannot find configuration file.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } 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 + { + 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; } - + 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 + { + JsonReport jsonReport = new JsonReport( + msg: "Cannot find target folder for conversion output.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } return; } VendorParser vendorParser; - switch (commandLine.Vendor) + switch (commandLine.Vendor) { - case "CiscoASA": + case "CiscoASA": vendorParser = new CiscoParser(); break; case "JuniperSRX": @@ -351,8 +486,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(); @@ -362,10 +497,10 @@ 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")) { PanoramaParser panParser = (PanoramaParser)vendorParser; @@ -375,11 +510,25 @@ public void DoMigration(CommandLine commandLine) { vendorParser.Parse(ciscoFile); } + + Console.WriteLine("Done."); + } 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("\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_parse_configuration_file"); + Console.WriteLine("\n" + jsonReport.PrintJson()); + return; + } } #region check middleware version @@ -388,12 +537,26 @@ 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 + { + JsonReport jsonReport = new JsonReport( + msg: "Unspecified ASA version. The configuration may not parse correctly.", err: "err_unsupported_version_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } 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 + { + 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.", err: "err_unsupported_version_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } return; } break; @@ -401,12 +564,26 @@ 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 + { + JsonReport jsonReport = new JsonReport( + 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; } 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 + { + 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.", err: "err_unsupported_version_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } return; } break; @@ -417,59 +594,101 @@ 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 + { + JsonReport jsonReport = new JsonReport( + 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; } 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 + { + 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.", err: "err_unsupported_version_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } 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 + { + JsonReport jsonReport = new JsonReport( + 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; } 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 + { + 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.", err: "err_unsupported_version_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } 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 + { + JsonReport jsonReport = new JsonReport( + 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; } 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 + { + 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.", err: "err_unsupported_version_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } return; } break; } #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": @@ -490,7 +709,7 @@ public void DoMigration(CommandLine commandLine) paConverter.OptimizeConf = commandLine.DontImportUnusedObjects; paConverter.ConvertUserConf = commandLine.ConvertUserConfiguration; paConverter.LDAPAccoutUnit = ldapAccountUnit; - vendorConverter = paConverter; + vendorConverter = paConverter; break; case "Panorama": PanoramaConverter panoramaConverter = new PanoramaConverter(); @@ -503,36 +722,76 @@ 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); + vendorConverter.IsConsoleRunning = true; + try { - Console.WriteLine("Conversion is in progress..."); - vendorConverter.Convert(convertNat); - Console.WriteLine("Conversion is finished."); + Console.WriteLine("Conversion started..."); + Dictionary results = vendorConverter.Convert(convertNat); + + 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) { 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 + { + 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 { - 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("Could not convert configuration file.", MessageTypes.Error); + else + { + JsonReport jsonReport = new JsonReport( + msg: "Could not convert configuration file.", + err: "err_cannot_convert_configuration_file"); + Console.WriteLine(jsonReport.PrintJson()); + } } return; - } - - vendorConverter.ExportConfigurationAsHtml(); - vendorConverter.ExportPolicyPackagesAsHtml(); + } + finally + { + vendorConverter.Progress.Dispose(); + } + + vendorConverter.ExportConfigurationAsHtml(); + vendorConverter.ExportPolicyPackagesAsHtml(); if (commandLine.ConvertNat) { - vendorConverter.ExportNatLayerAsHtml(); - } + vendorConverter.ExportNatLayerAsHtml(); + } } } } diff --git a/SmartMove/MainWindow.xaml.cs b/SmartMove/MainWindow.xaml.cs index 95a741ca..db11e3be 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: @@ -609,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(); } diff --git a/SmartMove/SmartMove.csproj b/SmartMove/SmartMove.csproj index 8f88ad71..8ddf9575 100644 --- a/SmartMove/SmartMove.csproj +++ b/SmartMove/SmartMove.csproj @@ -59,16 +59,13 @@ ..\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 - + - + + ..\packages\System.Windows.Interactivity.WPF.2.0.20525\lib\net40\System.Windows.Interactivity.dll + @@ -145,6 +142,7 @@ ResXFileCodeGenerator Resources.Designer.cs + SettingsSingleFileGenerator Settings.Designer.cs @@ -166,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 new file mode 100644 index 00000000..02e8275b --- /dev/null +++ b/SmartMove/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file