diff --git a/CheckPointObjects/CP_KnownServiceGroups.csv b/CheckPointObjects/CP_KnownServiceGroups.csv index 5f7475b0..6a55c730 100644 --- a/CheckPointObjects/CP_KnownServiceGroups.csv +++ b/CheckPointObjects/CP_KnownServiceGroups.csv @@ -48,4 +48,5 @@ "StoneBeat" "time" "Trojan_Services" -"Yahoo_Messenger" \ No newline at end of file +"Yahoo_Messenger" +"Mail" \ No newline at end of file diff --git a/CheckPointObjects/CheckPointObjects.cs b/CheckPointObjects/CheckPointObjects.cs index fc7f99ac..fc391e4f 100644 --- a/CheckPointObjects/CheckPointObjects.cs +++ b/CheckPointObjects/CheckPointObjects.cs @@ -1,986 +1,1073 @@ -/******************************************************************** -Copyright (c) 2017, Check Point Software Technologies Ltd. -All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -********************************************************************/ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Text.RegularExpressions; -using CommonUtils; - -namespace CheckPointObjects -{ - /// - /// Represents a basic Check Point object. - /// Exposes properties for the name and comments for the object, and validates their values. - /// Each derived object must implement the methods for CLI scripts generation. - /// - public abstract class CheckPointObject - { - /// - /// Regex: replace any char that is NOT any of the following to "_" char - /// - protected const string NameValidityRegex = @"[^A-Za-z0-9_.-]"; - - /// - /// Regex: replace any char that is NOT any of the following to "_" char - /// - protected const string CommentsValidityRegex = @"[^A-Za-z0-9 @#*$(){}\[\]_.\-=:,/]"; - - public const string Any = "any"; - public const string All_Internet = "All_Internet"; - public const string icmpProtocol = "icmp-proto"; - - public string Name { get; set; } - - public string SafeName() - { - return GetSafeName(Name); - } - - private string _comments = ""; - public string Comments - { - get { return Regex.Replace(_comments, CommentsValidityRegex, "_"); } - set { _comments = value; } - } - - // The Tag property is used as a general data placeholder. - public string Tag { get; set; } - - /// - /// A collection of object tag names. - /// - public List Tags = new List(); - - // the type of CheckPoint object, is used for JSON representation - public string TypeName - { - get { return this.GetType().Name; } - } - - public int ConvertedCommandId { get; set; } - public ConversionIncidentType ConversionIncidentType { get; set; } - - public virtual IPRanges GetIPRanges() - { - return new IPRanges(); - } - - public abstract string ToCLIScript(); - - public abstract string ToCLIScriptInstruction(); - - protected static string GetSafeName(string name) - { - return Regex.Replace(name, NameValidityRegex, "_"); - } - - protected static string WriteParam(string paramName, bool paramValue, bool defaultValue) - { - if (paramValue == defaultValue) - { - return ""; - } - - return paramName + " \"" + paramValue.ToString().ToLower() + "\" "; - } - - protected static string WriteParam(string paramName, string paramValue, string defaultValue) - { - if (paramValue == defaultValue || paramValue == null) - { - return ""; - } - - return paramName + " \"" + paramValue + "\" "; - } - - protected static string WriteListParam(string paramName, List paramValues, bool useSafeNames) - { - if (paramValues.Count == 0) - { - return ""; - } - - if (paramValues.Count == 1) - { - return WriteParam(paramName, paramValues[0], ""); - } - - string str = ""; - int i = 0; - - foreach (string paramValue in paramValues) - { - string val = paramValue; - if (useSafeNames) - { - val = GetSafeName(paramValue); - } - - str += string.Format("{0}.{1} \"{2}\" ", paramName, i, val); - i++; - } - - return str; - } - - protected static string WriteListParamWithIndexes(string paramName, List paramValues, bool useSafeNames, int i = 0) - { - if (paramValues.Count == 0) - { - return ""; - } - - string str = ""; - - foreach (string paramValue in paramValues) - { - string val = paramValue; - if (useSafeNames) - { - val = GetSafeName(paramValue); - } - - str += string.Format("{0}.{1} \"{2}\" ", paramName, i, val); - i++; - } - - return str; - } - } - - public class CheckPoint_PredifinedObject : CheckPointObject - { - public override string ToCLIScript() - { - return ""; - } - - public override string ToCLIScriptInstruction() - { - return ""; - } - } - - public class CheckPoint_Zone : CheckPointObject - { - public override string ToCLIScript() - { - return "add security-zone " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create zone [" + Name + "]"; - } - } - - public class CheckPoint_Domain : CheckPointObject - { - public string Fqdn { get; set; } - public bool IsSubDomain { get; set; } - - public override string ToCLIScript() - { - return "add dns-domain " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("is-sub-domain", IsSubDomain, !IsSubDomain) //"is-sub-domain" is a required field by documentation - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create domain [" + Name + "]"; - } - } - - public class CheckPoint_Host : CheckPointObject - { - public string IpAddress { get; set; } - - public override IPRanges GetIPRanges() - { - return new IPRanges(new IPRange(IPAddress.Parse(IpAddress))); - } - - public override string ToCLIScript() - { - return "add host " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("ip-address", IpAddress, "") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create host [" + Name + "] with ip-address [" + IpAddress + "]"; - } - } - - public class CheckPoint_Network : CheckPointObject - { - public string Subnet { get; set; } - public string Netmask { get; set; } - - public override IPRanges GetIPRanges() - { - return new IPRanges(new IPRange(IPNetwork.Parse(Subnet, Netmask))); - } - - public override string ToCLIScript() - { - return "add network " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("subnet", Subnet, "") - + WriteParam("subnet-mask", Netmask , "") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create network [" + Name + "]: subnet [" + Subnet + "] mask [" + Netmask + "]"; - } - } - - public class CheckPoint_Range : CheckPointObject - { - public string RangeFrom { get; set; } - public string RangeTo { get; set; } - - public override IPRanges GetIPRanges() - { - return new IPRanges(new IPRange(IPAddress.Parse(RangeFrom), IPAddress.Parse(RangeTo))); - } - - public override string ToCLIScript() - { - return "add address-range " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("ipv4-address-first", RangeFrom, "") - + WriteParam("ipv4-address-last", RangeTo, "") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create address range [" + Name + "]: from [" + RangeFrom + "] to [" + RangeTo + "]"; - } - } - - public class CheckPoint_NetworkGroup : CheckPointObject - { - public List Members = new List(); - - /// - /// This property is used to overcome the problematic order of objects creation for - /// GroupWithExclusion and NetworkGroup types cross-referencing each other. - /// - public bool CreateAfterGroupsWithExclusion { get; set; } - - public override string ToCLIScript() - { - return "add group " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteListParam("members", Members, true) - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create network group [" + Name + "]: " + Members.Count + " members"; - } - } - - public class CheckPoint_GroupWithExclusion : CheckPointObject - { - public string Include { get; set; } - public string Except { get; set; } - - public override string ToCLIScript() - { - return "add group-with-exclusion " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("include", Include, "") - + WriteParam("except", Except, "") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create group with exclusion [" + Name + "]: Include: " + Include + ", Except: " + Except; - } - } - - public class CheckPoint_SimpleGateway : CheckPointObject - { - public string IpAddress { get; set; } - - public override string ToCLIScript() - { - return "add simple-gateway " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("ip-address", IpAddress, "") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create simple gateway [" + Name + "] with ip-address [" + IpAddress + "]"; - } - } - - public class CheckPoint_UdpService : CheckPointObject - { - public string Port { get; set; } - public string SourcePort { get; set; } - public string SessionTimeout { get; set; } - - public override string ToCLIScript() - { - return "add service-udp " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("port", Port, "") - + WriteParam("source-port", SourcePort, "") - + WriteParam("session-timeout", SessionTimeout, "0") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create udp service [" + Name + "]: port [" + Port + "]"; - } - } - - public class CheckPoint_TcpService : CheckPointObject - { - public string Port { get; set; } - public string SourcePort { get; set; } - public string SessionTimeout { get; set; } - - public override string ToCLIScript() - { - return "add service-tcp " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("port", Port, "") - + WriteParam("source-port", SourcePort, "") - + WriteParam("session-timeout", SessionTimeout, "0") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create tcp service [" + Name + "]: port [" + Port + "]"; - } - } - - public class CheckPoint_SctpService : CheckPointObject - { - public string Port { get; set; } - public string SourcePort { get; set; } - public string SessionTimeout { get; set; } - - public override string ToCLIScript() - { - return "add service-sctp " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("port", Port, "") - + WriteParam("source-port", SourcePort, "") - + WriteParam("session-timeout", SessionTimeout, "0") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create sctp service [" + Name + "]: port [" + Port + "]"; - } - } - - public class CheckPoint_IcmpService : CheckPointObject - { - public string Type { get; set; } - public string Code { get; set; } - - public override string ToCLIScript() - { - return "add service-icmp " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("icmp-type", Type, "0") - + WriteParam("icmp-code", Code, "0") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create icmp service [" + Name + "]: type [" + Type + "] code [" + Code + "]"; - } - } - - public class CheckPoint_RpcService : CheckPointObject - { - public string ProgramNumber { get; set; } - - public override string ToCLIScript() - { - return "add service-rpc " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("program-number", ProgramNumber, "") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create rpc service [" + Name + "]: program-number [" + ProgramNumber + "]"; - } - } - - public class CheckPoint_DceRpcService : CheckPointObject - { - public string InterfaceUuid { get; set; } - - public override string ToCLIScript() - { - return "add service-dce-rpc " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("interface-uuid", InterfaceUuid, "") - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create dce-rpc service [" + Name + "]: interface-uuid [" + InterfaceUuid + "]"; - } - } - - public class CheckPoint_OtherService : CheckPointObject - { - public string IpProtocol { get; set; } - - public override string ToCLIScript() - { - return "add service-other " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteParam("ip-protocol", IpProtocol, "") - + WriteParam("match-for-any", true, false) - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create other service [" + Name + "]: IP protocol [" + IpProtocol + "]"; - } - } - - public class CheckPoint_ServiceGroup : CheckPointObject - { - public List Members = new List(); - - public override string ToCLIScript() - { - return "add service-group " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteListParam("members", Members, true) - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create service group [" + Name + "]: " + Members.Count + " members"; - } - } - - public class CheckPoint_ApplicationGroup : CheckPointObject - { - public List Members = new List(); - - public override string ToCLIScript() - { - return "add application-site-group " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteListParam("members", Members, false) - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create application group [" + Name + "]: " + Members.Count + " members"; - } - } - - public class CheckPoint_Time : CheckPointObject - { - public enum Weekdays { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; - public enum RecurrencePatternEnum { None, Daily, Weekly, Monthly }; - - public bool StartNow { get; set; } - public string StartDate { get; set; } - public string StartTime { get; set; } - public double StartPosix { get; set; } - - public bool EndNever { get; set; } - public string EndDate { get; set; } - public string EndTime { get; set; } - public double EndPosix { get; set; } - - public bool HoursRangesEnabled_1 { get; set; } - public string HoursRangesFrom_1 { get; set; } - public string HoursRangesTo_1 { get; set; } - - public bool HoursRangesEnabled_2 { get; set; } - public string HoursRangesFrom_2 { get; set; } - public string HoursRangesTo_2 { get; set; } - - public bool HoursRangesEnabled_3 { get; set; } - public string HoursRangesFrom_3 { get; set; } - public string HoursRangesTo_3 { get; set; } - - public RecurrencePatternEnum RecurrencePattern { get; set; } - - public List RecurrenceWeekdays = new List(); - - public override string ToCLIScript() - { - return "add time " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - - + WriteParam("start-now", StartNow.ToString().ToLower(), "") - + WriteParam("start.date", StartDate, "") - + WriteParam("start.time", StartTime, "") - + WriteParam("start.posix", (StartPosix > 0 ? "" + StartPosix : ""), "") - - + WriteParam("end-never", EndNever.ToString().ToLower(), "") - + WriteParam("end.date", EndDate, "") - + WriteParam("end.time", EndTime, "") - + WriteParam("end.posix", (EndPosix > 0 ? "" + EndPosix : ""), "") - - + WriteParam("hours-ranges.1.enabled", (HoursRangesEnabled_1 ? HoursRangesEnabled_1.ToString().ToLower() : ""), "") - + WriteParam("hours-ranges.1.from", HoursRangesFrom_1, "") - + WriteParam("hours-ranges.1.to", HoursRangesTo_1, "") - - + WriteParam("hours-ranges.2.enabled", (HoursRangesEnabled_2 ? HoursRangesEnabled_2.ToString().ToLower() : ""), "") - + WriteParam("hours-ranges.2.from", HoursRangesFrom_2, "") - + WriteParam("hours-ranges.2.to", HoursRangesTo_2, "") - - + WriteParam("hours-ranges.3.enabled", (HoursRangesEnabled_3 ? HoursRangesEnabled_3.ToString().ToLower() : ""), "") - + WriteParam("hours-ranges.3.from", HoursRangesFrom_3, "") - + WriteParam("hours-ranges.3.to", HoursRangesTo_3, "") - - + WriteParam("recurrence.pattern", ((RecurrenceWeekdays.Count > 0 || RecurrencePattern == RecurrencePatternEnum.Weekly) ? "Weekly" : ""), "") - + WriteParam("recurrence.pattern", ((RecurrencePattern == RecurrencePatternEnum.Daily) ? "Daily" : ""), "") - + WriteParam("recurrence.pattern", ((RecurrencePattern == RecurrencePatternEnum.Monthly) ? "Monthly" : ""), "") - + WriteListParamWithIndexes("recurrence.weekdays", (from o in RecurrenceWeekdays select o.ToString()).ToList(), true) - - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create time [" + Name + "]"; - } - } - - public class CheckPoint_TimeGroup : CheckPointObject - { - public List Members = new List(); - - public override string ToCLIScript() - { - return "add time-group " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") - + WriteListParam("members", Members, true) - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create time group [" + Name + "]: " + Members.Count + " members"; - } - } - - public class AccessRoleUser - { - public string Name { get; set; } - public string BaseDn { get; set; } - } - - public class CheckPoint_AccessRole : CheckPointObject - { - public List Networks = new List(); - public List Users = new List(); - - public override string ToCLIScript() - { - if(Networks.Count == 0) - { - Networks.Add("any"); - } - return "add access-role " - + WriteParam("name", SafeName(), "") - + WriteListParam("networks", Networks, true) - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create access role [" + Name + "]: " + Users.Count + " users"; - } - } - - public class CheckPoint_Rule : CheckPointObject - { - public enum ActionType { Accept, Drop, Reject, SubPolicy }; - public enum TrackTypes { None, Log }; - - public const string SubPolicyCleanupRuleName = "Sub-Policy Cleanup rule"; - - public bool Enabled { get; set; } - public string Layer { get; set; } - public string SubPolicyName { get; set; } - public ActionType Action { get; set; } - public TrackTypes Track { get; set; } - public bool SourceNegated { get; set; } - public bool DestinationNegated { get; set; } - - private string _conversionComments; - public string ConversionComments - { - get { return Regex.Replace(_conversionComments, CommentsValidityRegex, "_"); } - set { _conversionComments = value; } - } - - public List Source = new List(); - public List Destination = new List(); - public List Service = new List(); - public List Time = new List(); - - public CheckPoint_Rule() - { - Enabled = true; - Layer = ""; - SubPolicyName = ""; - Action = ActionType.Drop; - Track = TrackTypes.Log; - SourceNegated = false; - DestinationNegated = false; - ConversionComments = ""; - } - - public override string ToCLIScript() - { - string actionName = ""; - - switch (Action) - { - case ActionType.Accept: - actionName = "accept"; - break; - case ActionType.Drop: - actionName = "drop"; - break; - case ActionType.Reject: - actionName = "reject"; - break; - case ActionType.SubPolicy: - actionName = "apply layer"; - break; - } - - return "add access-rule " + WriteParam("layer", Layer, "") + WriteParam("comments", Comments, "") - + WriteListParam("source", (from o in Source select o.Name).ToList(), true) - + WriteListParam("destination", (from o in Destination select o.Name).ToList(), true) - + WriteListParam("service", (from o in Service select o.Name).ToList(), true) - + WriteParamWithIndexesForApplications() - + WriteListParam("time", (from o in Time select o.Name).ToList(), true) - + WriteParam("action", actionName, "") - + WriteParam("track-settings.type", Track.ToString(), "") - + WriteParam("enabled", Enabled, true) - + WriteParam("source-negate", SourceNegated, false) - + WriteParam("destination-negate", DestinationNegated, false) - + WriteParam("position", "top", "") - + WriteParam("inline-layer", SubPolicyName, "") - + WriteParam("name", Name, "") - + WriteParam("custom-fields.field-1", ConversionComments.Substring(0, Math.Min(ConversionComments.Length, 150)), ""); - } - - public override string ToCLIScriptInstruction() - { - return ""; - } - - public CheckPoint_Rule Clone() - { - var newRule = new CheckPoint_Rule(); - newRule.Name = Name; - newRule.Comments = Comments; - newRule.Enabled = Enabled; - newRule.Layer = Layer; - newRule.SubPolicyName = SubPolicyName; - newRule.Action = Action; - newRule.Track = Track; - newRule.SourceNegated = SourceNegated; - newRule.DestinationNegated = DestinationNegated; - newRule.ConvertedCommandId = ConvertedCommandId; - newRule.ConversionIncidentType = ConversionIncidentType; - - foreach(CheckPointObject obj in Source) - { - newRule.Source.Add(obj); - } - foreach (CheckPointObject obj in Destination) - { - newRule.Destination.Add(obj); - } - foreach (CheckPointObject obj in Service) - { - newRule.Service.Add(obj); - } - foreach (CheckPointObject obj in Time) - { - newRule.Time.Add(obj); - } - CloneApplicationsToRule(newRule); - - return newRule; - } - - public bool CompareTo(CheckPoint_Rule other) - { - if (Enabled != other.Enabled || - Action != other.Action || - Track != other.Track || - SourceNegated != other.SourceNegated || - DestinationNegated != other.DestinationNegated) - { - return false; - } - - if ((Time.Count != other.Time.Count) || - (Time.Count > 0 && other.Time.Count > 0 && Time[0].Name != other.Time[0].Name)) - { - return false; - } - - bool sourceMatch = CompareLists(Source, other.Source); - bool destMatch = CompareLists(Destination, other.Destination); - bool serviceMatch = CompareLists(Service, other.Service); - bool applicationMatch = CompareApplications(other); - - return sourceMatch && destMatch && serviceMatch && applicationMatch; - } - - public bool IsCleanupRule() - { - if (!string.IsNullOrEmpty(Name) && Name == SubPolicyCleanupRuleName) - { - return true; // sub-policy's automatic cleanup rule - } - - if ((Source.Count == 1 && Source[0].Name == Any) && - (Destination.Count == 1 && Destination[0].Name == Any) && - (Service.Count == 1 && Service[0].Name == Any) && - IsApplicationsClean() && - (Action == ActionType.Drop)) - { - return true; // user defined cleanup rule - } - - return false; - } - - protected static bool CompareLists(IEnumerable items1, IEnumerable items2) - { - var list1 = (from o in items1 select o.Name).ToList(); - var list2 = (from o in items2 select o.Name).ToList(); - - var firstNotSecond = list1.Except(list2).ToList(); - var secondNotFirst = list2.Except(list1).ToList(); - - return (!firstNotSecond.Any() && !secondNotFirst.Any()); - } - - //WriteParamWithIndexesForApplications will be overridden in the derived class if the class needs specific implementation for applications - //return null because this object doesn't handle with applications. - protected virtual string WriteParamWithIndexesForApplications() - { - return null; - } - - //CloneApplicationsToRule will be overridden in the derived class if the class needs specific clone implementation for applications - //in this class the function empty because it doesn't handle with applications in services. - protected virtual void CloneApplicationsToRule(CheckPoint_Rule newRule) - { - return; - } - - //CompareApplications will be overridden in the derived class if the class needs specific compare implementation for applications - //this function returns true so the CompareTo function won't be affected. - protected virtual bool CompareApplications(CheckPoint_Rule other) - { - return true; - } - - //IsApplicationsClean will be overridden in the derived class if the class needs specific check for cleanup rule - ////this function returns true so the IsCleanupRule function won't be affected. - protected virtual bool IsApplicationsClean() - { - return true; - } - } - - //In Check Point rules - both applications and services are part of "service" filed in the rule. - //This class used for rules that contains applications in the services list. - public class CheckPoint_RuleWithApplication : CheckPoint_Rule - { - //this is the vendor's responsibility to separate the applications from the services. - public List Application = new List(); - - //Since applications can include spaces and services can't, we first get services with safe names - //and then applications without safe names with the right index so it will be continue the services indexing. - protected override string WriteParamWithIndexesForApplications() - { - return WriteListParamWithIndexes("service", (from o in Application select o.Name).ToList(), false, Service.Count); - } - - //specific extension for cloning applications - protected override void CloneApplicationsToRule(CheckPoint_Rule newRule) - { - if (newRule is CheckPoint_RuleWithApplication) { - foreach (CheckPointObject obj in Application) - { - ((CheckPoint_RuleWithApplication)newRule).Application.Add(obj); - } - } - } - - //specific extension for comparing applications - protected override bool CompareApplications(CheckPoint_Rule other) - { - if (other is CheckPoint_RuleWithApplication) - { - return CompareLists(Application, ((CheckPoint_RuleWithApplication)other).Application); - } - - return false; - } - - //specific extension to check if the applications list contains only ANY parameter. - protected override bool IsApplicationsClean() - { - return (Application.Count == 1 && Application[0].Name == Any); - } - - } - - public class CheckPoint_Layer : CheckPointObject - { - public List Rules = new List(); - public bool ApplicationsAndUrlFiltering { get; set; } - public bool Shared { get; set; } - - public override string ToCLIScript() - { - return "add access-layer " + WriteParam("name", Name, "") + WriteParam("comments", Comments, "") - + WriteParam("add-default-rule", false, true) - + WriteParam("applications-and-url-filtering", ApplicationsAndUrlFiltering, false) - + WriteParam("shared", Shared, false) - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create layer [" + Name + "]"; - } - } - - public class CheckPoint_NAT_Rule : CheckPointObject - { - public enum NatMethod { Static, Hide }; - - public bool Enabled { get; set; } - public string Package { get; set; } - public NatMethod Method { get; set; } - public object VendorCustomData { get; set; } - - public CheckPointObject Source; - public CheckPointObject Destination; - public CheckPointObject Service; - public CheckPointObject TranslatedSource; - public CheckPointObject TranslatedDestination; - public CheckPointObject TranslatedService; - - public CheckPoint_NAT_Rule() - { - Enabled = true; - } - - public override string ToCLIScript() - { - return "add nat-rule " + WriteParam("package", Package, "") - + WriteParam("original-source", (Source != null) ? Source.Name : "", "") - + WriteParam("original-destination", (Destination != null) ? Destination.Name : "", "") - + WriteParam("original-service", (Service != null) ? Service.Name : "", "") - + WriteParam("translated-source", (TranslatedSource != null) ? TranslatedSource.Name : "", "") - + WriteParam("translated-destination", (TranslatedDestination != null) ? TranslatedDestination.Name : "", "") - + WriteParam("translated-service", (TranslatedService != null) ? TranslatedService.Name : "", "") - + WriteParam("comments", Comments, "") - + WriteParam("method", Method.ToString().ToLower(), "") - + WriteParam("enabled", Enabled, true) - + WriteParam("position", "top", ""); - } - - public override string ToCLIScriptInstruction() - { - return ""; - } - - public CheckPoint_NAT_Rule Clone() - { - var newRule = new CheckPoint_NAT_Rule(); - newRule.Name = Name; - newRule.Comments = Comments; - newRule.Enabled = Enabled; - newRule.Method = Method; - newRule.Source = Source; - newRule.Destination = Destination; - newRule.Service = Service; - newRule.TranslatedSource = TranslatedSource; - newRule.TranslatedDestination = TranslatedDestination; - newRule.TranslatedService = TranslatedService; - newRule.ConvertedCommandId = ConvertedCommandId; - newRule.ConversionIncidentType = ConversionIncidentType; - - return newRule; - } - } - - public class CheckPoint_Package : CheckPointObject - { - public string NameOfAccessLayer - { - get { return Name + " Network"; } - } - - public CheckPoint_Layer ParentLayer = new CheckPoint_Layer(); - public List SubPolicies = new List(); - - public override string ToCLIScript() - { - return "add package " + WriteParam("name", Name, "") - + WriteParam("threat-prevention", false, true) - + WriteListParam("tags", Tags, true); - } - - public override string ToCLIScriptInstruction() - { - return "create package [" + Name + "]"; - } - - public int TotalRules() - { - int count = ParentLayer.Rules.Count(); - foreach (var layer in SubPolicies) - { - count += layer.Rules.Count(); - } - return count; - } - } -} +/******************************************************************** +Copyright (c) 2017, Check Point Software Technologies Ltd. +All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +********************************************************************/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text.RegularExpressions; +using CommonUtils; + +namespace CheckPointObjects +{ + /// + /// Represents a basic Check Point object. + /// Exposes properties for the name and comments for the object, and validates their values. + /// Each derived object must implement the methods for CLI scripts generation. + /// + public abstract class CheckPointObject + { + /// + /// Regex: replace any char that is NOT any of the following to "_" char + /// + protected const string NameValidityRegex = @"[^A-Za-z0-9_.-]"; + + /// + /// Regex: replace any char that is NOT any of the following to "_" char + /// + protected const string CommentsValidityRegex = @"[^A-Za-z0-9 @#*$(){}\[\]_.\-=:,/]"; + + public const string Any = "any"; + public const string All = "All"; + public const string All_Internet = "All_Internet"; + public const string icmpProtocol = "icmp-proto"; + + public string Name { get; set; } + + public string SafeName() + { + return GetSafeName(Name); + } + + private string _comments = ""; + public string Comments + { + get { return Regex.Replace(_comments, CommentsValidityRegex, "_"); } + set { _comments = value; } + } + + // The Tag property is used as a general data placeholder. + public string Tag { get; set; } + + /// + /// A collection of object tag names. + /// + public List Tags = new List(); + + // the type of CheckPoint object, is used for JSON representation + public string TypeName + { + get { return this.GetType().Name; } + } + + public int ConvertedCommandId { get; set; } + public ConversionIncidentType ConversionIncidentType { get; set; } + + public virtual IPRanges GetIPRanges() + { + return new IPRanges(); + } + + public abstract string ToCLIScript(); + + public abstract string ToCLIScriptInstruction(); + + protected static string GetSafeName(string name) + { + return Regex.Replace(name, NameValidityRegex, "_"); + } + + //escaping quote sign in script + public List EscapeQuote(List members) + { + List resultList = new List(); + foreach (string member in members) + { + if (member.IndexOf("\'") != -1) + resultList.Add(member.Replace("\'", "\'\\\'\'")); + else + resultList.Add(member); + } + return resultList; + } + + protected static string WriteParam(string paramName, bool paramValue, bool defaultValue) + { + if (paramValue == defaultValue) + { + return ""; + } + + return paramName + " \"" + paramValue.ToString().ToLower() + "\" "; + } + + protected static string WriteParam(string paramName, string paramValue, string defaultValue) + { + if (paramValue == defaultValue || paramValue == null) + { + return ""; + } + + return paramName + " \"" + paramValue + "\" "; + } + + protected static string WriteListParam(string paramName, List paramValues, bool useSafeNames) + { + if (paramValues.Count == 0) + { + return ""; + } + + if (paramValues.Count == 1) + { + return WriteParam(paramName, paramValues[0], ""); + } + + string str = ""; + int i = 0; + + foreach (string paramValue in paramValues) + { + string val = paramValue; + if (useSafeNames) + { + val = GetSafeName(paramValue); + } + + str += string.Format("{0}.{1} \"{2}\" ", paramName, i, val); + i++; + } + + return str; + } + + protected static string WriteListParamWithIndexes(string paramName, List paramValues, bool useSafeNames, int i = 0) + { + if (paramValues.Count == 0) + { + return ""; + } + + string str = ""; + + foreach (string paramValue in paramValues) + { + string val = paramValue; + if (useSafeNames) + { + val = GetSafeName(paramValue); + } + + str += string.Format("{0}.{1} \"{2}\" ", paramName, i, val); + i++; + } + + return str; + } + } + + public class CheckPoint_PredifinedObject : CheckPointObject + { + public override string ToCLIScript() + { + return ""; + } + + public override string ToCLIScriptInstruction() + { + return ""; + } + } + + public class CheckPoint_Zone : CheckPointObject + { + public override string ToCLIScript() + { + return "add security-zone " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create zone [" + Name + "]"; + } + } + + public class CheckPoint_Domain : CheckPointObject + { + public string Fqdn { get; set; } + public bool IsSubDomain { get; set; } + + public override string ToCLIScript() + { + return "add dns-domain " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("is-sub-domain", IsSubDomain, !IsSubDomain) //"is-sub-domain" is a required field by documentation + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create domain [" + Name + "]"; + } + } + + public class CheckPoint_Host : CheckPointObject + { + public string IpAddress { get; set; } + + public override IPRanges GetIPRanges() + { + return new IPRanges(new IPRange(IPAddress.Parse(IpAddress))); + } + + public override string ToCLIScript() + { + return "add host " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("ip-address", IpAddress, "") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create host [" + Name + "] with ip-address [" + IpAddress + "]"; + } + } + + public class CheckPoint_Network : CheckPointObject + { + public string Subnet { get; set; } + public string Netmask { get; set; } + + public override IPRanges GetIPRanges() + { + return new IPRanges(new IPRange(IPNetwork.Parse(Subnet, Netmask))); + } + + public override string ToCLIScript() + { + return "add network " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("subnet", Subnet, "") + + WriteParam("subnet-mask", Netmask , "") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create network [" + Name + "]: subnet [" + Subnet + "] mask [" + Netmask + "]"; + } + } + + public class CheckPoint_Range : CheckPointObject + { + public string RangeFrom { get; set; } + public string RangeTo { get; set; } + + public override IPRanges GetIPRanges() + { + return new IPRanges(new IPRange(IPAddress.Parse(RangeFrom), IPAddress.Parse(RangeTo))); + } + + public override string ToCLIScript() + { + return "add address-range " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("ipv4-address-first", RangeFrom, "") + + WriteParam("ipv4-address-last", RangeTo, "") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create address range [" + Name + "]: from [" + RangeFrom + "] to [" + RangeTo + "]"; + } + } + + public class CheckPoint_NetworkGroup : CheckPointObject + { + public List Members = new List(); + + public bool IsPanoramaDeviceGroup = false; + + /// + /// This property is used to overcome the problematic order of objects creation for + /// GroupWithExclusion and NetworkGroup types cross-referencing each other. + /// + public bool CreateAfterGroupsWithExclusion { get; set; } + + public override string ToCLIScript() + { + return "add group " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteListParam("members", Members, true) + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create network group [" + Name + "]: " + Members.Count + " members"; + } + } + + public class CheckPoint_GroupWithExclusion : CheckPointObject + { + public string Include { get; set; } + public string Except { get; set; } + + public override string ToCLIScript() + { + return "add group-with-exclusion " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("include", Include, "") + + WriteParam("except", Except, "") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create group with exclusion [" + Name + "]: Include: " + Include + ", Except: " + Except; + } + } + + public class CheckPoint_SimpleGateway : CheckPointObject + { + public string IpAddress { get; set; } + + public override string ToCLIScript() + { + return "add simple-gateway " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("ip-address", IpAddress, "") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create simple gateway [" + Name + "] with ip-address [" + IpAddress + "]"; + } + } + + public class CheckPoint_UdpService : CheckPointObject + { + public string Port { get; set; } + public string SourcePort { get; set; } + public string SessionTimeout { get; set; } + + public override string ToCLIScript() + { + return "add service-udp " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("port", Port, "") + + WriteParam("source-port", SourcePort, "") + + WriteParam("session-timeout", SessionTimeout, "0") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create udp service [" + Name + "]: port [" + Port + "]"; + } + } + + public class CheckPoint_TcpService : CheckPointObject + { + public string Port { get; set; } + public string SourcePort { get; set; } + public string SessionTimeout { get; set; } + + public override string ToCLIScript() + { + return "add service-tcp " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("port", Port, "") + + WriteParam("source-port", SourcePort, "") + + WriteParam("session-timeout", SessionTimeout, "0") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create tcp service [" + Name + "]: port [" + Port + "]"; + } + } + + public class CheckPoint_SctpService : CheckPointObject + { + public string Port { get; set; } + public string SourcePort { get; set; } + public string SessionTimeout { get; set; } + + public override string ToCLIScript() + { + return "add service-sctp " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("port", Port, "") + + WriteParam("source-port", SourcePort, "") + + WriteParam("session-timeout", SessionTimeout, "0") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create sctp service [" + Name + "]: port [" + Port + "]"; + } + } + + public class CheckPoint_IcmpService : CheckPointObject + { + public string Type { get; set; } + public string Code { get; set; } + + public override string ToCLIScript() + { + return "add service-icmp " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("icmp-type", Type, "0") + + WriteParam("icmp-code", Code, "0") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create icmp service [" + Name + "]: type [" + Type + "] code [" + Code + "]"; + } + } + + public class CheckPoint_RpcService : CheckPointObject + { + public string ProgramNumber { get; set; } + + public override string ToCLIScript() + { + return "add service-rpc " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("program-number", ProgramNumber, "") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create rpc service [" + Name + "]: program-number [" + ProgramNumber + "]"; + } + } + + public class CheckPoint_DceRpcService : CheckPointObject + { + public string InterfaceUuid { get; set; } + + public override string ToCLIScript() + { + return "add service-dce-rpc " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("interface-uuid", InterfaceUuid, "") + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create dce-rpc service [" + Name + "]: interface-uuid [" + InterfaceUuid + "]"; + } + } + + public class CheckPoint_OtherService : CheckPointObject + { + public string IpProtocol { get; set; } + + public override string ToCLIScript() + { + return "add service-other " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteParam("ip-protocol", IpProtocol, "") + + WriteParam("match-for-any", true, false) + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create other service [" + Name + "]: IP protocol [" + IpProtocol + "]"; + } + } + + public class CheckPoint_ServiceGroup : CheckPointObject + { + public List Members = new List(); + + public override string ToCLIScript() + { + return "add service-group " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteListParam("members", Members, true) + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create service group [" + Name + "]: " + Members.Count + " members"; + } + } + + public class CheckPoint_ApplicationGroup : CheckPointObject + { + public List Members = new List(); + + public override string ToCLIScript() + { + List members = EscapeQuote(Members);//escaping quote sign in script + + return "add application-site-group " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteListParam("members", members, false) + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create application group [" + Name + "]: " + Members.Count + " members"; + } + } + + public class CheckPoint_Time : CheckPointObject + { + public enum Weekdays { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; + public enum RecurrencePatternEnum { None, Daily, Weekly, Monthly }; + + public bool StartNow { get; set; } + public string StartDate { get; set; } + public string StartTime { get; set; } + public double StartPosix { get; set; } + + public bool EndNever { get; set; } + public string EndDate { get; set; } + public string EndTime { get; set; } + public double EndPosix { get; set; } + + public bool HoursRangesEnabled_1 { get; set; } + public string HoursRangesFrom_1 { get; set; } + public string HoursRangesTo_1 { get; set; } + + public bool HoursRangesEnabled_2 { get; set; } + public string HoursRangesFrom_2 { get; set; } + public string HoursRangesTo_2 { get; set; } + + public bool HoursRangesEnabled_3 { get; set; } + public string HoursRangesFrom_3 { get; set; } + public string HoursRangesTo_3 { get; set; } + + public RecurrencePatternEnum RecurrencePattern { get; set; } + + public List RecurrenceWeekdays = new List(); + + public override string ToCLIScript() + { + return "add time " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + + WriteParam("start-now", StartNow.ToString().ToLower(), "") + + WriteParam("start.date", StartDate, "") + + WriteParam("start.time", StartTime, "") + + WriteParam("start.posix", (StartPosix > 0 ? "" + StartPosix : ""), "") + + + WriteParam("end-never", EndNever.ToString().ToLower(), "") + + WriteParam("end.date", EndDate, "") + + WriteParam("end.time", EndTime, "") + + WriteParam("end.posix", (EndPosix > 0 ? "" + EndPosix : ""), "") + + + WriteParam("hours-ranges.1.enabled", (HoursRangesEnabled_1 ? HoursRangesEnabled_1.ToString().ToLower() : ""), "") + + WriteParam("hours-ranges.1.from", HoursRangesFrom_1, "") + + WriteParam("hours-ranges.1.to", HoursRangesTo_1, "") + + + WriteParam("hours-ranges.2.enabled", (HoursRangesEnabled_2 ? HoursRangesEnabled_2.ToString().ToLower() : ""), "") + + WriteParam("hours-ranges.2.from", HoursRangesFrom_2, "") + + WriteParam("hours-ranges.2.to", HoursRangesTo_2, "") + + + WriteParam("hours-ranges.3.enabled", (HoursRangesEnabled_3 ? HoursRangesEnabled_3.ToString().ToLower() : ""), "") + + WriteParam("hours-ranges.3.from", HoursRangesFrom_3, "") + + WriteParam("hours-ranges.3.to", HoursRangesTo_3, "") + + + WriteParam("recurrence.pattern", ((RecurrenceWeekdays.Count > 0 || RecurrencePattern == RecurrencePatternEnum.Weekly) ? "Weekly" : ""), "") + + WriteParam("recurrence.pattern", ((RecurrencePattern == RecurrencePatternEnum.Daily) ? "Daily" : ""), "") + + WriteParam("recurrence.pattern", ((RecurrencePattern == RecurrencePatternEnum.Monthly) ? "Monthly" : ""), "") + + WriteListParamWithIndexes("recurrence.weekdays", (from o in RecurrenceWeekdays select o.ToString()).ToList(), true) + + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create time [" + Name + "]"; + } + + public CheckPoint_Time Clone() + { + var newTime = new CheckPoint_Time(); + + newTime.Name = Name; + newTime.Comments = Comments; + newTime.StartNow = StartNow; + newTime.StartDate = StartDate; + newTime.StartTime = StartTime; + newTime.StartPosix = StartPosix; + newTime.EndNever = EndNever; + newTime.EndDate = EndDate; + newTime.EndTime = EndTime; + newTime.EndPosix = EndPosix; + + newTime.HoursRangesEnabled_1 = HoursRangesEnabled_1; + newTime.HoursRangesFrom_1 = HoursRangesFrom_1; + newTime.HoursRangesTo_1 = HoursRangesTo_1; + + newTime.HoursRangesEnabled_2 = HoursRangesEnabled_2; + newTime.HoursRangesFrom_2 = HoursRangesFrom_2; + newTime.HoursRangesTo_2 = HoursRangesTo_2; + + newTime.HoursRangesEnabled_3 = HoursRangesEnabled_3; + newTime.HoursRangesFrom_3 = HoursRangesFrom_3; + newTime.HoursRangesTo_3 = HoursRangesTo_3; + + newTime.RecurrencePattern = RecurrencePattern; + newTime.RecurrenceWeekdays = RecurrenceWeekdays; + + return newTime; + } + } + + public class CheckPoint_TimeGroup : CheckPointObject + { + public List Members = new List(); + + public override string ToCLIScript() + { + return "add time-group " + WriteParam("name", SafeName(), "") + WriteParam("comments", Comments, "") + + WriteListParam("members", Members, true) + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create time group [" + Name + "]: " + Members.Count + " members"; + } + } + + public class AccessRoleUser + { + public string Name { get; set; } + public string BaseDn { get; set; } + } + + public class CheckPoint_AccessRole : CheckPointObject + { + public List Networks = new List(); + public List Users = new List(); + + public override string ToCLIScript() + { + if(Networks.Count == 0) + { + Networks.Add("any"); + } + return "add access-role " + + WriteParam("name", SafeName(), "") + + WriteListParam("networks", Networks, true) + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create access role [" + Name + "]: " + Users.Count + " users"; + } + } + + public class CheckPoint_Rule : CheckPointObject + { + public enum ActionType { Accept, Drop, Reject, SubPolicy }; + public enum TrackTypes { None, Log }; + + public const string SubPolicyCleanupRuleName = "Sub-Policy Cleanup rule"; + + public bool Enabled { get; set; } + public string Layer { get; set; } + public string SubPolicyName { get; set; } + public ActionType Action { get; set; } + public TrackTypes Track { get; set; } + public bool SourceNegated { get; set; } + public bool DestinationNegated { get; set; } + + public List Target = new List();//"install-on" parameter of CP rule + public bool TargetNegated { get; set; } + + private string _conversionComments; + public string ConversionComments + { + get { return Regex.Replace(_conversionComments, CommentsValidityRegex, "_"); } + set { _conversionComments = value; } + } + + public List Source = new List(); + public List Destination = new List(); + public List Service = new List(); + public List Time = new List(); + + public CheckPoint_Rule() + { + Enabled = true; + Layer = ""; + SubPolicyName = ""; + Action = ActionType.Drop; + Track = TrackTypes.Log; + SourceNegated = false; + DestinationNegated = false; + ConversionComments = ""; + } + + public override string ToCLIScript() + { + string actionName = ""; + + switch (Action) + { + case ActionType.Accept: + actionName = "accept"; + break; + case ActionType.Drop: + actionName = "drop"; + break; + case ActionType.Reject: + actionName = "reject"; + break; + case ActionType.SubPolicy: + actionName = "apply layer"; + break; + } + + return "add access-rule " + WriteParam("layer", Layer, "") + WriteParam("comments", Comments, "") + + WriteListParam("source", (from o in Source select o.Name).ToList(), true) + + WriteListParam("destination", (from o in Destination select o.Name).ToList(), true) + + WriteServicesParams() + + WriteParamWithIndexesForApplications() + + WriteListParam("time", (from o in Time select o.Name).ToList(), true) + + WriteParam("action", actionName, "") + + WriteParam("track-settings.type", Track.ToString(), "") + + WriteParam("enabled", Enabled, true) + + WriteParam("source-negate", SourceNegated, false) + + WriteParam("destination-negate", DestinationNegated, false) + + WriteParam("position", "top", "") + + WriteParam("inline-layer", SubPolicyName, "") + + WriteParam("name", Name, "") + + WriteListParam("install-on", (from o in Target select o).ToList(), true) + + WriteParam("custom-fields.field-1", ConversionComments.Substring(0, Math.Min(ConversionComments.Length, 150)), ""); + } + + public override string ToCLIScriptInstruction() + { + return ""; + } + + public CheckPoint_Rule Clone() + { + var newRule = new CheckPoint_Rule(); + newRule.Name = Name; + newRule.Comments = Comments; + newRule.Enabled = Enabled; + newRule.Layer = Layer; + newRule.SubPolicyName = SubPolicyName; + newRule.Action = Action; + newRule.Track = Track; + newRule.SourceNegated = SourceNegated; + newRule.DestinationNegated = DestinationNegated; + newRule.ConvertedCommandId = ConvertedCommandId; + newRule.ConversionIncidentType = ConversionIncidentType; + + foreach(CheckPointObject obj in Source) + { + newRule.Source.Add(obj); + } + foreach (CheckPointObject obj in Destination) + { + newRule.Destination.Add(obj); + } + foreach (CheckPointObject obj in Service) + { + newRule.Service.Add(obj); + } + foreach (CheckPointObject obj in Time) + { + newRule.Time.Add(obj); + } + foreach (string obj in Target) + { + newRule.Target.Add(obj); + } + CloneApplicationsToRule(newRule); + + return newRule; + } + + public bool CompareTo(CheckPoint_Rule other) + { + if (Enabled != other.Enabled || + Action != other.Action || + Track != other.Track || + SourceNegated != other.SourceNegated || + DestinationNegated != other.DestinationNegated) + { + return false; + } + + if ((Time.Count != other.Time.Count) || + (Time.Count > 0 && other.Time.Count > 0 && Time[0].Name != other.Time[0].Name)) + { + return false; + } + + bool sourceMatch = CompareLists(Source, other.Source); + bool destMatch = CompareLists(Destination, other.Destination); + bool serviceMatch = CompareLists(Service, other.Service); + bool applicationMatch = CompareApplications(other); + + return sourceMatch && destMatch && serviceMatch && applicationMatch; + } + + public bool IsCleanupRule() + { + if (!string.IsNullOrEmpty(Name) && Name == SubPolicyCleanupRuleName) + { + return true; // sub-policy's automatic cleanup rule + } + return checkRuleType(ActionType.Drop);// user defined cleanup rule + } + + /// + /// Verifies if the rule allows all traffic (which means rule has source: Any, destination: Any, service: Any and action: Accept) + /// + /// + public bool IsAllowAnyRule() + { + return checkRuleType(ActionType.Accept);// user defined Allow Any rule + } + + private bool checkRuleType(ActionType actionType) + { + if ((Source.Count == 1 && Source[0].Name == Any || Source.Count == 0) && + (Destination.Count == 1 && Destination[0].Name == Any || Destination.Count == 0) && + (Service.Count == 1 && Service[0].Name == Any || Service.Count == 0) && + IsApplicationsClean() && + (Action == actionType)) + { + return true; + } + return false; + } + + protected static bool CompareLists(IEnumerable items1, IEnumerable items2) + { + var list1 = (from o in items1 select o.Name).ToList(); + var list2 = (from o in items2 select o.Name).ToList(); + + var firstNotSecond = list1.Except(list2).ToList(); + var secondNotFirst = list2.Except(list1).ToList(); + + return (!firstNotSecond.Any() && !secondNotFirst.Any()); + } + + //WriteParamWithIndexesForApplications will be overridden in the derived class if the class needs specific implementation for applications + //return null because this object doesn't handle with applications. + protected virtual string WriteParamWithIndexesForApplications() + { + return null; + } + + protected virtual string WriteServicesParams() + { + return WriteListParam("service", (from o in Service select o.Name).ToList(), true); + } + + //CloneApplicationsToRule will be overridden in the derived class if the class needs specific clone implementation for applications + //in this class the function empty because it doesn't handle with applications in services. + protected virtual void CloneApplicationsToRule(CheckPoint_Rule newRule) + { + return; + } + + //CompareApplications will be overridden in the derived class if the class needs specific compare implementation for applications + //this function returns true so the CompareTo function won't be affected. + protected virtual bool CompareApplications(CheckPoint_Rule other) + { + return true; + } + + //IsApplicationsClean will be overridden in the derived class if the class needs specific check for cleanup rule + ////this function returns true so the IsCleanupRule function won't be affected. + protected virtual bool IsApplicationsClean() + { + return true; + } + } + + //In Check Point rules - both applications and services are part of "service" filed in the rule. + //This class used for rules that contains applications in the services list. + public class CheckPoint_RuleWithApplication : CheckPoint_Rule + { + //this is the vendor's responsibility to separate the applications from the services. + public List Application = new List(); + + //Since applications can include spaces and services can't, we first get services with safe names + //and then applications without safe names with the right index so it will be continue the services indexing. + protected override string WriteParamWithIndexesForApplications() + { + return WriteListParamWithIndexes("service", (from o in Application select o.Name).ToList(), false, Service.Count); + } + + protected override string WriteServicesParams() + { + return WriteListParamWithIndexes("service", (from o in Service select o.Name).ToList(), true, 0);//add indexes to services in case applications present as well + } + + //specific extension for cloning applications + protected override void CloneApplicationsToRule(CheckPoint_Rule newRule) + { + if (newRule is CheckPoint_RuleWithApplication) { + foreach (CheckPointObject obj in Application) + { + ((CheckPoint_RuleWithApplication)newRule).Application.Add(obj); + } + } + } + + //specific extension for comparing applications + protected override bool CompareApplications(CheckPoint_Rule other) + { + if (other is CheckPoint_RuleWithApplication) + { + return CompareLists(Application, ((CheckPoint_RuleWithApplication)other).Application); + } + + return false; + } + + //specific extension to check if the applications list contains only ANY parameter. + protected override bool IsApplicationsClean() + { + return (Application.Count == 1 && Application[0].Name == Any || Application.Count == 0); + } + + } + + public class CheckPoint_Layer : CheckPointObject + { + public List Rules = new List(); + public bool ApplicationsAndUrlFiltering { get; set; } + public bool Shared { get; set; } + + public override string ToCLIScript() + { + return "add access-layer " + WriteParam("name", Name, "") + WriteParam("comments", Comments, "") + + WriteParam("add-default-rule", false, true) + + WriteParam("applications-and-url-filtering", ApplicationsAndUrlFiltering, false) + + WriteParam("shared", Shared, false) + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create layer [" + Name + "]"; + } + } + + public class CheckPoint_NAT_Rule : CheckPointObject + { + public enum NatMethod { Static, Hide }; + + public bool Enabled { get; set; } + public string Package { get; set; } + public NatMethod Method { get; set; } + public object VendorCustomData { get; set; } + + public CheckPointObject Source; + public CheckPointObject Destination; + public CheckPointObject Service; + public CheckPointObject TranslatedSource; + public CheckPointObject TranslatedDestination; + public CheckPointObject TranslatedService; + + public List Target = new List(); + + public CheckPoint_NAT_Rule() + { + Enabled = true; + } + + public override string ToCLIScript() + { + return "add nat-rule " + WriteParam("package", Package, "") + + WriteParam("original-source", (Source != null) ? Source.Name : "", "") + + WriteParam("original-destination", (Destination != null) ? Destination.Name : "", "") + + WriteParam("original-service", (Service != null) ? Service.Name : "", "") + + WriteParam("translated-source", (TranslatedSource != null) ? TranslatedSource.Name : "", "") + + WriteParam("translated-destination", (TranslatedDestination != null) ? TranslatedDestination.Name : "", "") + + WriteParam("translated-service", (TranslatedService != null) ? TranslatedService.Name : "", "") + + WriteParam("comments", Comments, "") + + WriteParam("method", Method.ToString().ToLower(), "") + + WriteParam("enabled", Enabled, true) + + WriteParam("position", "top", "") + + WriteListParam("install-on", (from o in Target select o).ToList(), true); + + } + + public override string ToCLIScriptInstruction() + { + return ""; + } + + public CheckPoint_NAT_Rule Clone() + { + var newRule = new CheckPoint_NAT_Rule(); + newRule.Name = Name; + newRule.Comments = Comments; + newRule.Enabled = Enabled; + newRule.Method = Method; + newRule.Source = Source; + newRule.Destination = Destination; + newRule.Service = Service; + newRule.TranslatedSource = TranslatedSource; + newRule.TranslatedDestination = TranslatedDestination; + newRule.TranslatedService = TranslatedService; + newRule.ConvertedCommandId = ConvertedCommandId; + newRule.ConversionIncidentType = ConversionIncidentType; + newRule.Target = Target; + + return newRule; + } + } + + public class CheckPoint_Package : CheckPointObject + { + public string NameOfAccessLayer + { + get { return Name + " Network"; } + } + + public CheckPoint_Layer ParentLayer = new CheckPoint_Layer(); + public List SubPolicies = new List(); + + public override string ToCLIScript() + { + return "add package " + WriteParam("name", Name, "") + + WriteParam("threat-prevention", false, true) + + WriteListParam("tags", Tags, true); + } + + public override string ToCLIScriptInstruction() + { + return "create package [" + Name + "]"; + } + + public int TotalRules() + { + int count = ParentLayer.Rules.Count(); + foreach (var layer in SubPolicies) + { + count += layer.Rules.Count(); + } + return count; + } + } +} diff --git a/CiscoMigration/CiscoCommands.cs b/CiscoMigration/CiscoCommands.cs index 33123a18..f9cbffc3 100644 --- a/CiscoMigration/CiscoCommands.cs +++ b/CiscoMigration/CiscoCommands.cs @@ -1,2375 +1,2375 @@ -/******************************************************************** -Copyright (c) 2017, Check Point Software Technologies Ltd. -All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -********************************************************************/ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using CommonUtils; - -namespace CiscoMigration -{ - public enum ProtocolType { NA, Ip, Icmp, Udp, Tcp, KnownOtherIpProtocol, ReferenceObject }; - public enum TcpUdpPortOperatorType { NA, All, Lt, Gt, Eq, Neq, Range, ReferenceObject }; - public enum ServiceDirection { Source, Destination }; - - public interface ICiscoCommand - { - string Name(); - void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases); - } - - /// - /// Represents a basic Cisco command. - /// Each derived command auto-parses the appropriate configuration line text according to its "name" (via reflection mechanism). - /// Some commands may have child commands (network group commad has child network object commands). - /// The "Id" property is the configuration line number. - /// The "ParentId" property is the parent configuration line number. - /// The "CiscoId" property is the user defined name of the command. - /// - public class CiscoCommand : ICiscoCommand - { - public const string InterfacePrefix = "Interface_"; - public const string Any = "any"; - - private string _text = ""; - private string[] _words; - - public string Text - { - get { return _text; } - set - { - _text = value; - - string trimmedText = _text.Trim(); - char[] delimiterChars = { ' ', '\t' }; - - // Replace multiple spaces with a single space - trimmedText = Regex.Replace(trimmedText, @"\s+", " "); - - _words = trimmedText.Split(delimiterChars); - } - } - - public int IndentationLevel - { - get - { - if (Text.Length == 0) - { - return 0; - } - - int pos = 0; - while (Text.Substring(pos, 1) == " ") - { - pos++; - } - return pos; - } - } - - public string FirstWord - { - get - { - if (_words != null && _words.Any()) - { - // This is a special handling!!! - // There are several commands that have the first word "ip"... - if (_words[0] == "ip") - { - if (_words.Count() > 1 && _words[1] == "address") - { - return _words[0] + " " + _words[1]; - } - if (_words.Count() > 3 && _words[1] == "verify" && _words[2] == "reverse-path" && _words[3] == "interface") - { - return _words[0] + " " + _words[1] + " " + _words[2] + " " + _words[3]; - } - } - else - { - return _words[0]; - } - } - - return ""; - } - } - - public int Id { get; set; } - public int? ParentId { get; set; } - public string CiscoId { get; set; } - public string Description { get; set; } - public string Tag { get; set; } - public string DataForNextElement { get; set; } - public bool KnownCommand { get; set; } - public bool NotAnInterestingCommand { get; set; } - public ConversionIncidentType ConversionIncidentType { get; set; } - public string ConversionIncidentMessage { get; set; } - public List Children { get; set; } - - public CiscoCommand() - { - CiscoId = ""; - Description = ""; - DataForNextElement = ""; - } - - public string GetParam(int pos) - { - if (_words == null || _words.Length <= pos) - { - return ""; - } - - return _words[pos]; - } - - public List GetParams(int pos) - { - var res = new List(); - - if (_words == null || !_words.Any()) - { - return res; - } - - for (int i = 0; i < _words.Length; i++) - { - if (i >= pos) - { - res.Add(_words[i]); - } - } - - return res; - } - - public int GetParamPosition(string paramName) - { - if (_words == null || !_words.Any()) - { - return -1; - } - - int pos = 0; - foreach (string word in _words) - { - if (word == paramName) - { - return pos; - } - pos++; - } - - return -1; - } - - public List Flatten() - { - var res = new List(); - res.Add(this); - - if (Children != null) - { - foreach (CiscoCommand child in Children) - { - foreach (CiscoCommand flattenchild in child.Flatten()) - { - res.Add(flattenchild); - } - } - } - - return res; - } - - public virtual string Name() { return ""; } - - public virtual void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - if (command.Children != null) - { - foreach (CiscoCommand child in command.Children) - { - if (child.Name() == "description") - { - Description = child.Description; - } - } - } - - ConversionIncidentType = ConversionIncidentType.None; - ConversionIncidentMessage = ""; - } - } - - public class Cisco_Description : CiscoCommand - { - public Cisco_Description() - { - NotAnInterestingCommand = true; - } - - public override string Name() { return "description"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - if (!string.IsNullOrEmpty(command.Text)) - { - Description = command.Text.Trim().Substring(Name().Length + 1); - } - - } - } - - public class Cisco_ASA : CiscoCommand - { - public string Version { get; set; } - - public override string Name() { return "ASA"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - const string version = "version"; - if (!string.IsNullOrEmpty(command.Text) && command.GetParam(1).ToLower() == version) - { - Version = command.Text.Trim().Substring(Name().Length + version.Length + 2); - } - else - { - Version = ""; - } - } - } - - public class Cisco_Alias : CiscoCommand - { - public override string Name() { return "name"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - string real = command.GetParam(1); - string alias = command.GetParam(2); - - if (!string.IsNullOrEmpty(alias) && !string.IsNullOrEmpty(real) && !aliases.ContainsKey(alias)) - { - aliases.Add(alias, real); - } - } - } - - public class Cisco_SSH : CiscoCommand - { - public string IpAddress { get; set; } - public string Netmask { get; set; } - public string Interface { get; set; } - - public override string Name() { return "ssh"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - IpAddress = ""; - Netmask = ""; - Interface = ""; - - string commandParam = command.GetParam(1); - if (NetworkUtils.IsValidIp(commandParam)) - { - IpAddress = commandParam; - } - else - { - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "IPv4 address was expected, but '" + commandParam + "' was found."; - return; - } - - commandParam = command.GetParam(2); - if (NetworkUtils.IsValidNetmask(commandParam)) - { - Netmask = commandParam; - } - else - { - IpAddress = ""; - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "IPv4 netmask was expected, but " + commandParam + " was found."; - return; - } - - Interface = command.GetParam(3); - } - } - - public class Cisco_Hostname : CiscoCommand - { - public string HostName { get; set; } - - public override string Name() { return "hostname"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - HostName = command.GetParam(1); - } - } - - public class Cisco_Object : CiscoCommand - { - public enum ObjectTypes { NA, Fqdn, Host, Network, Range, TcpService, UdpService, IcmpService, KnownOtherService }; - - public ObjectTypes ObjectType { get; set; } - public string Fqdn { get; set; } - public string HostAddress { get; set; } - public string Network { get; set; } - public string Netmask { get; set; } - public string RangeFrom { get; set; } - public string RangeTo { get; set; } - public bool IsDestination { get; set; } - public string ServiceProtocol { get; set; } - public string ServiceOperator { set; get; } - public string ServicePort { get; set; } - - public override string Name() { return "object"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - CiscoId = command.GetParam(2); - ObjectType = ObjectTypes.NA; - - switch (command.GetParam(1)) - { - case "network": - ParseNetworks(); - break; - - case "service": - ParseServices(); - break; - - default: - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "Unrecognized object type (" + command.GetParam(1) + ")"; - break; - } - } - - private void ParseNetworks() - { - if (Children == null) - { - return; - } - - int found = 0; - - foreach (CiscoCommand child in Children) - { - switch (child.Name()) - { - case "fqdn": - ObjectType = ObjectTypes.Fqdn; - Fqdn = ((Cisco_Fqdn)child).Fqdn; - found++; - break; - - case "host": - ObjectType = ObjectTypes.Host; - HostAddress = ((Cisco_Host)child).HostAddress; - found++; - break; - - case "subnet": - ObjectType = ObjectTypes.Network; - Network = ((Cisco_Subnet)child).Network; - Netmask = ((Cisco_Subnet)child).Netmask; - found++; - break; - - case "range": - ObjectType = ObjectTypes.Range; - RangeFrom = ((Cisco_Range)child).RangeFrom; - RangeTo = ((Cisco_Range)child).RangeTo; - found++; - break; - } - - if (found == 1) - { - if (child.ConversionIncidentType != ConversionIncidentType.None) - { - ConversionIncidentType = child.ConversionIncidentType; - ConversionIncidentMessage = child.ConversionIncidentMessage; - } - } - } - - if (found > 1) - { - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "An Object (network) can only hold one fqdn, host, range or subnet"; - Console.WriteLine(ConversionIncidentMessage); - } - } - - private void ParseServices() - { - if (Children == null) - { - return; - } - - int found = 0; - - foreach (CiscoCommand child in Children) - { - if (child.Name() == "service") - { - found++; - - var service = (Cisco_Service)child; - ServiceProtocol = service.Protocol; - ServiceOperator = service.Operator; - ServicePort = service.Port; - IsDestination = service.IsDestination; - - if (service.ConversionIncidentType != ConversionIncidentType.None) - { - ConversionIncidentType = service.ConversionIncidentType; - ConversionIncidentMessage = service.ConversionIncidentMessage; - } - - switch (ServiceProtocol) - { - case "ip": - // Predefined "any" object. No special handling... - break; - - case "icmp": - ObjectType = ObjectTypes.IcmpService; - break; - - case "tcp": - ObjectType = ObjectTypes.TcpService; - break; - - case "udp": - ObjectType = ObjectTypes.UdpService; - break; - - default: - // No need to check also for CiscoKnownServices.IsKnownServiceNumber here, - // because it is already done in Cisco_Service class!!! - if (CiscoKnownServices.IsKnownService(ServiceProtocol)) - { - ObjectType = ObjectTypes.KnownOtherService; - } - else - { - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Unrecognized service protocol (" + ServiceProtocol + ")"; - Console.WriteLine(ConversionIncidentMessage); - } - break; - } - } - } - - if (found > 1) - { - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "An Object (service) can only hold one service"; - Console.WriteLine(ConversionIncidentMessage); - } - } - } - - public class Cisco_Fqdn : CiscoCommand - { - public string Fqdn { get; set; } - - public override string Name() { return "fqdn"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - Fqdn = (command.GetParam(1) == "v4") ? command.GetParam(2) : command.GetParam(1); - } - } - - public class Cisco_Host : CiscoCommand - { - public string HostAddress { get; set; } - - public override string Name() { return "host"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - HostAddress = command.GetParam(1); - if (!NetworkUtils.IsValidIp(HostAddress)) - { - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Invalid host IP address (" + HostAddress + "). Using IP 1.1.1.1."; - Console.WriteLine(ConversionIncidentMessage); - - HostAddress = "1.1.1.1"; - } - } - } - - public class Cisco_Subnet : CiscoCommand - { - public string Network { get; set; } - public string Netmask { get; set; } - - public override string Name() { return "subnet"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - Network = command.GetParam(1); - Netmask = command.GetParam(2); - - if (!NetworkUtils.IsValidIp(Network) || !NetworkUtils.IsValidNetmask(Netmask)) - { - 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"; - } - } - } - - public class Cisco_Range : CiscoCommand - { - public string RangeFrom { get; set; } - public string RangeTo { get; set; } - - public override string Name() { return "range"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - RangeFrom = command.GetParam(1); - if (!NetworkUtils.IsValidIp(RangeFrom)) - { - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Invalid range starting IP address (" + RangeFrom + "). Using IP 0.0.0.0."; - Console.WriteLine(ConversionIncidentMessage); - - RangeFrom = "0.0.0.0"; - } - - RangeTo = command.GetParam(2); - if (!NetworkUtils.IsValidIp(RangeTo)) - { - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Invalid range ending IP address (" + RangeTo + "). Using IP 255.255.255.255."; - Console.WriteLine(ConversionIncidentMessage); - - RangeTo = "255.255.255.255"; - } - } - } - - public class Cisco_Service : CiscoCommand - { - public string Protocol { get; set; } - public bool IsDestination { get; set; } - public string Port { get; set; } - public string Operator { get; set; } - - public override string Name() { return "service"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - // Parsing Options: - //----------------- - // 1. service protocol_name_or_number - // 2. service {icmp | icmp6} [icmp-type] - // 3. service {tcp | udp} [source operator port] [destination operator port] - //----------------- - - Protocol = command.GetParam(1); - - IsDestination = false; - Port = ""; - Operator = ""; - - switch (Protocol) - { - case "ip": - IsDestination = true; - break; - - case "icmp": - case "icmp6": - IsDestination = true; - Protocol = "icmp"; - Operator = "eq"; - Port = CiscoKnownServices.ConvertIcmpServiceToType(command.GetParam(2)); - break; - - case "tcp": - case "udp": - IsDestination = (command.GetParam(2) == "destination"); - Operator = command.GetParam(3); - Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(4)); - - int nextParamId = 5; // we need this because of 'range' operator - - if (Operator == "range") - { - Operator = "eq"; - Port = Port + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(5)); - nextParamId = 6; // !!! - } - - if (!IsDestination && command.GetParam(nextParamId) == "destination") - { - // "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); - Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(nextParamId + 2)); - - if (Operator == "range") - { - Operator = "eq"; - Port = Port + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(nextParamId + 3)); - } - } - - if (string.IsNullOrEmpty(Operator) || string.IsNullOrEmpty(Port)) - { - // Use ALL tcp/udp ports if nothing specified!!! - IsDestination = true; - Operator = "all"; - Port = "1-65535"; - } - break; - - default: - IsDestination = true; - - string serviceName; - if (CiscoKnownServices.IsKnownService(Protocol)) - { - Port = CiscoKnownServices.ConvertServiceToPort(Protocol); - } - else if (CiscoKnownServices.IsKnownServiceNumber(Protocol, out serviceName)) // protocol number is used!!! - { - Port = Protocol; - Protocol = serviceName; - } - else - { - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Unrecognized service protocol (" + Protocol + ")"; - Console.WriteLine(ConversionIncidentMessage); - } - break; - } - } - } - - public class Cisco_NetworkObject : CiscoCommand - { - public string IpAddress { get; set; } - public string Netmask { get; set; } - public string ReferencedObject { get; set; } - - public override string Name() { return "network-object"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - IpAddress = ""; - Netmask = ""; - ReferencedObject = ""; - - switch (command.GetParam(1)) - { - case "object": - ReferencedObject = command.GetParam(2); - break; - - case "host": - string ipAddressOrObjectName = command.GetParam(2); - if (ciscoIds.ContainsKey(ipAddressOrObjectName)) - { - ReferencedObject = ipAddressOrObjectName; - } - else - { - IpAddress = aliases.ContainsKey(ipAddressOrObjectName) ? aliases[ipAddressOrObjectName] : ipAddressOrObjectName; - if (!NetworkUtils.IsValidIp(IpAddress)) - { - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Invalid IP address (" + IpAddress + "). Using IP 1.1.1.1."; - Console.WriteLine(ConversionIncidentMessage); - - IpAddress = "1.1.1.1"; - } - - Netmask = "255.255.255.255"; - } - break; - - default: - // subnet - IpAddress = command.GetParam(1); - if (aliases.ContainsKey((IpAddress))) - { - IpAddress = aliases[IpAddress]; - } - Netmask = command.GetParam(2); - - if (!NetworkUtils.IsValidIp(IpAddress) || !NetworkUtils.IsValidNetmask(Netmask)) - { - 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"; - } - break; - } - } - } - - public class Cisco_ProtocolObject : CiscoCommand - { - public string ProtocolName { get; set; } - - public override string Name() { return "protocol-object"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - ProtocolName = command.GetParam(1); - } - } - - public class Cisco_PortObject : CiscoCommand - { - public string Port { get; set; } - - public override string Name() { return "port-object"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - Port = ""; - - string portOperator = command.GetParam(1); - - switch (portOperator) - { - case "eq": - Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(2)); - break; - - case "range": - Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(2)) + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(3)); - break; - } - } - } - - public class Cisco_ServiceObject : CiscoCommand - { - public string Protocol { get; set; } - public bool IsDestination { get; set; } - public string Port { get; set; } - public string Operator { get; set; } - public string RefObjectName { get; set; } - - public override string Name() { return "service-object"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - // Parsing Options: - //----------------- - // 1. service-object object object_name - // 2. service-object protocol_name_or_number - // 3. service-object {icmp | icmp6} [icmp-type] - // 4. service-object {tcp | udp | tcp-udp} [source operator port] [destination operator port] - //----------------- - - Protocol = command.GetParam(1); - - IsDestination = false; - Port = ""; - Operator = ""; - RefObjectName = ""; - - switch (Protocol) - { - case "object": - RefObjectName = command.GetParam(2); - Protocol = ""; - break; - - case "ip": - IsDestination = true; - break; - - case "icmp": - case "icmp6": - IsDestination = true; - Protocol = "icmp"; - Operator = "eq"; - Port = CiscoKnownServices.ConvertIcmpServiceToType(command.GetParam(2)); - break; - - case "tcp": - case "udp": - case "tcp-udp": - IsDestination = (command.GetParam(2) == "destination"); - Operator = command.GetParam(3); - Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(4)); - - int nextParamId = 5; // we need this because of 'range' operator - - if (Operator == "range") - { - Operator = "eq"; - Port = Port + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(5)); - nextParamId = 6; // !!! - } - - if (!IsDestination && command.GetParam(nextParamId) == "destination") - { - // "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); - Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(nextParamId + 2)); - - if (Operator == "range") - { - Operator = "eq"; - Port = Port + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(nextParamId + 3)); - } - } - - if (string.IsNullOrEmpty(Operator) || string.IsNullOrEmpty(Port)) - { - // Use ALL tcp/udp ports if nothing specified!!! - IsDestination = true; - Operator = "all"; - Port = "1-65535"; - } - break; - - default: - IsDestination = true; - - string serviceName; - if (CiscoKnownServices.IsKnownService(Protocol)) - { - Port = CiscoKnownServices.ConvertServiceToPort(Protocol); - } - else if (CiscoKnownServices.IsKnownServiceNumber(Protocol, out serviceName)) // protocol number is used!!! - { - Port = Protocol; - Protocol = serviceName; - } - else - { - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Unrecognized service protocol (" + Protocol + ")"; - Console.WriteLine(ConversionIncidentMessage); - } - break; - } - } - } - - public class Cisco_IcmpObject : CiscoCommand - { - public string IcmpType { get; set; } - - public override string Name() { return "icmp-object"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - IcmpType = command.GetParam(1); - } - } - - public class Cisco_ReferenceGroupObject : CiscoCommand - { - public string ReferenceId { get; set; } - - public override string Name() { return "group-object"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - ReferenceId = command.GetParam(1); - } - } - - public class Cisco_GroupObject : CiscoCommand - { - public enum Group_Type { NA, Service, Protocol, Icmp, Network }; - - private Dictionary _ciscoIds; - - public Group_Type GroupType { get; set; } - public string ServiceProtocol { get; set; } - - public List Protocols = new List(); - public List IcmpTypes = new List(); - public List MembersGroupNames = new List(); - public List MemberObjects = new List(); - - public override string Name() { return "object-group"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - _ciscoIds = ciscoIds; - - CiscoId = command.GetParam(2); - ServiceProtocol = ""; - - switch (command.GetParam(1)) - { - case "service": - GroupType = Group_Type.Service; - break; - - case "protocol": - GroupType = Group_Type.Protocol; - break; - - case "icmp-type": - GroupType = Group_Type.Icmp; - break; - - case "network": - GroupType = Group_Type.Network; - break; - - default: - GroupType = Group_Type.NA; - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "Unrecognized group type (" + command.GetParam(1) + ")"; - return; - } - - if (GroupType == Group_Type.Service) - { - ServiceProtocol = command.GetParam(3); - } - - if (command.Children == null) - { - return; - } - - foreach (CiscoCommand child in command.Children) - { - bool hasValidChild = true; - - switch (child.Name()) - { - case "protocol-object": - Protocols.Add(((Cisco_ProtocolObject)child).ProtocolName); - break; - - case "port-object": - MemberObjects.Add((Cisco_PortObject)child); - break; - - case "icmp-object": - IcmpTypes.Add(((Cisco_IcmpObject)child).IcmpType); - break; - - case "group-object": - MembersGroupNames.Add(((Cisco_ReferenceGroupObject)child).ReferenceId); - break; - - case "network-object": - MemberObjects.Add((Cisco_NetworkObject)child); - break; - - case "service-object": - MemberObjects.Add((Cisco_ServiceObject)child); - break; - - default: - hasValidChild = false; - break; - } - - if (hasValidChild) - { - if (child.ConversionIncidentType != ConversionIncidentType.None) - { - ConversionIncidentType = child.ConversionIncidentType; - ConversionIncidentMessage = child.ConversionIncidentMessage; - } - } - } - } - - public List GetChildServices() - { - var services = new List(); - - if (Children != null) - { - foreach (CiscoCommand child in Children) - { - if (child.Name() == "service-object") - { - services.Add((Cisco_ServiceObject)child); - } - else if (child.Name() == "group-object") - { - if (_ciscoIds.ContainsKey(((Cisco_ReferenceGroupObject)child).ReferenceId)) - { - var referencedGroupObject = (Cisco_GroupObject)_ciscoIds[((Cisco_ReferenceGroupObject)child).ReferenceId]; - var referencedGroupServices = referencedGroupObject.GetChildServices(); - - foreach (Cisco_ServiceObject referencedService in referencedGroupServices) - { - if (!services.Contains(referencedService)) - { - services.Add(referencedService); - } - } - } - } - } - } - - return services; - } - - public List GetChildPorts() - { - var ports = new List(); - - if (Children != null) - { - foreach (CiscoCommand child in Children) - { - if (child.Name() == "port-object") - { - ports.Add((Cisco_PortObject)child); - } - else if (child.Name() == "group-object") - { - if (_ciscoIds.ContainsKey(((Cisco_ReferenceGroupObject)child).ReferenceId)) - { - var referencedGroupObject = (Cisco_GroupObject)_ciscoIds[((Cisco_ReferenceGroupObject)child).ReferenceId]; - var referencedGroupPorts = referencedGroupObject.GetChildPorts(); - - foreach (Cisco_PortObject referencedPort in referencedGroupPorts) - { - if (!ports.Contains(referencedPort)) - { - ports.Add(referencedPort); - } - } - } - } - } - } - - return ports; - } - } - - public class Cisco_SecurityLevel : CiscoCommand - { - public string Value { get; set; } - - public override string Name() { return "security-level"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - Value = command.GetParam(1); - } - } - - public class Cisco_NameIf : CiscoCommand - { - public string Value { get; set; } - - public override string Name() { return "nameif"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - Value = InterfacePrefix + command.GetParam(1); - } - } - - public class Cisco_VLan : CiscoCommand - { - public string Value { get; set; } - - public override string Name() { return "vlan"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - Value = command.GetParam(1); - } - } - - public class Cisco_IP : CiscoCommand - { - public string IpAddress { get; set; } - public string Netmask { get; set; } - - public override string Name() { return "ip address"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - IpAddress = ""; - Netmask = ""; - - if (command.GetParam(1) == "address") - { - IpAddress = command.GetParam(2); - Netmask = command.GetParam(3); - } - } - } - - public class Cisco_Shutdown : CiscoCommand - { - public bool IsShutdown { get; set; } - - public override string Name() { return "shutdown"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - IsShutdown = (command.GetParam(0) == "shutdown"); - } - } - - public class Cisco_ManagementOnly : CiscoCommand - { - public bool IsManagementOnly { get; set; } - - public override string Name() { return "management-only"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - IsManagementOnly = (command.GetParam(0) == "management-only"); - } - } - - public class Cisco_TimeRange : CiscoCommand - { - public enum Weekdays { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; - - private string _timeRangeName; - - private string _startDateTime; - private string _endDateTime; - - private List _periodicsList; - - public string TimeRangeName - { - get { return _timeRangeName; } - } - - public string StartDateTime - { - get { return _startDateTime; } - } - - public string EndDateTime - { - get { return _endDateTime; } - } - - public List PeriodicsList - { - get { return _periodicsList; } - } - - public override string Name() { return "time-range"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - _periodicsList = new List(); - - _timeRangeName = this.GetParam(1); - - foreach(CiscoCommand child in Children) - { - if(child.FirstWord.Equals("absolute")) - { - int startIndex = child.Text.IndexOf("start"); - int endIndex = child.Text.IndexOf("end"); - if(startIndex > -1 && endIndex > -1) - { - _startDateTime = child.Text.Substring("absolute".Length + "start".Length + 2, endIndex - startIndex - "start".Length).Trim(); - _endDateTime = child.Text.Substring(endIndex + "end".Length).Trim(); - } - else if (startIndex > -1 && endIndex == -1) - { - _startDateTime = child.Text.Substring("absolute".Length + "start".Length + 2).Trim(); - } - else if(startIndex == -1 && endIndex > -1) - { - _endDateTime = child.Text.Substring("absolute".Length + "end".Length + 2).Trim(); - } - } - - if (child.FirstWord.Equals("periodic")) - { - string period = child.Text.Substring("periodic".Length + 1).Trim(); - - string[] daysTimes = period.Trim().Split(new string[] { "to" }, StringSplitOptions.RemoveEmptyEntries); - - string[] daysTimes_1 = daysTimes[0].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); - string[] daysTimes_2 = daysTimes[1].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); - - if (daysTimes_1.Length == 2 && daysTimes_2.Length == 2) - { - int startWdIndex = (int)Enum.Parse(typeof(Weekdays), daysTimes_1[0]); - int endWdIndex = (int)Enum.Parse(typeof(Weekdays), daysTimes_2[0]); - - if (startWdIndex < endWdIndex) - { - _periodicsList.Add((Weekdays)startWdIndex + " " + daysTimes_1[1] + " to 23:59"); - - for (int i = startWdIndex+1; i <= endWdIndex-1; i++) - { - _periodicsList.Add((Weekdays)i + " 0:00 to 23:59"); - } - - _periodicsList.Add((Weekdays)endWdIndex + " 0:00 to " + daysTimes_2[1]); - } - else - { - int firstWdIndex = (int)Enum.GetValues(typeof(Weekdays)).Cast().First(); - int lastWdIndex = (int)Enum.GetValues(typeof(Weekdays)).Cast().Last(); - - _periodicsList.Add((Weekdays)startWdIndex + " " + daysTimes_1[1] + " to 23:59"); - - for (int i = startWdIndex + 1; i <= lastWdIndex; i++) - { - _periodicsList.Add((Weekdays)i + " 0:00 to 23:59"); - } - - for (int i = firstWdIndex; i <= endWdIndex-1; i++) - { - _periodicsList.Add((Weekdays)i + " 0:00 to 23:59"); - } - - _periodicsList.Add((Weekdays)endWdIndex + " 0:00 to " + daysTimes_2[1]); - } - } - else - { - _periodicsList.Add(period); - } - } - } - } - } - - public class Cisco_Interface : CiscoCommand - { - public string InterfaceName { get; set; } - public int SecurityLevel { get; set; } - public string VLan { get; set; } - public string IpAddress { get; set; } - public string Netmask { get; set; } - public bool Shutdown { get; set; } - public bool ManagementOnly { get; set; } - public bool LeadsToInternet { get; set; } - - public class Subnet - { - public string Network { get; private set; } - public string Netmask { get; private set; } - - public Subnet (string sIp, string sMask) - { - Network = sIp; - Netmask = sMask; - } - } - - public List Topology = new List(); - - public override string Name() { return "interface"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - InterfaceName = command.GetParam(1); - SecurityLevel = 0; - VLan = ""; - IpAddress = ""; - Netmask = ""; - Shutdown = false; - ManagementOnly = false; - LeadsToInternet = false; - - if (command.Children == null) - { - return; - } - - foreach (CiscoCommand child in command.Children) - { - switch (child.Name()) - { - case "security-level": - int securityLevel; - if (int.TryParse(((Cisco_SecurityLevel)child).Value, out securityLevel)) - { - SecurityLevel = securityLevel; - } - break; - - case "nameif": - CiscoId = ((Cisco_NameIf)child).Value; - break; - - case "vlan": - VLan = ((Cisco_VLan)child).Value; - break; - - case "shutdown": - Shutdown = ((Cisco_Shutdown)child).IsShutdown; - break; - - case "management-only": - ManagementOnly = ((Cisco_ManagementOnly)child).IsManagementOnly; - break; - - case "ip address": - IpAddress = ((Cisco_IP)child).IpAddress; - Netmask = ((Cisco_IP)child).Netmask; - - if (NetworkUtils.IsValidIp(IpAddress) && NetworkUtils.IsValidNetmask(Netmask)) - { - Topology.Add(new Subnet(NetworkUtils.GetNetwork(IpAddress, Netmask), Netmask)); - } - else - { - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Invalid IP subnet (" + IpAddress + "/" + Netmask + ")."; - Console.WriteLine(ConversionIncidentMessage); - } - break; - } - } - } - - public bool HasValidIpAddress() - { - return NetworkUtils.IsValidIp(IpAddress) && NetworkUtils.IsValidNetmask(Netmask); - } - } - - public class Cisco_Route : CiscoCommand - { - public string InterfaceName { get; set; } - public bool DefaultRoute { get; set; } - public string DestinationIp { get; set; } - public string DestinationNetmask { get; set; } - public string Gateway { get; set; } - - public override string Name() { return "route"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - DefaultRoute = false; - InterfaceName = command.GetParam(1); - DestinationIp = command.GetParam(2); - DestinationNetmask = command.GetParam(3); - Gateway = command.GetParam(4); - - bool destinationIpResolved = false; - - if (ciscoIds.ContainsKey(DestinationIp)) - { - var refObj = (Cisco_Object)ciscoIds[DestinationIp]; - if (refObj != null) - { - switch (refObj.ObjectType) - { - case Cisco_Object.ObjectTypes.Host: - DestinationIp = refObj.HostAddress; - destinationIpResolved = true; - break; - - case Cisco_Object.ObjectTypes.Network: - DestinationIp = refObj.Network; - destinationIpResolved = true; - break; - } - } - } - else - { - DestinationIp = aliases.ContainsKey(DestinationIp) ? aliases[DestinationIp] : DestinationIp; - destinationIpResolved = true; - } - - if (!destinationIpResolved) - { - 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"; - } - - if (!NetworkUtils.IsValidIp(DestinationIp)) - { - 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"; - } - - if (DestinationIp == "0.0.0.0" && DestinationNetmask == "0.0.0.0") - { - DefaultRoute = true; - } - } - } - - public class Cisco_AntiSpoofing : CiscoCommand - { - public string InterfaceName { get; set; } - - public override string Name() { return "ip verify reverse-path interface"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - if (command.GetParam(1) == "verify" && command.GetParam(2) == "reverse-path" && command.GetParam(3) == "interface") - { - InterfaceName = command.GetParam(4); - } - } - } - - public class Cisco_SameSecurityTraffic : CiscoCommand - { - public enum InterfaceTrafficType { NA, Inter, Intra }; - - public InterfaceTrafficType TrafficType { get; set; } - - public override string Name() { return "same-security-traffic"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - if (command.GetParam(1) == "permit") - { - switch (command.GetParam(2)) - { - case "inter-interface": - TrafficType = InterfaceTrafficType.Inter; - break; - - case "intra-interface": - TrafficType = InterfaceTrafficType.Intra; - break; - } - } - } - } - - public class Cisco_Nat : CiscoCommand - { - public bool Inactive { get; set; } - public string RealInterface { get; set; } - public string MappedInterface { get; set; } - public bool IsStatic { get; set; } - public bool IsHideBehindInterface { get; set; } - public bool IsUnidirectional { get; set; } - public bool IsAutoAfter { get; set; } - public string StaticNatIpAddressOrObjectName { get; set; } - public string DynamicNatIpAddressOrObjectName { get; set; } - public string SourceId { get; set; } - public string TranslatedSourceId { get; set; } - public string DestinationId { get; set; } - public string TranslatedDestinationId { get; set; } - public string ServiceProtocol { get; set; } - public string ServiceId { get; set; } - public string TranslatedServiceId { get; set; } - - public override string Name() { return "nat"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - /************************************************************************************** - * There are two types of NAT: - * 1. Object NAT - child object of a Network Object - this is the commonly used NAT - * 2. Regular NAT - twice or manual NAT rule - more scalable, enables extra features over Object NAT - * - * Each of these two types may be Static or Dynamic. - * Static NAT allows bidirectional traffic (mirrored rules). - * - * Each NAT command is started as follows: - * --------------------------------------- - * nat [(real_interface, mapped_interface)] ... - * - **************************************************************************************/ - - base.Parse(command, prevCommand, ciscoIds, aliases); - - string param = command.GetParam(1).Trim(new char[] { '(', ')' }); - string[] interfaces = param.Split(','); - - if (interfaces.Length > 0) - { - RealInterface = interfaces[0]; - MappedInterface = (interfaces.Length > 1) ? interfaces[1] : ""; - } - else - { - RealInterface = ""; - MappedInterface = ""; - } - - Inactive = false; - IsStatic = false; - IsHideBehindInterface = false; - IsUnidirectional = false; - StaticNatIpAddressOrObjectName = ""; - DynamicNatIpAddressOrObjectName = ""; - SourceId = ""; - TranslatedSourceId = ""; - DestinationId = ""; - TranslatedDestinationId = ""; - ServiceProtocol = ""; - ServiceId = ""; - TranslatedServiceId = ""; - - if (command.IndentationLevel > 0) - { - ParseObjectNatCommand(command, prevCommand, ciscoIds); - } - else - { - ParseRegularNatCommand(command, prevCommand, ciscoIds); - } - - if (command.GetParamPosition("unidirectional") > 0/* || command.GetParamPosition("no-proxy-arp") > 0*/) // commented due to A.R. suggestion... - { - IsUnidirectional = true; - } - - if (command.GetParamPosition("inactive") > 0) - { - Inactive = true; - } - } - - private void ParseObjectNatCommand(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds) - { - /******************************************************** - * Parsing options for Object NAT: - * ------------------------------- - * ... static {mapped_host_ip_address | mapped_object_name | interface} [service {tcp | udp} real_port mapped_port] - * - * ... dynamic {mapped_host_ip_address | mapped_object_name | interface} - * - * + mapped_object may be a host or network or range - */ - - switch (command.GetParam(2)) - { - case "static": - IsStatic = true; - - if (command.GetParam(3) == "interface") - { - IsHideBehindInterface = true; // Static NAT with port-translation - } - else - { - // static hide behind an arbitrary ip/network - StaticNatIpAddressOrObjectName = command.GetParam(3); - } - - int servicePos = command.GetParamPosition("service"); - if (servicePos > 0) - { - ServiceProtocol = command.GetParam(servicePos + 1); - if (ServiceProtocol == "tcp" || ServiceProtocol == "udp") - { - ServiceId = CiscoKnownServices.ConvertServiceToPort(command.GetParam(servicePos + 2)); - TranslatedServiceId = CiscoKnownServices.ConvertServiceToPort(command.GetParam(servicePos + 3)); - } - else - { - ServiceProtocol = ""; - - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Unrecognized service protocol (" + ServiceProtocol + ")"; - Console.WriteLine(ConversionIncidentMessage); - } - } - break; - - case "dynamic": - if (command.GetParam(3) == "interface") - { - IsHideBehindInterface = true; - } - else - { - // dynamic hide behind an arbitrary ip/network - DynamicNatIpAddressOrObjectName = command.GetParam(3); - } - - // Check for interface fall-back configuration - if (command.GetParam(4) == "interface") - { - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "Interface fall-back for dynamic object NAT is not supported"; - Console.WriteLine(ConversionIncidentMessage); - } - break; - } - } - - private void ParseRegularNatCommand(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds) - { - /******************************************************** - * Parsing options for regular (manual or twice) NAT: - * -------------------------------------------------- - * ... [after-object] source static real_object_name [mapped_object_name | interface] [destination static mapped_object_name real_object_name] [service real_service_name mapped_service_name] - * - * ... [after-auto] source dynamic {real_object_name | any} {mapped_object_name | interface} [destination static mapped_object_name real_object_name] [service mapped_service_name real_service_name] - * - * + real_object/mapped_object may be a host or network - */ - - int sourcePos = 2; - - if (command.GetParam(2) == "after-auto" || command.GetParam(2) == "after-object") - { - IsAutoAfter = true; - sourcePos = 3; - } - - if (command.GetParam(sourcePos) == "source") - { - if (command.GetParam(sourcePos + 1) == "static") - { - IsStatic = true; - } - - SourceId = command.GetParam(sourcePos + 2); - TranslatedSourceId = command.GetParam(sourcePos + 3); - if (TranslatedSourceId == "interface") - { - IsHideBehindInterface = true; - } - - int destPos = command.GetParamPosition("destination"); - if (destPos > 0) // twice-NAT - { - // check sanity - if (command.GetParam(destPos + 1) != "static") - { - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "Not handling NAT with dynamic destination"; - Console.WriteLine(ConversionIncidentMessage); - return; - } - - DestinationId = command.GetParam(destPos + 2); - TranslatedDestinationId = command.GetParam(destPos + 3); - } - - int servicePos = command.GetParamPosition("service"); - if (servicePos > 0) - { - ServiceId = command.GetParam(servicePos + 1); - TranslatedServiceId = command.GetParam(servicePos + 2); - } - } - else - { - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "Not handling NAT with dynamic source"; - Console.WriteLine(ConversionIncidentMessage); - } - } - } - - public class Cisco_AccessGroup : CiscoCommand - { - public enum DirectionType { Inbound, Outbound, Global }; - - public DirectionType Direction { get; set; } - public string AccessListName { get; set; } - public string InterfaceName { get; set; } - - public override string Name() { return "access-group"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - // Parsing Options: - //----------------- - // access-group access_list_name {{in | out} interface interface_name | global} - //----------------- - - base.Parse(command, prevCommand, ciscoIds, aliases); - - AccessListName = command.GetParam(1); - InterfaceName = (command.GetParam(3) == "interface") ? command.GetParam(4) : ""; - - switch (command.GetParam(2)) - { - case "in": - Direction = DirectionType.Inbound; - break; - - case "out": - Direction = DirectionType.Outbound; - break; - - case "global": - Direction = DirectionType.Global; - break; - - default: - Console.WriteLine("Error: unknown access-group traffic direction (" + command.GetParam(2) + ")."); - break; - } - - if (Direction != DirectionType.Inbound && Direction != DirectionType.Global) - { - ConversionIncidentType = ConversionIncidentType.Informative; - ConversionIncidentMessage = "Outbound ACLs will not be converted"; - Console.WriteLine(ConversionIncidentMessage); - } - } - } - - public class Cisco_AccessList : CiscoCommand - { - public enum ActionType { NA, Deny, Permit }; - - public class SourceDest - { - public enum SourceDestType { NA, Any, Any6, ReferenceObject, Host, SubnetAndMask }; - - public SourceDestType Type { get; set; } - public string HostIp { get; set; } - public string Subnet { get; set; } - public string Netmask { get; set; } - public string RefObjectName { get; set; } - public int WordsCount { get; set; } - - public SourceDest() - { - Type = SourceDestType.NA; - HostIp = ""; - Subnet = ""; - Netmask = ""; - RefObjectName = ""; - WordsCount = -1; - } - - public SourceDest(List words) : this() - { - if (!words.Any()) - { - WordsCount = 0; - return; - } - - switch (words[0]) - { - case "any": - case "any4": - Type = SourceDestType.Any; - WordsCount = 1; - break; - - case "any6": - Type = SourceDestType.Any6; - WordsCount = 1; - break; - - case "host": - Type = SourceDestType.Host; - if (words.Count > 1) - { - HostIp = words[1]; - WordsCount = 2; - } - break; - - case "object-group": - case "object": - Type = SourceDestType.ReferenceObject; - if (words.Count > 1) - { - RefObjectName = words[1]; - WordsCount = 2; - } - break; - - case "interface": - Type = SourceDestType.ReferenceObject; - if (words.Count > 1) - { - RefObjectName = InterfacePrefix + words[1]; - WordsCount = 2; - } - break; - - default: - // both the ip_address and ip_mask are specified - Type = SourceDestType.SubnetAndMask; - if (words.Count > 1) - { - Subnet = words[0]; - Netmask = words[1]; - WordsCount = 2; - } - break; - } - } - } - - public class ProtocolProperties - { - private Dictionary _ciscoIds; - - public ProtocolType Protocol { get; set; } - public TcpUdpPortOperatorType TcpUdpPortOperator { get; set; } - public ServiceDirection Where { get; set; } - public string TcpUdpPortValue { get; set; } - public int WordsCount { get; set; } - - public ProtocolProperties() - { - Protocol = ProtocolType.NA; - TcpUdpPortOperator = TcpUdpPortOperatorType.NA; - Where = ServiceDirection.Destination; - TcpUdpPortValue = ""; - WordsCount = -1; - } - - public ProtocolProperties(ProtocolType protocol, List words, Dictionary ciscoIds, ServiceDirection where) : this() - { - _ciscoIds = ciscoIds; - Protocol = protocol; - Where = where; - WordsCount = 0; - - if (protocol == ProtocolType.Ip || - protocol == ProtocolType.Tcp || - protocol == ProtocolType.Udp || - protocol == ProtocolType.ReferenceObject) - { - TcpUdpPortOperator = TcpUdpPortOperatorType.All; - - if (words.Count > 0) - { - switch (words[0]) - { - case "range": - TcpUdpPortOperator = TcpUdpPortOperatorType.Range; - if (words.Count > 2) - { - TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]) + "-" + - CiscoKnownServices.ConvertServiceToPort(words[2]); - WordsCount = 3; - } - break; - - case "lt": - TcpUdpPortOperator = TcpUdpPortOperatorType.Lt; - if (words.Count > 1) - { - TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]); - WordsCount = 2; - } - break; - - case "gt": - TcpUdpPortOperator = TcpUdpPortOperatorType.Gt; - if (words.Count > 1) - { - TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]); - WordsCount = 2; - } - break; - - case "eq": - TcpUdpPortOperator = TcpUdpPortOperatorType.Eq; - if (words.Count > 1) - { - TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]); - WordsCount = 2; - } - break; - - case "neq": - TcpUdpPortOperator = TcpUdpPortOperatorType.Neq; - if (words.Count > 1) - { - TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]); - WordsCount = 2; - } - break; - - - case "object": - if (words.Count > 1 && IsServiceObject(words[1])) - { - TcpUdpPortOperator = TcpUdpPortOperatorType.ReferenceObject; - TcpUdpPortValue = words[1]; - WordsCount = 2; - } - break; - - case "object-group": - if (words.Count > 1 && IsServiceGroup(words[1])) - { - TcpUdpPortOperator = TcpUdpPortOperatorType.ReferenceObject; - TcpUdpPortValue = words[1]; - WordsCount = 2; - } - break; - } - } - } - else if (protocol == ProtocolType.Icmp) - { - if (words.Count > 0) - { - switch (words[0]) - { - case "object-group": - if (words.Count > 1 && IsServiceGroup(words[1])) - { - TcpUdpPortOperator = TcpUdpPortOperatorType.ReferenceObject; - TcpUdpPortValue = words[1]; - WordsCount = 2; - } - break; - - default: - if (CiscoKnownServices.IsKnownIcmpService(words[0])) - { - TcpUdpPortOperator = TcpUdpPortOperatorType.Eq; - TcpUdpPortValue = CiscoKnownServices.ConvertIcmpServiceToType(words[0]); - WordsCount = 1; - } - break; - } - } - } - else if (protocol == ProtocolType.KnownOtherIpProtocol) - { - } - } - - private bool IsServiceGroup(string name) - { - if (_ciscoIds.ContainsKey(name) && _ciscoIds[name].Name() == "object-group") - { - var group = (Cisco_GroupObject)_ciscoIds[name]; - if (group.GroupType == Cisco_GroupObject.Group_Type.Service || group.GroupType == Cisco_GroupObject.Group_Type.Icmp) - { - return true; - } - } - - return false; - } - - private bool IsServiceObject(string name) - { - if (_ciscoIds.ContainsKey(name) && _ciscoIds[name].Name() == "object") - { - var obj = (Cisco_Object)_ciscoIds[name]; - if (obj.ObjectType == Cisco_Object.ObjectTypes.TcpService || - obj.ObjectType == Cisco_Object.ObjectTypes.UdpService || - obj.ObjectType == Cisco_Object.ObjectTypes.IcmpService) - { - return true; - } - } - - return false; - } - } - - public string ACLName { get; set; } - public bool Inactive { get; set; } - public ActionType Action { get; set; } - public ProtocolType Protocol { get; set; } - public string ProtocolReference { get; set; } - public string Remark { get; set; } - public bool IsRemark { get; set; } - public bool IsTimeRangeSpecified { get; set; } - public string TimeRangeName { get; set; } - public SourceDest Source { get; set; } - public SourceDest Destination { get; set; } - public ProtocolProperties SourceProperties { get; set; } - public ProtocolProperties DestinationProperties { get; set; } - - public override string Name() { return "access-list"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - /* - * OPTION I - REMARK format - the easiest option: - * - access-list access_list_name remark text - Example: - hostname(config)# access-list ACL_OUT remark - this is the inside admin address - * - * OPTION II - STANDARD format - used for a limited number of features, such as route maps or VPN filters. - * uses IPv4 addresses only, and defines destination addresses only. - * - access-list access_list_name standard {deny | permit} {any/any4 | host ip_address | ip_address ip_mask} - Example: - hostname(config)# access-list OSPF standard permit 192.168.1.0 255.255.255.0 - * - * OPTION III.I - EXTENDED format - for ICMP based traffic matching - * - access-list access_list_name extended {deny | permit} icmp source_address_argument dest_address_argument [icmp_argument] [time-range time_range_name] [inactive] - Example: - hostname(config)# access-list ACL_IN extended permit icmp any any echo - * - * OPTION III.II - EXTENDED format - for TCP and UDP based traffic matching, with ports - * - access-list access_list_name extended {deny | permit} {tcp | udp} source_address_argument [port_argument] dest_address_argument [port_argument] [time-range time_range_name] [inactive] - Example: - hostname(config)# access-list ACL_IN extended deny tcp any host 209.165.201.29 eq www - hostname(config)# access-list ACL_IN extended deny tcp 192.168.1.0 255.255.255.0 209.165.201.0 255.255.255.224 - * - * OPTION III.III - EXTENDED format - for general IP address and FQDN based matching - * - access-list access_list_name extended {deny | permit} protocol_argument source_address_argument dest_address_argument [time-range time_range_name] [inactive] - Example: - hostname(config)# access-list ACL_IN extended permit ip any any - * - * ********************** - * ACL COMMAND ARGUMENTS: - * - * protocol_argument specification: one of the following options: - * -------------------------------------------------------------- - * protocol_name/protocol_number - * object service_object_id --> may be also a icmp service object - * object-group service_group_id - * object-group protocol_group_id - * - * source_address_argument/dest_address_argument specification: one of the following options: - * ------------------------------------------------------------------------------------------ - * any/any4/any6 - * host ip_address - * interface interface_name - * object network_object_id - * object-group network_group_id - * ip_address ip_mask - * - * icmp_argument specification: one of the following options: - * ---------------------------------------------------------- - * icmp_type - * object-group icmp_group_id --> object-group icmp-type command - * - * port_argument specification: one of the following options: - * ---------------------------------------------------------- - * operator port --> where operator can be one of: lt, gt, eq, neq, range; port can be number or name of a TCP or UDP port - * object-group service_group_id - * - */ - - base.Parse(command, prevCommand, ciscoIds, aliases); - - ACLName = command.GetParam(1); - Inactive = false; - Action = ActionType.NA; - Protocol = ProtocolType.NA; - ProtocolReference = ""; - Remark = ""; - IsRemark = false; +/******************************************************************** +Copyright (c) 2017, Check Point Software Technologies Ltd. +All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +********************************************************************/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using CommonUtils; + +namespace CiscoMigration +{ + public enum ProtocolType { NA, Ip, Icmp, Udp, Tcp, KnownOtherIpProtocol, ReferenceObject }; + public enum TcpUdpPortOperatorType { NA, All, Lt, Gt, Eq, Neq, Range, ReferenceObject }; + public enum ServiceDirection { Source, Destination }; + + public interface ICiscoCommand + { + string Name(); + void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases); + } + + /// + /// Represents a basic Cisco command. + /// Each derived command auto-parses the appropriate configuration line text according to its "name" (via reflection mechanism). + /// Some commands may have child commands (network group commad has child network object commands). + /// The "Id" property is the configuration line number. + /// The "ParentId" property is the parent configuration line number. + /// The "CiscoId" property is the user defined name of the command. + /// + public class CiscoCommand : ICiscoCommand + { + public const string InterfacePrefix = "Interface_"; + public const string Any = "any"; + + private string _text = ""; + private string[] _words; + + public string Text + { + get { return _text; } + set + { + _text = value; + + string trimmedText = _text.Trim(); + char[] delimiterChars = { ' ', '\t' }; + + // Replace multiple spaces with a single space + trimmedText = Regex.Replace(trimmedText, @"\s+", " "); + + _words = trimmedText.Split(delimiterChars); + } + } + + public int IndentationLevel + { + get + { + if (Text.Length == 0) + { + return 0; + } + + int pos = 0; + while (Text.Substring(pos, 1) == " ") + { + pos++; + } + return pos; + } + } + + public string FirstWord + { + get + { + if (_words != null && _words.Any()) + { + // This is a special handling!!! + // There are several commands that have the first word "ip"... + if (_words[0] == "ip") + { + if (_words.Count() > 1 && _words[1] == "address") + { + return _words[0] + " " + _words[1]; + } + if (_words.Count() > 3 && _words[1] == "verify" && _words[2] == "reverse-path" && _words[3] == "interface") + { + return _words[0] + " " + _words[1] + " " + _words[2] + " " + _words[3]; + } + } + else + { + return _words[0]; + } + } + + return ""; + } + } + + public int Id { get; set; } + public int? ParentId { get; set; } + public string CiscoId { get; set; } + public string Description { get; set; } + public string Tag { get; set; } + public string DataForNextElement { get; set; } + public bool KnownCommand { get; set; } + public bool NotAnInterestingCommand { get; set; } + public ConversionIncidentType ConversionIncidentType { get; set; } + public string ConversionIncidentMessage { get; set; } + public List Children { get; set; } + + public CiscoCommand() + { + CiscoId = ""; + Description = ""; + DataForNextElement = ""; + } + + public string GetParam(int pos) + { + if (_words == null || _words.Length <= pos) + { + return ""; + } + + return _words[pos]; + } + + public List GetParams(int pos) + { + var res = new List(); + + if (_words == null || !_words.Any()) + { + return res; + } + + for (int i = 0; i < _words.Length; i++) + { + if (i >= pos) + { + res.Add(_words[i]); + } + } + + return res; + } + + public int GetParamPosition(string paramName) + { + if (_words == null || !_words.Any()) + { + return -1; + } + + int pos = 0; + foreach (string word in _words) + { + if (word == paramName) + { + return pos; + } + pos++; + } + + return -1; + } + + public List Flatten() + { + var res = new List(); + res.Add(this); + + if (Children != null) + { + foreach (CiscoCommand child in Children) + { + foreach (CiscoCommand flattenchild in child.Flatten()) + { + res.Add(flattenchild); + } + } + } + + return res; + } + + public virtual string Name() { return ""; } + + public virtual void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + if (command.Children != null) + { + foreach (CiscoCommand child in command.Children) + { + if (child.Name() == "description") + { + Description = child.Description; + } + } + } + + ConversionIncidentType = ConversionIncidentType.None; + ConversionIncidentMessage = ""; + } + } + + public class Cisco_Description : CiscoCommand + { + public Cisco_Description() + { + NotAnInterestingCommand = true; + } + + public override string Name() { return "description"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + if (!string.IsNullOrEmpty(command.Text)) + { + Description = command.Text.Trim().Substring(Name().Length + 1); + } + + } + } + + public class Cisco_ASA : CiscoCommand + { + public string Version { get; set; } + + public override string Name() { return "ASA"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + const string version = "version"; + if (!string.IsNullOrEmpty(command.Text) && command.GetParam(1).ToLower() == version) + { + Version = command.Text.Trim().Substring(Name().Length + version.Length + 2); + } + else + { + Version = ""; + } + } + } + + public class Cisco_Alias : CiscoCommand + { + public override string Name() { return "name"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + string real = command.GetParam(1); + string alias = command.GetParam(2); + + if (!string.IsNullOrEmpty(alias) && !string.IsNullOrEmpty(real) && !aliases.ContainsKey(alias)) + { + aliases.Add(alias, real); + } + } + } + + public class Cisco_SSH : CiscoCommand + { + public string IpAddress { get; set; } + public string Netmask { get; set; } + public string Interface { get; set; } + + public override string Name() { return "ssh"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + IpAddress = ""; + Netmask = ""; + Interface = ""; + + string commandParam = command.GetParam(1); + if (NetworkUtils.IsValidIp(commandParam)) + { + IpAddress = commandParam; + } + else + { + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "IPv4 address was expected, but '" + commandParam + "' was found."; + return; + } + + commandParam = command.GetParam(2); + if (NetworkUtils.IsValidNetmask(commandParam)) + { + Netmask = commandParam; + } + else + { + IpAddress = ""; + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "IPv4 netmask was expected, but " + commandParam + " was found."; + return; + } + + Interface = command.GetParam(3); + } + } + + public class Cisco_Hostname : CiscoCommand + { + public string HostName { get; set; } + + public override string Name() { return "hostname"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + HostName = command.GetParam(1); + } + } + + public class Cisco_Object : CiscoCommand + { + public enum ObjectTypes { NA, Fqdn, Host, Network, Range, TcpService, UdpService, IcmpService, KnownOtherService }; + + public ObjectTypes ObjectType { get; set; } + public string Fqdn { get; set; } + public string HostAddress { get; set; } + public string Network { get; set; } + public string Netmask { get; set; } + public string RangeFrom { get; set; } + public string RangeTo { get; set; } + public bool IsDestination { get; set; } + public string ServiceProtocol { get; set; } + public string ServiceOperator { set; get; } + public string ServicePort { get; set; } + + public override string Name() { return "object"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + CiscoId = command.GetParam(2); + ObjectType = ObjectTypes.NA; + + switch (command.GetParam(1)) + { + case "network": + ParseNetworks(); + break; + + case "service": + ParseServices(); + break; + + default: + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "Unrecognized object type (" + command.GetParam(1) + ")"; + break; + } + } + + private void ParseNetworks() + { + if (Children == null) + { + return; + } + + int found = 0; + + foreach (CiscoCommand child in Children) + { + switch (child.Name()) + { + case "fqdn": + ObjectType = ObjectTypes.Fqdn; + Fqdn = ((Cisco_Fqdn)child).Fqdn; + found++; + break; + + case "host": + ObjectType = ObjectTypes.Host; + HostAddress = ((Cisco_Host)child).HostAddress; + found++; + break; + + case "subnet": + ObjectType = ObjectTypes.Network; + Network = ((Cisco_Subnet)child).Network; + Netmask = ((Cisco_Subnet)child).Netmask; + found++; + break; + + case "range": + ObjectType = ObjectTypes.Range; + RangeFrom = ((Cisco_Range)child).RangeFrom; + RangeTo = ((Cisco_Range)child).RangeTo; + found++; + break; + } + + if (found == 1) + { + if (child.ConversionIncidentType != ConversionIncidentType.None) + { + ConversionIncidentType = child.ConversionIncidentType; + ConversionIncidentMessage = child.ConversionIncidentMessage; + } + } + } + + if (found > 1) + { + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "An Object (network) can only hold one fqdn, host, range or subnet"; + Console.WriteLine(ConversionIncidentMessage); + } + } + + private void ParseServices() + { + if (Children == null) + { + return; + } + + int found = 0; + + foreach (CiscoCommand child in Children) + { + if (child.Name() == "service") + { + found++; + + var service = (Cisco_Service)child; + ServiceProtocol = service.Protocol; + ServiceOperator = service.Operator; + ServicePort = service.Port; + IsDestination = service.IsDestination; + + if (service.ConversionIncidentType != ConversionIncidentType.None) + { + ConversionIncidentType = service.ConversionIncidentType; + ConversionIncidentMessage = service.ConversionIncidentMessage; + } + + switch (ServiceProtocol) + { + case "ip": + // Predefined "any" object. No special handling... + break; + + case "icmp": + ObjectType = ObjectTypes.IcmpService; + break; + + case "tcp": + ObjectType = ObjectTypes.TcpService; + break; + + case "udp": + ObjectType = ObjectTypes.UdpService; + break; + + default: + // No need to check also for CiscoKnownServices.IsKnownServiceNumber here, + // because it is already done in Cisco_Service class!!! + if (CiscoKnownServices.IsKnownService(ServiceProtocol)) + { + ObjectType = ObjectTypes.KnownOtherService; + } + else + { + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Unrecognized service protocol (" + ServiceProtocol + ")"; + Console.WriteLine(ConversionIncidentMessage); + } + break; + } + } + } + + if (found > 1) + { + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "An Object (service) can only hold one service"; + Console.WriteLine(ConversionIncidentMessage); + } + } + } + + public class Cisco_Fqdn : CiscoCommand + { + public string Fqdn { get; set; } + + public override string Name() { return "fqdn"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + Fqdn = (command.GetParam(1) == "v4") ? command.GetParam(2) : command.GetParam(1); + } + } + + public class Cisco_Host : CiscoCommand + { + public string HostAddress { get; set; } + + public override string Name() { return "host"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + HostAddress = command.GetParam(1); + if (!NetworkUtils.IsValidIp(HostAddress)) + { + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Invalid host IP address (" + HostAddress + "). Using IP 1.1.1.1."; + Console.WriteLine(ConversionIncidentMessage); + + HostAddress = "1.1.1.1"; + } + } + } + + public class Cisco_Subnet : CiscoCommand + { + public string Network { get; set; } + public string Netmask { get; set; } + + public override string Name() { return "subnet"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + Network = command.GetParam(1); + Netmask = command.GetParam(2); + + if (!NetworkUtils.IsValidIp(Network) || !NetworkUtils.IsValidNetmask(Netmask)) + { + 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"; + } + } + } + + public class Cisco_Range : CiscoCommand + { + public string RangeFrom { get; set; } + public string RangeTo { get; set; } + + public override string Name() { return "range"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + RangeFrom = command.GetParam(1); + if (!NetworkUtils.IsValidIp(RangeFrom)) + { + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Invalid range starting IP address (" + RangeFrom + "). Using IP 0.0.0.0."; + Console.WriteLine(ConversionIncidentMessage); + + RangeFrom = "0.0.0.0"; + } + + RangeTo = command.GetParam(2); + if (!NetworkUtils.IsValidIp(RangeTo)) + { + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Invalid range ending IP address (" + RangeTo + "). Using IP 255.255.255.255."; + Console.WriteLine(ConversionIncidentMessage); + + RangeTo = "255.255.255.255"; + } + } + } + + public class Cisco_Service : CiscoCommand + { + public string Protocol { get; set; } + public bool IsDestination { get; set; } + public string Port { get; set; } + public string Operator { get; set; } + + public override string Name() { return "service"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + // Parsing Options: + //----------------- + // 1. service protocol_name_or_number + // 2. service {icmp | icmp6} [icmp-type] + // 3. service {tcp | udp} [source operator port] [destination operator port] + //----------------- + + Protocol = command.GetParam(1); + + IsDestination = false; + Port = ""; + Operator = ""; + + switch (Protocol) + { + case "ip": + IsDestination = true; + break; + + case "icmp": + case "icmp6": + IsDestination = true; + Protocol = "icmp"; + Operator = "eq"; + Port = CiscoKnownServices.ConvertIcmpServiceToType(command.GetParam(2)); + break; + + case "tcp": + case "udp": + IsDestination = (command.GetParam(2) == "destination"); + Operator = command.GetParam(3); + Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(4)); + + int nextParamId = 5; // we need this because of 'range' operator + + if (Operator == "range") + { + Operator = "eq"; + Port = Port + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(5)); + nextParamId = 6; // !!! + } + + if (!IsDestination && command.GetParam(nextParamId) == "destination") + { + // "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); + Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(nextParamId + 2)); + + if (Operator == "range") + { + Operator = "eq"; + Port = Port + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(nextParamId + 3)); + } + } + + if (string.IsNullOrEmpty(Operator) || string.IsNullOrEmpty(Port)) + { + // Use ALL tcp/udp ports if nothing specified!!! + IsDestination = true; + Operator = "all"; + Port = "1-65535"; + } + break; + + default: + IsDestination = true; + + string serviceName; + if (CiscoKnownServices.IsKnownService(Protocol)) + { + Port = CiscoKnownServices.ConvertServiceToPort(Protocol); + } + else if (CiscoKnownServices.IsKnownServiceNumber(Protocol, out serviceName)) // protocol number is used!!! + { + Port = Protocol; + Protocol = serviceName; + } + else + { + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Unrecognized service protocol (" + Protocol + ")"; + Console.WriteLine(ConversionIncidentMessage); + } + break; + } + } + } + + public class Cisco_NetworkObject : CiscoCommand + { + public string IpAddress { get; set; } + public string Netmask { get; set; } + public string ReferencedObject { get; set; } + + public override string Name() { return "network-object"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + IpAddress = ""; + Netmask = ""; + ReferencedObject = ""; + + switch (command.GetParam(1)) + { + case "object": + ReferencedObject = command.GetParam(2); + break; + + case "host": + string ipAddressOrObjectName = command.GetParam(2); + if (ciscoIds.ContainsKey(ipAddressOrObjectName)) + { + ReferencedObject = ipAddressOrObjectName; + } + else + { + IpAddress = aliases.ContainsKey(ipAddressOrObjectName) ? aliases[ipAddressOrObjectName] : ipAddressOrObjectName; + if (!NetworkUtils.IsValidIp(IpAddress)) + { + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Invalid IP address (" + IpAddress + "). Using IP 1.1.1.1."; + Console.WriteLine(ConversionIncidentMessage); + + IpAddress = "1.1.1.1"; + } + + Netmask = "255.255.255.255"; + } + break; + + default: + // subnet + IpAddress = command.GetParam(1); + if (aliases.ContainsKey((IpAddress))) + { + IpAddress = aliases[IpAddress]; + } + Netmask = command.GetParam(2); + + if (!NetworkUtils.IsValidIp(IpAddress) || !NetworkUtils.IsValidNetmask(Netmask)) + { + 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"; + } + break; + } + } + } + + public class Cisco_ProtocolObject : CiscoCommand + { + public string ProtocolName { get; set; } + + public override string Name() { return "protocol-object"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + ProtocolName = command.GetParam(1); + } + } + + public class Cisco_PortObject : CiscoCommand + { + public string Port { get; set; } + + public override string Name() { return "port-object"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + Port = ""; + + string portOperator = command.GetParam(1); + + switch (portOperator) + { + case "eq": + Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(2)); + break; + + case "range": + Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(2)) + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(3)); + break; + } + } + } + + public class Cisco_ServiceObject : CiscoCommand + { + public string Protocol { get; set; } + public bool IsDestination { get; set; } + public string Port { get; set; } + public string Operator { get; set; } + public string RefObjectName { get; set; } + + public override string Name() { return "service-object"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + // Parsing Options: + //----------------- + // 1. service-object object object_name + // 2. service-object protocol_name_or_number + // 3. service-object {icmp | icmp6} [icmp-type] + // 4. service-object {tcp | udp | tcp-udp} [source operator port] [destination operator port] + //----------------- + + Protocol = command.GetParam(1); + + IsDestination = false; + Port = ""; + Operator = ""; + RefObjectName = ""; + + switch (Protocol) + { + case "object": + RefObjectName = command.GetParam(2); + Protocol = ""; + break; + + case "ip": + IsDestination = true; + break; + + case "icmp": + case "icmp6": + IsDestination = true; + Protocol = "icmp"; + Operator = "eq"; + Port = CiscoKnownServices.ConvertIcmpServiceToType(command.GetParam(2)); + break; + + case "tcp": + case "udp": + case "tcp-udp": + IsDestination = (command.GetParam(2) == "destination"); + Operator = command.GetParam(3); + Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(4)); + + int nextParamId = 5; // we need this because of 'range' operator + + if (Operator == "range") + { + Operator = "eq"; + Port = Port + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(5)); + nextParamId = 6; // !!! + } + + if (!IsDestination && command.GetParam(nextParamId) == "destination") + { + // "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); + Port = CiscoKnownServices.ConvertServiceToPort(command.GetParam(nextParamId + 2)); + + if (Operator == "range") + { + Operator = "eq"; + Port = Port + "-" + CiscoKnownServices.ConvertServiceToPort(command.GetParam(nextParamId + 3)); + } + } + + if (string.IsNullOrEmpty(Operator) || string.IsNullOrEmpty(Port)) + { + // Use ALL tcp/udp ports if nothing specified!!! + IsDestination = true; + Operator = "all"; + Port = "1-65535"; + } + break; + + default: + IsDestination = true; + + string serviceName; + if (CiscoKnownServices.IsKnownService(Protocol)) + { + Port = CiscoKnownServices.ConvertServiceToPort(Protocol); + } + else if (CiscoKnownServices.IsKnownServiceNumber(Protocol, out serviceName)) // protocol number is used!!! + { + Port = Protocol; + Protocol = serviceName; + } + else + { + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Unrecognized service protocol (" + Protocol + ")"; + Console.WriteLine(ConversionIncidentMessage); + } + break; + } + } + } + + public class Cisco_IcmpObject : CiscoCommand + { + public string IcmpType { get; set; } + + public override string Name() { return "icmp-object"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + IcmpType = command.GetParam(1); + } + } + + public class Cisco_ReferenceGroupObject : CiscoCommand + { + public string ReferenceId { get; set; } + + public override string Name() { return "group-object"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + ReferenceId = command.GetParam(1); + } + } + + public class Cisco_GroupObject : CiscoCommand + { + public enum Group_Type { NA, Service, Protocol, Icmp, Network }; + + private Dictionary _ciscoIds; + + public Group_Type GroupType { get; set; } + public string ServiceProtocol { get; set; } + + public List Protocols = new List(); + public List IcmpTypes = new List(); + public List MembersGroupNames = new List(); + public List MemberObjects = new List(); + + public override string Name() { return "object-group"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + _ciscoIds = ciscoIds; + + CiscoId = command.GetParam(2); + ServiceProtocol = ""; + + switch (command.GetParam(1)) + { + case "service": + GroupType = Group_Type.Service; + break; + + case "protocol": + GroupType = Group_Type.Protocol; + break; + + case "icmp-type": + GroupType = Group_Type.Icmp; + break; + + case "network": + GroupType = Group_Type.Network; + break; + + default: + GroupType = Group_Type.NA; + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "Unrecognized group type (" + command.GetParam(1) + ")"; + return; + } + + if (GroupType == Group_Type.Service) + { + ServiceProtocol = command.GetParam(3); + } + + if (command.Children == null) + { + return; + } + + foreach (CiscoCommand child in command.Children) + { + bool hasValidChild = true; + + switch (child.Name()) + { + case "protocol-object": + Protocols.Add(((Cisco_ProtocolObject)child).ProtocolName); + break; + + case "port-object": + MemberObjects.Add((Cisco_PortObject)child); + break; + + case "icmp-object": + IcmpTypes.Add(((Cisco_IcmpObject)child).IcmpType); + break; + + case "group-object": + MembersGroupNames.Add(((Cisco_ReferenceGroupObject)child).ReferenceId); + break; + + case "network-object": + MemberObjects.Add((Cisco_NetworkObject)child); + break; + + case "service-object": + MemberObjects.Add((Cisco_ServiceObject)child); + break; + + default: + hasValidChild = false; + break; + } + + if (hasValidChild) + { + if (child.ConversionIncidentType != ConversionIncidentType.None) + { + ConversionIncidentType = child.ConversionIncidentType; + ConversionIncidentMessage = child.ConversionIncidentMessage; + } + } + } + } + + public List GetChildServices() + { + var services = new List(); + + if (Children != null) + { + foreach (CiscoCommand child in Children) + { + if (child.Name() == "service-object") + { + services.Add((Cisco_ServiceObject)child); + } + else if (child.Name() == "group-object") + { + if (_ciscoIds.ContainsKey(((Cisco_ReferenceGroupObject)child).ReferenceId)) + { + var referencedGroupObject = (Cisco_GroupObject)_ciscoIds[((Cisco_ReferenceGroupObject)child).ReferenceId]; + var referencedGroupServices = referencedGroupObject.GetChildServices(); + + foreach (Cisco_ServiceObject referencedService in referencedGroupServices) + { + if (!services.Contains(referencedService)) + { + services.Add(referencedService); + } + } + } + } + } + } + + return services; + } + + public List GetChildPorts() + { + var ports = new List(); + + if (Children != null) + { + foreach (CiscoCommand child in Children) + { + if (child.Name() == "port-object") + { + ports.Add((Cisco_PortObject)child); + } + else if (child.Name() == "group-object") + { + if (_ciscoIds.ContainsKey(((Cisco_ReferenceGroupObject)child).ReferenceId)) + { + var referencedGroupObject = (Cisco_GroupObject)_ciscoIds[((Cisco_ReferenceGroupObject)child).ReferenceId]; + var referencedGroupPorts = referencedGroupObject.GetChildPorts(); + + foreach (Cisco_PortObject referencedPort in referencedGroupPorts) + { + if (!ports.Contains(referencedPort)) + { + ports.Add(referencedPort); + } + } + } + } + } + } + + return ports; + } + } + + public class Cisco_SecurityLevel : CiscoCommand + { + public string Value { get; set; } + + public override string Name() { return "security-level"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + Value = command.GetParam(1); + } + } + + public class Cisco_NameIf : CiscoCommand + { + public string Value { get; set; } + + public override string Name() { return "nameif"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + Value = InterfacePrefix + command.GetParam(1); + } + } + + public class Cisco_VLan : CiscoCommand + { + public string Value { get; set; } + + public override string Name() { return "vlan"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + Value = command.GetParam(1); + } + } + + public class Cisco_IP : CiscoCommand + { + public string IpAddress { get; set; } + public string Netmask { get; set; } + + public override string Name() { return "ip address"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + IpAddress = ""; + Netmask = ""; + + if (command.GetParam(1) == "address") + { + IpAddress = command.GetParam(2); + Netmask = command.GetParam(3); + } + } + } + + public class Cisco_Shutdown : CiscoCommand + { + public bool IsShutdown { get; set; } + + public override string Name() { return "shutdown"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + IsShutdown = (command.GetParam(0) == "shutdown"); + } + } + + public class Cisco_ManagementOnly : CiscoCommand + { + public bool IsManagementOnly { get; set; } + + public override string Name() { return "management-only"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + IsManagementOnly = (command.GetParam(0) == "management-only"); + } + } + + public class Cisco_TimeRange : CiscoCommand + { + public enum Weekdays { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; + + private string _timeRangeName; + + private string _startDateTime; + private string _endDateTime; + + private List _periodicsList; + + public string TimeRangeName + { + get { return _timeRangeName; } + } + + public string StartDateTime + { + get { return _startDateTime; } + } + + public string EndDateTime + { + get { return _endDateTime; } + } + + public List PeriodicsList + { + get { return _periodicsList; } + } + + public override string Name() { return "time-range"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + _periodicsList = new List(); + + _timeRangeName = this.GetParam(1); + + foreach(CiscoCommand child in Children) + { + if(child.FirstWord.Equals("absolute")) + { + int startIndex = child.Text.IndexOf("start"); + int endIndex = child.Text.IndexOf("end"); + if(startIndex > -1 && endIndex > -1) + { + _startDateTime = child.Text.Substring("absolute".Length + "start".Length + 2, endIndex - startIndex - "start".Length).Trim(); + _endDateTime = child.Text.Substring(endIndex + "end".Length).Trim(); + } + else if (startIndex > -1 && endIndex == -1) + { + _startDateTime = child.Text.Substring("absolute".Length + "start".Length + 2).Trim(); + } + else if(startIndex == -1 && endIndex > -1) + { + _endDateTime = child.Text.Substring("absolute".Length + "end".Length + 2).Trim(); + } + } + + if (child.FirstWord.Equals("periodic")) + { + string period = child.Text.Substring("periodic".Length + 1).Trim(); + + string[] daysTimes = period.Trim().Split(new string[] { "to" }, StringSplitOptions.RemoveEmptyEntries); + + string[] daysTimes_1 = daysTimes[0].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); + string[] daysTimes_2 = daysTimes[1].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); + + if (daysTimes_1.Length == 2 && daysTimes_2.Length == 2) + { + int startWdIndex = (int)Enum.Parse(typeof(Weekdays), daysTimes_1[0]); + int endWdIndex = (int)Enum.Parse(typeof(Weekdays), daysTimes_2[0]); + + if (startWdIndex < endWdIndex) + { + _periodicsList.Add((Weekdays)startWdIndex + " " + daysTimes_1[1] + " to 23:59"); + + for (int i = startWdIndex+1; i <= endWdIndex-1; i++) + { + _periodicsList.Add((Weekdays)i + " 0:00 to 23:59"); + } + + _periodicsList.Add((Weekdays)endWdIndex + " 0:00 to " + daysTimes_2[1]); + } + else + { + int firstWdIndex = (int)Enum.GetValues(typeof(Weekdays)).Cast().First(); + int lastWdIndex = (int)Enum.GetValues(typeof(Weekdays)).Cast().Last(); + + _periodicsList.Add((Weekdays)startWdIndex + " " + daysTimes_1[1] + " to 23:59"); + + for (int i = startWdIndex + 1; i <= lastWdIndex; i++) + { + _periodicsList.Add((Weekdays)i + " 0:00 to 23:59"); + } + + for (int i = firstWdIndex; i <= endWdIndex-1; i++) + { + _periodicsList.Add((Weekdays)i + " 0:00 to 23:59"); + } + + _periodicsList.Add((Weekdays)endWdIndex + " 0:00 to " + daysTimes_2[1]); + } + } + else + { + _periodicsList.Add(period); + } + } + } + } + } + + public class Cisco_Interface : CiscoCommand + { + public string InterfaceName { get; set; } + public int SecurityLevel { get; set; } + public string VLan { get; set; } + public string IpAddress { get; set; } + public string Netmask { get; set; } + public bool Shutdown { get; set; } + public bool ManagementOnly { get; set; } + public bool LeadsToInternet { get; set; } + + public class Subnet + { + public string Network { get; private set; } + public string Netmask { get; private set; } + + public Subnet (string sIp, string sMask) + { + Network = sIp; + Netmask = sMask; + } + } + + public List Topology = new List(); + + public override string Name() { return "interface"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + InterfaceName = command.GetParam(1); + SecurityLevel = 0; + VLan = ""; + IpAddress = ""; + Netmask = ""; + Shutdown = false; + ManagementOnly = false; + LeadsToInternet = false; + + if (command.Children == null) + { + return; + } + + foreach (CiscoCommand child in command.Children) + { + switch (child.Name()) + { + case "security-level": + int securityLevel; + if (int.TryParse(((Cisco_SecurityLevel)child).Value, out securityLevel)) + { + SecurityLevel = securityLevel; + } + break; + + case "nameif": + CiscoId = ((Cisco_NameIf)child).Value; + break; + + case "vlan": + VLan = ((Cisco_VLan)child).Value; + break; + + case "shutdown": + Shutdown = ((Cisco_Shutdown)child).IsShutdown; + break; + + case "management-only": + ManagementOnly = ((Cisco_ManagementOnly)child).IsManagementOnly; + break; + + case "ip address": + IpAddress = ((Cisco_IP)child).IpAddress; + Netmask = ((Cisco_IP)child).Netmask; + + if (NetworkUtils.IsValidIp(IpAddress) && NetworkUtils.IsValidNetmask(Netmask)) + { + Topology.Add(new Subnet(NetworkUtils.GetNetwork(IpAddress, Netmask), Netmask)); + } + else + { + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Invalid IP subnet (" + IpAddress + "/" + Netmask + ")."; + Console.WriteLine(ConversionIncidentMessage); + } + break; + } + } + } + + public bool HasValidIpAddress() + { + return NetworkUtils.IsValidIp(IpAddress) && NetworkUtils.IsValidNetmask(Netmask); + } + } + + public class Cisco_Route : CiscoCommand + { + public string InterfaceName { get; set; } + public bool DefaultRoute { get; set; } + public string DestinationIp { get; set; } + public string DestinationNetmask { get; set; } + public string Gateway { get; set; } + + public override string Name() { return "route"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + DefaultRoute = false; + InterfaceName = command.GetParam(1); + DestinationIp = command.GetParam(2); + DestinationNetmask = command.GetParam(3); + Gateway = command.GetParam(4); + + bool destinationIpResolved = false; + + if (ciscoIds.ContainsKey(DestinationIp)) + { + var refObj = (Cisco_Object)ciscoIds[DestinationIp]; + if (refObj != null) + { + switch (refObj.ObjectType) + { + case Cisco_Object.ObjectTypes.Host: + DestinationIp = refObj.HostAddress; + destinationIpResolved = true; + break; + + case Cisco_Object.ObjectTypes.Network: + DestinationIp = refObj.Network; + destinationIpResolved = true; + break; + } + } + } + else + { + DestinationIp = aliases.ContainsKey(DestinationIp) ? aliases[DestinationIp] : DestinationIp; + destinationIpResolved = true; + } + + if (!destinationIpResolved) + { + 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"; + } + + if (!NetworkUtils.IsValidIp(DestinationIp)) + { + 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"; + } + + if (DestinationIp == "0.0.0.0" && DestinationNetmask == "0.0.0.0") + { + DefaultRoute = true; + } + } + } + + public class Cisco_AntiSpoofing : CiscoCommand + { + public string InterfaceName { get; set; } + + public override string Name() { return "ip verify reverse-path interface"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + if (command.GetParam(1) == "verify" && command.GetParam(2) == "reverse-path" && command.GetParam(3) == "interface") + { + InterfaceName = command.GetParam(4); + } + } + } + + public class Cisco_SameSecurityTraffic : CiscoCommand + { + public enum InterfaceTrafficType { NA, Inter, Intra }; + + public InterfaceTrafficType TrafficType { get; set; } + + public override string Name() { return "same-security-traffic"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + if (command.GetParam(1) == "permit") + { + switch (command.GetParam(2)) + { + case "inter-interface": + TrafficType = InterfaceTrafficType.Inter; + break; + + case "intra-interface": + TrafficType = InterfaceTrafficType.Intra; + break; + } + } + } + } + + public class Cisco_Nat : CiscoCommand + { + public bool Inactive { get; set; } + public string RealInterface { get; set; } + public string MappedInterface { get; set; } + public bool IsStatic { get; set; } + public bool IsHideBehindInterface { get; set; } + public bool IsUnidirectional { get; set; } + public bool IsAutoAfter { get; set; } + public string StaticNatIpAddressOrObjectName { get; set; } + public string DynamicNatIpAddressOrObjectName { get; set; } + public string SourceId { get; set; } + public string TranslatedSourceId { get; set; } + public string DestinationId { get; set; } + public string TranslatedDestinationId { get; set; } + public string ServiceProtocol { get; set; } + public string ServiceId { get; set; } + public string TranslatedServiceId { get; set; } + + public override string Name() { return "nat"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + /************************************************************************************** + * There are two types of NAT: + * 1. Object NAT - child object of a Network Object - this is the commonly used NAT + * 2. Regular NAT - twice or manual NAT rule - more scalable, enables extra features over Object NAT + * + * Each of these two types may be Static or Dynamic. + * Static NAT allows bidirectional traffic (mirrored rules). + * + * Each NAT command is started as follows: + * --------------------------------------- + * nat [(real_interface, mapped_interface)] ... + * + **************************************************************************************/ + + base.Parse(command, prevCommand, ciscoIds, aliases); + + string param = command.GetParam(1).Trim(new char[] { '(', ')' }); + string[] interfaces = param.Split(','); + + if (interfaces.Length > 0) + { + RealInterface = interfaces[0]; + MappedInterface = (interfaces.Length > 1) ? interfaces[1] : ""; + } + else + { + RealInterface = ""; + MappedInterface = ""; + } + + Inactive = false; + IsStatic = false; + IsHideBehindInterface = false; + IsUnidirectional = false; + StaticNatIpAddressOrObjectName = ""; + DynamicNatIpAddressOrObjectName = ""; + SourceId = ""; + TranslatedSourceId = ""; + DestinationId = ""; + TranslatedDestinationId = ""; + ServiceProtocol = ""; + ServiceId = ""; + TranslatedServiceId = ""; + + if (command.IndentationLevel > 0) + { + ParseObjectNatCommand(command, prevCommand, ciscoIds); + } + else + { + ParseRegularNatCommand(command, prevCommand, ciscoIds); + } + + if (command.GetParamPosition("unidirectional") > 0/* || command.GetParamPosition("no-proxy-arp") > 0*/) // commented due to A.R. suggestion... + { + IsUnidirectional = true; + } + + if (command.GetParamPosition("inactive") > 0) + { + Inactive = true; + } + } + + private void ParseObjectNatCommand(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds) + { + /******************************************************** + * Parsing options for Object NAT: + * ------------------------------- + * ... static {mapped_host_ip_address | mapped_object_name | interface} [service {tcp | udp} real_port mapped_port] + * + * ... dynamic {mapped_host_ip_address | mapped_object_name | interface} + * + * + mapped_object may be a host or network or range + */ + + switch (command.GetParam(2)) + { + case "static": + IsStatic = true; + + if (command.GetParam(3) == "interface") + { + IsHideBehindInterface = true; // Static NAT with port-translation + } + else + { + // static hide behind an arbitrary ip/network + StaticNatIpAddressOrObjectName = command.GetParam(3); + } + + int servicePos = command.GetParamPosition("service"); + if (servicePos > 0) + { + ServiceProtocol = command.GetParam(servicePos + 1); + if (ServiceProtocol == "tcp" || ServiceProtocol == "udp") + { + ServiceId = CiscoKnownServices.ConvertServiceToPort(command.GetParam(servicePos + 2)); + TranslatedServiceId = CiscoKnownServices.ConvertServiceToPort(command.GetParam(servicePos + 3)); + } + else + { + ServiceProtocol = ""; + + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Unrecognized service protocol (" + ServiceProtocol + ")"; + Console.WriteLine(ConversionIncidentMessage); + } + } + break; + + case "dynamic": + if (command.GetParam(3) == "interface") + { + IsHideBehindInterface = true; + } + else + { + // dynamic hide behind an arbitrary ip/network + DynamicNatIpAddressOrObjectName = command.GetParam(3); + } + + // Check for interface fall-back configuration + if (command.GetParam(4) == "interface") + { + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "Interface fall-back for dynamic object NAT is not supported"; + Console.WriteLine(ConversionIncidentMessage); + } + break; + } + } + + private void ParseRegularNatCommand(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds) + { + /******************************************************** + * Parsing options for regular (manual or twice) NAT: + * -------------------------------------------------- + * ... [after-object] source static real_object_name [mapped_object_name | interface] [destination static mapped_object_name real_object_name] [service real_service_name mapped_service_name] + * + * ... [after-auto] source dynamic {real_object_name | any} {mapped_object_name | interface} [destination static mapped_object_name real_object_name] [service mapped_service_name real_service_name] + * + * + real_object/mapped_object may be a host or network + */ + + int sourcePos = 2; + + if (command.GetParam(2) == "after-auto" || command.GetParam(2) == "after-object") + { + IsAutoAfter = true; + sourcePos = 3; + } + + if (command.GetParam(sourcePos) == "source") + { + if (command.GetParam(sourcePos + 1) == "static") + { + IsStatic = true; + } + + SourceId = command.GetParam(sourcePos + 2); + TranslatedSourceId = command.GetParam(sourcePos + 3); + if (TranslatedSourceId == "interface") + { + IsHideBehindInterface = true; + } + + int destPos = command.GetParamPosition("destination"); + if (destPos > 0) // twice-NAT + { + // check sanity + if (command.GetParam(destPos + 1) != "static") + { + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "Not handling NAT with dynamic destination"; + Console.WriteLine(ConversionIncidentMessage); + return; + } + + DestinationId = command.GetParam(destPos + 2); + TranslatedDestinationId = command.GetParam(destPos + 3); + } + + int servicePos = command.GetParamPosition("service"); + if (servicePos > 0) + { + ServiceId = command.GetParam(servicePos + 1); + TranslatedServiceId = command.GetParam(servicePos + 2); + } + } + else + { + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "Not handling NAT with dynamic source"; + Console.WriteLine(ConversionIncidentMessage); + } + } + } + + public class Cisco_AccessGroup : CiscoCommand + { + public enum DirectionType { Inbound, Outbound, Global }; + + public DirectionType Direction { get; set; } + public string AccessListName { get; set; } + public string InterfaceName { get; set; } + + public override string Name() { return "access-group"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + // Parsing Options: + //----------------- + // access-group access_list_name {{in | out} interface interface_name | global} + //----------------- + + base.Parse(command, prevCommand, ciscoIds, aliases); + + AccessListName = command.GetParam(1); + InterfaceName = (command.GetParam(3) == "interface") ? command.GetParam(4) : ""; + + switch (command.GetParam(2)) + { + case "in": + Direction = DirectionType.Inbound; + break; + + case "out": + Direction = DirectionType.Outbound; + break; + + case "global": + Direction = DirectionType.Global; + break; + + default: + Console.WriteLine("Error: unknown access-group traffic direction (" + command.GetParam(2) + ")."); + break; + } + + if (Direction != DirectionType.Inbound && Direction != DirectionType.Global) + { + ConversionIncidentType = ConversionIncidentType.Informative; + ConversionIncidentMessage = "Outbound ACLs will not be converted"; + Console.WriteLine(ConversionIncidentMessage); + } + } + } + + public class Cisco_AccessList : CiscoCommand + { + public enum ActionType { NA, Deny, Permit }; + + public class SourceDest + { + public enum SourceDestType { NA, Any, Any6, ReferenceObject, Host, SubnetAndMask }; + + public SourceDestType Type { get; set; } + public string HostIp { get; set; } + public string Subnet { get; set; } + public string Netmask { get; set; } + public string RefObjectName { get; set; } + public int WordsCount { get; set; } + + public SourceDest() + { + Type = SourceDestType.NA; + HostIp = ""; + Subnet = ""; + Netmask = ""; + RefObjectName = ""; + WordsCount = -1; + } + + public SourceDest(List words) : this() + { + if (!words.Any()) + { + WordsCount = 0; + return; + } + + switch (words[0]) + { + case "any": + case "any4": + Type = SourceDestType.Any; + WordsCount = 1; + break; + + case "any6": + Type = SourceDestType.Any6; + WordsCount = 1; + break; + + case "host": + Type = SourceDestType.Host; + if (words.Count > 1) + { + HostIp = words[1]; + WordsCount = 2; + } + break; + + case "object-group": + case "object": + Type = SourceDestType.ReferenceObject; + if (words.Count > 1) + { + RefObjectName = words[1]; + WordsCount = 2; + } + break; + + case "interface": + Type = SourceDestType.ReferenceObject; + if (words.Count > 1) + { + RefObjectName = InterfacePrefix + words[1]; + WordsCount = 2; + } + break; + + default: + // both the ip_address and ip_mask are specified + Type = SourceDestType.SubnetAndMask; + if (words.Count > 1) + { + Subnet = words[0]; + Netmask = words[1]; + WordsCount = 2; + } + break; + } + } + } + + public class ProtocolProperties + { + private Dictionary _ciscoIds; + + public ProtocolType Protocol { get; set; } + public TcpUdpPortOperatorType TcpUdpPortOperator { get; set; } + public ServiceDirection Where { get; set; } + public string TcpUdpPortValue { get; set; } + public int WordsCount { get; set; } + + public ProtocolProperties() + { + Protocol = ProtocolType.NA; + TcpUdpPortOperator = TcpUdpPortOperatorType.NA; + Where = ServiceDirection.Destination; + TcpUdpPortValue = ""; + WordsCount = -1; + } + + public ProtocolProperties(ProtocolType protocol, List words, Dictionary ciscoIds, ServiceDirection where) : this() + { + _ciscoIds = ciscoIds; + Protocol = protocol; + Where = where; + WordsCount = 0; + + if (protocol == ProtocolType.Ip || + protocol == ProtocolType.Tcp || + protocol == ProtocolType.Udp || + protocol == ProtocolType.ReferenceObject) + { + TcpUdpPortOperator = TcpUdpPortOperatorType.All; + + if (words.Count > 0) + { + switch (words[0]) + { + case "range": + TcpUdpPortOperator = TcpUdpPortOperatorType.Range; + if (words.Count > 2) + { + TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]) + "-" + + CiscoKnownServices.ConvertServiceToPort(words[2]); + WordsCount = 3; + } + break; + + case "lt": + TcpUdpPortOperator = TcpUdpPortOperatorType.Lt; + if (words.Count > 1) + { + TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]); + WordsCount = 2; + } + break; + + case "gt": + TcpUdpPortOperator = TcpUdpPortOperatorType.Gt; + if (words.Count > 1) + { + TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]); + WordsCount = 2; + } + break; + + case "eq": + TcpUdpPortOperator = TcpUdpPortOperatorType.Eq; + if (words.Count > 1) + { + TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]); + WordsCount = 2; + } + break; + + case "neq": + TcpUdpPortOperator = TcpUdpPortOperatorType.Neq; + if (words.Count > 1) + { + TcpUdpPortValue = CiscoKnownServices.ConvertServiceToPort(words[1]); + WordsCount = 2; + } + break; + + + case "object": + if (words.Count > 1 && IsServiceObject(words[1])) + { + TcpUdpPortOperator = TcpUdpPortOperatorType.ReferenceObject; + TcpUdpPortValue = words[1]; + WordsCount = 2; + } + break; + + case "object-group": + if (words.Count > 1 && IsServiceGroup(words[1])) + { + TcpUdpPortOperator = TcpUdpPortOperatorType.ReferenceObject; + TcpUdpPortValue = words[1]; + WordsCount = 2; + } + break; + } + } + } + else if (protocol == ProtocolType.Icmp) + { + if (words.Count > 0) + { + switch (words[0]) + { + case "object-group": + if (words.Count > 1 && IsServiceGroup(words[1])) + { + TcpUdpPortOperator = TcpUdpPortOperatorType.ReferenceObject; + TcpUdpPortValue = words[1]; + WordsCount = 2; + } + break; + + default: + if (CiscoKnownServices.IsKnownIcmpService(words[0])) + { + TcpUdpPortOperator = TcpUdpPortOperatorType.Eq; + TcpUdpPortValue = CiscoKnownServices.ConvertIcmpServiceToType(words[0]); + WordsCount = 1; + } + break; + } + } + } + else if (protocol == ProtocolType.KnownOtherIpProtocol) + { + } + } + + private bool IsServiceGroup(string name) + { + if (_ciscoIds.ContainsKey(name) && _ciscoIds[name].Name() == "object-group") + { + var group = (Cisco_GroupObject)_ciscoIds[name]; + if (group.GroupType == Cisco_GroupObject.Group_Type.Service || group.GroupType == Cisco_GroupObject.Group_Type.Icmp) + { + return true; + } + } + + return false; + } + + private bool IsServiceObject(string name) + { + if (_ciscoIds.ContainsKey(name) && _ciscoIds[name].Name() == "object") + { + var obj = (Cisco_Object)_ciscoIds[name]; + if (obj.ObjectType == Cisco_Object.ObjectTypes.TcpService || + obj.ObjectType == Cisco_Object.ObjectTypes.UdpService || + obj.ObjectType == Cisco_Object.ObjectTypes.IcmpService) + { + return true; + } + } + + return false; + } + } + + public string ACLName { get; set; } + public bool Inactive { get; set; } + public ActionType Action { get; set; } + public ProtocolType Protocol { get; set; } + public string ProtocolReference { get; set; } + public string Remark { get; set; } + public bool IsRemark { get; set; } + public bool IsTimeRangeSpecified { get; set; } + public string TimeRangeName { get; set; } + public SourceDest Source { get; set; } + public SourceDest Destination { get; set; } + public ProtocolProperties SourceProperties { get; set; } + public ProtocolProperties DestinationProperties { get; set; } + + public override string Name() { return "access-list"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + /* + * OPTION I - REMARK format - the easiest option: + * + access-list access_list_name remark text + Example: + hostname(config)# access-list ACL_OUT remark - this is the inside admin address + * + * OPTION II - STANDARD format - used for a limited number of features, such as route maps or VPN filters. + * uses IPv4 addresses only, and defines destination addresses only. + * + access-list access_list_name standard {deny | permit} {any/any4 | host ip_address | ip_address ip_mask} + Example: + hostname(config)# access-list OSPF standard permit 192.168.1.0 255.255.255.0 + * + * OPTION III.I - EXTENDED format - for ICMP based traffic matching + * + access-list access_list_name extended {deny | permit} icmp source_address_argument dest_address_argument [icmp_argument] [time-range time_range_name] [inactive] + Example: + hostname(config)# access-list ACL_IN extended permit icmp any any echo + * + * OPTION III.II - EXTENDED format - for TCP and UDP based traffic matching, with ports + * + access-list access_list_name extended {deny | permit} {tcp | udp} source_address_argument [port_argument] dest_address_argument [port_argument] [time-range time_range_name] [inactive] + Example: + hostname(config)# access-list ACL_IN extended deny tcp any host 209.165.201.29 eq www + hostname(config)# access-list ACL_IN extended deny tcp 192.168.1.0 255.255.255.0 209.165.201.0 255.255.255.224 + * + * OPTION III.III - EXTENDED format - for general IP address and FQDN based matching + * + access-list access_list_name extended {deny | permit} protocol_argument source_address_argument dest_address_argument [time-range time_range_name] [inactive] + Example: + hostname(config)# access-list ACL_IN extended permit ip any any + * + * ********************** + * ACL COMMAND ARGUMENTS: + * + * protocol_argument specification: one of the following options: + * -------------------------------------------------------------- + * protocol_name/protocol_number + * object service_object_id --> may be also a icmp service object + * object-group service_group_id + * object-group protocol_group_id + * + * source_address_argument/dest_address_argument specification: one of the following options: + * ------------------------------------------------------------------------------------------ + * any/any4/any6 + * host ip_address + * interface interface_name + * object network_object_id + * object-group network_group_id + * ip_address ip_mask + * + * icmp_argument specification: one of the following options: + * ---------------------------------------------------------- + * icmp_type + * object-group icmp_group_id --> object-group icmp-type command + * + * port_argument specification: one of the following options: + * ---------------------------------------------------------- + * operator port --> where operator can be one of: lt, gt, eq, neq, range; port can be number or name of a TCP or UDP port + * object-group service_group_id + * + */ + + base.Parse(command, prevCommand, ciscoIds, aliases); + + ACLName = command.GetParam(1); + Inactive = false; + Action = ActionType.NA; + Protocol = ProtocolType.NA; + ProtocolReference = ""; + Remark = ""; + IsRemark = false; IsTimeRangeSpecified = false; - var prevAclCommand = prevCommand as Cisco_AccessList; - - if (command.GetParam(2) == "remark") - { - IsRemark = true; - - // Note that there may be several consecutive remark lines, so we need to aggregate to a single remark + var prevAclCommand = prevCommand as Cisco_AccessList; + + if (command.GetParam(2) == "remark") + { + IsRemark = true; + + // Note that there may be several consecutive remark lines, so we need to aggregate to a single remark string dataForNextElement = ""; - if (prevAclCommand != null && prevAclCommand.IsRemark && !string.IsNullOrEmpty(prevAclCommand.DataForNextElement)) + if (prevAclCommand != null && prevAclCommand.IsRemark && !string.IsNullOrEmpty(prevAclCommand.DataForNextElement)) { - dataForNextElement = prevAclCommand.DataForNextElement; - } - - string text = command.Text.Trim(); - int offset = text.IndexOf("remark") + 7; - - if (!string.IsNullOrEmpty(dataForNextElement)) - { - dataForNextElement += ", "; - } - - dataForNextElement += text.Substring(offset).Trim(); - DataForNextElement = dataForNextElement; - - return; - } - - if (prevAclCommand != null && ACLName.Equals(prevAclCommand.ACLName) && !string.IsNullOrEmpty(prevAclCommand.DataForNextElement)) + dataForNextElement = prevAclCommand.DataForNextElement; + } + + string text = command.Text.Trim(); + int offset = text.IndexOf("remark") + 7; + + if (!string.IsNullOrEmpty(dataForNextElement)) + { + dataForNextElement += ", "; + } + + dataForNextElement += text.Substring(offset).Trim(); + DataForNextElement = dataForNextElement; + + return; + } + + if (prevAclCommand != null && ACLName.Equals(prevAclCommand.ACLName) && !string.IsNullOrEmpty(prevAclCommand.DataForNextElement)) { Remark = prevAclCommand.DataForNextElement; if (CiscoParser.SpreadAclRemarks) { DataForNextElement = Remark; - } - } - - int denyPosition = command.GetParamPosition("deny"); - int permitPosition = command.GetParamPosition("permit"); - int protocolPosition = Math.Max(denyPosition, permitPosition) + 1; // protocol field should follow the action field (either deny or permit) - int sourcePosition = protocolPosition + 1; - - if (denyPosition > 0) - { - Action = ActionType.Deny; - } - - if (permitPosition > 0) - { - Action = ActionType.Permit; - } - - if (command.GetParam(2) == "standard") - { - Protocol = ProtocolType.Ip; - - Source = new SourceDest - { - Type = SourceDest.SourceDestType.Any - }; - - SourceProperties = new ProtocolProperties - { - Protocol = Protocol, - TcpUdpPortOperator = TcpUdpPortOperatorType.All - }; - - Destination = new SourceDest(command.GetParams(4)); - - DestinationProperties = new ProtocolProperties - { - Protocol = Protocol, - TcpUdpPortOperator = TcpUdpPortOperatorType.All - }; - - return; - } - - if (command.GetParamPosition("time-range") > 0) - { - IsTimeRangeSpecified = true; - int indexTimeRange = command.GetParamPosition("time-range"); - TimeRangeName = command.GetParam(indexTimeRange + 1); - } - - if (command.GetParamPosition("inactive") > 0) - { - Inactive = true; - } - - string strProtocol = command.GetParam(protocolPosition); - switch (strProtocol) - { - case "ip": - Protocol = ProtocolType.Ip; - break; - - case "icmp": - case "icmp6": - Protocol = ProtocolType.Icmp; - break; - - case "udp": - Protocol = ProtocolType.Udp; - break; - - case "tcp": - Protocol = ProtocolType.Tcp; - break; - - case "object-group": - case "object": - Protocol = ProtocolType.ReferenceObject; - ProtocolReference = command.GetParam(protocolPosition + 1); - sourcePosition++; - break; - - default: - string serviceName; - if (CiscoKnownServices.IsKnownService(strProtocol)) - { - Protocol = ProtocolType.KnownOtherIpProtocol; - } - else if (CiscoKnownServices.IsKnownServiceNumber(strProtocol, out serviceName)) // protocol number is used!!! - { - Protocol = ProtocolType.KnownOtherIpProtocol; - strProtocol = serviceName; - } - else - { - ProtocolReference = strProtocol; - ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - ConversionIncidentMessage = "Unrecognized service protocol (" + strProtocol + ")"; - Console.WriteLine(ConversionIncidentMessage); - } - break; - } - - Source = new SourceDest(command.GetParams(sourcePosition)); - SourceProperties = new ProtocolProperties(Protocol, command.GetParams(sourcePosition + Source.WordsCount), ciscoIds, ServiceDirection.Source); - Destination = new SourceDest(command.GetParams(sourcePosition + Source.WordsCount + SourceProperties.WordsCount)); - DestinationProperties = new ProtocolProperties(Protocol, command.GetParams(sourcePosition + Source.WordsCount + SourceProperties.WordsCount + Destination.WordsCount), ciscoIds, ServiceDirection.Destination); - - if (Protocol == ProtocolType.KnownOtherIpProtocol) - { - // This information is needed in order to create/query appropriate service objects - DestinationProperties.TcpUdpPortValue = strProtocol; - DestinationProperties.WordsCount = 1; - } - } - } - - public class Cisco_ClassMap : CiscoCommand - { - public string ClassMapName; - public List MatchedAclNames = new List(); - - public override string Name() { return "class-map"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - base.Parse(command, prevCommand, ciscoIds, aliases); - - ClassMapName = command.GetParam(1); - - if (command.Children == null) - { - return; - } - - foreach (CiscoCommand child in command.Children) - { - if (child.Name() == "match" && !string.IsNullOrEmpty(((Cisco_Match_AccessList)child).AccessListName)) - { - MatchedAclNames.Add(((Cisco_Match_AccessList)child).AccessListName); - } - } - } - } - - public class Cisco_Match_AccessList : CiscoCommand - { - public string AccessListName { get; set; } - - public override string Name() { return "match"; } - - public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) - { - // Parsing Options: - //----------------- - // match access-list access_list_name - //----------------- - - base.Parse(command, prevCommand, ciscoIds, aliases); - - AccessListName = (command.GetParam(1) == "access-list") ? command.GetParam(2) : ""; - } - } -} + } + } + + int denyPosition = command.GetParamPosition("deny"); + int permitPosition = command.GetParamPosition("permit"); + int protocolPosition = Math.Max(denyPosition, permitPosition) + 1; // protocol field should follow the action field (either deny or permit) + int sourcePosition = protocolPosition + 1; + + if (denyPosition > 0) + { + Action = ActionType.Deny; + } + + if (permitPosition > 0) + { + Action = ActionType.Permit; + } + + if (command.GetParam(2) == "standard") + { + Protocol = ProtocolType.Ip; + + Source = new SourceDest + { + Type = SourceDest.SourceDestType.Any + }; + + SourceProperties = new ProtocolProperties + { + Protocol = Protocol, + TcpUdpPortOperator = TcpUdpPortOperatorType.All + }; + + Destination = new SourceDest(command.GetParams(4)); + + DestinationProperties = new ProtocolProperties + { + Protocol = Protocol, + TcpUdpPortOperator = TcpUdpPortOperatorType.All + }; + + return; + } + + if (command.GetParamPosition("time-range") > 0) + { + IsTimeRangeSpecified = true; + int indexTimeRange = command.GetParamPosition("time-range"); + TimeRangeName = command.GetParam(indexTimeRange + 1); + } + + if (command.GetParamPosition("inactive") > 0) + { + Inactive = true; + } + + string strProtocol = command.GetParam(protocolPosition); + switch (strProtocol) + { + case "ip": + Protocol = ProtocolType.Ip; + break; + + case "icmp": + case "icmp6": + Protocol = ProtocolType.Icmp; + break; + + case "udp": + Protocol = ProtocolType.Udp; + break; + + case "tcp": + Protocol = ProtocolType.Tcp; + break; + + case "object-group": + case "object": + Protocol = ProtocolType.ReferenceObject; + ProtocolReference = command.GetParam(protocolPosition + 1); + sourcePosition++; + break; + + default: + string serviceName; + if (CiscoKnownServices.IsKnownService(strProtocol)) + { + Protocol = ProtocolType.KnownOtherIpProtocol; + } + else if (CiscoKnownServices.IsKnownServiceNumber(strProtocol, out serviceName)) // protocol number is used!!! + { + Protocol = ProtocolType.KnownOtherIpProtocol; + strProtocol = serviceName; + } + else + { + ProtocolReference = strProtocol; + ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + ConversionIncidentMessage = "Unrecognized service protocol (" + strProtocol + ")"; + Console.WriteLine(ConversionIncidentMessage); + } + break; + } + + Source = new SourceDest(command.GetParams(sourcePosition)); + SourceProperties = new ProtocolProperties(Protocol, command.GetParams(sourcePosition + Source.WordsCount), ciscoIds, ServiceDirection.Source); + Destination = new SourceDest(command.GetParams(sourcePosition + Source.WordsCount + SourceProperties.WordsCount)); + DestinationProperties = new ProtocolProperties(Protocol, command.GetParams(sourcePosition + Source.WordsCount + SourceProperties.WordsCount + Destination.WordsCount), ciscoIds, ServiceDirection.Destination); + + if (Protocol == ProtocolType.KnownOtherIpProtocol) + { + // This information is needed in order to create/query appropriate service objects + DestinationProperties.TcpUdpPortValue = strProtocol; + DestinationProperties.WordsCount = 1; + } + } + } + + public class Cisco_ClassMap : CiscoCommand + { + public string ClassMapName; + public List MatchedAclNames = new List(); + + public override string Name() { return "class-map"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + base.Parse(command, prevCommand, ciscoIds, aliases); + + ClassMapName = command.GetParam(1); + + if (command.Children == null) + { + return; + } + + foreach (CiscoCommand child in command.Children) + { + if (child.Name() == "match" && !string.IsNullOrEmpty(((Cisco_Match_AccessList)child).AccessListName)) + { + MatchedAclNames.Add(((Cisco_Match_AccessList)child).AccessListName); + } + } + } + } + + public class Cisco_Match_AccessList : CiscoCommand + { + public string AccessListName { get; set; } + + public override string Name() { return "match"; } + + public override void Parse(CiscoCommand command, CiscoCommand prevCommand, Dictionary ciscoIds, Dictionary aliases) + { + // Parsing Options: + //----------------- + // match access-list access_list_name + //----------------- + + base.Parse(command, prevCommand, ciscoIds, aliases); + + AccessListName = (command.GetParam(1) == "access-list") ? command.GetParam(2) : ""; + } + } +} diff --git a/CiscoMigration/CiscoConverter.cs b/CiscoMigration/CiscoConverter.cs index 17749789..f7cb4deb 100644 --- a/CiscoMigration/CiscoConverter.cs +++ b/CiscoMigration/CiscoConverter.cs @@ -35,18 +35,18 @@ namespace CiscoMigration /// public class CiscoConverter : VendorConverter { - #region Helper Classes - - private class DuplicateNameInfo - { - public int DuplicatesCount { get; set; } - public bool IsCPPredefinedName { get; private set; } - - public DuplicateNameInfo(bool isCPPredefinedName) - { - DuplicatesCount = 0; - IsCPPredefinedName = isCPPredefinedName; - } + #region Helper Classes + + private class DuplicateNameInfo + { + public int DuplicatesCount { get; set; } + public bool IsCPPredefinedName { get; private set; } + + public DuplicateNameInfo(bool isCPPredefinedName) + { + DuplicatesCount = 0; + IsCPPredefinedName = isCPPredefinedName; + } } private class CiscoNetwork @@ -510,8 +510,8 @@ private static void GetServicePortRanges(string servicePort, out int from, out i private Cisco_Hostname _ciscoHostnameCommand; private List _ciscoGlobalAclCommands = new List(); - private List _cpPreorderedNatRules = new List(); - + private List _cpPreorderedNatRules = new List(); + private Dictionary _duplicateNamesLookup = new Dictionary(StringComparer.InvariantCultureIgnoreCase); private List _ciscoServiceInvalidNames = new List(); private List _ciscoFqdnInvalidNames = new List(); @@ -521,7 +521,7 @@ private static void GetServicePortRanges(string servicePort, out int from, out i private bool _isIntraInterfaceTrafficAllowed = false; private Dictionary> _ciscoTimeNamesToCpTimeNamesDict = new Dictionary>(); - + private enum CheckPointDummyObjectType { Host, NetworkGroup, ServiceGroup, OtherService, TimeGroup }; private IEnumerable CiscoAllCommands @@ -571,7 +571,7 @@ private IEnumerable CiscoInterfaceCommands return _ciscoInterfaceCommands ?? (_ciscoInterfaceCommands = _ciscoParser.Filter("interface")); } } - + private IEnumerable CisciTimeRangeCommands { get @@ -579,7 +579,7 @@ private IEnumerable CisciTimeRangeCommands return _ciscoTimeRangeCommands ?? (_ciscoTimeRangeCommands = _ciscoParser.Filter("time-range")); } } - + private IEnumerable CiscoClassMapCommands { get @@ -620,20 +620,20 @@ private Cisco_Hostname CiscoHostnameCommand #endregion - #region Private Methods - - protected override bool AddCheckPointObject(CheckPointObject cpObject) - { - if (base.AddCheckPointObject(cpObject)) - { - string vendor = Vendor.CiscoASA.ToString(); - if (!cpObject.Tags.Contains(vendor)) - { - cpObject.Tags.Add(vendor); - } - } - - return false; + #region Private Methods + + protected override bool AddCheckPointObject(CheckPointObject cpObject) + { + if (base.AddCheckPointObject(cpObject)) + { + string vendor = Vendor.CiscoASA.ToString(); + if (!cpObject.Tags.Contains(vendor)) + { + cpObject.Tags.Add(vendor); + } + } + + return false; } private void ApplyConversionIncidentOnCheckPointObject(CheckPointObject cpObject, CiscoCommand ciscoCommand) @@ -1682,7 +1682,7 @@ private void Add_ServicesAndServiceGroups() } } } - + private void Add_TimeRanges() { IEnumerable caTimesList = CisciTimeRangeCommands; @@ -1735,7 +1735,7 @@ private void Add_TimeRanges() } string periodic = null; - if(caTime.PeriodicsList.Count == 1) + if (caTime.PeriodicsList.Count == 1) { periodic = caTime.PeriodicsList[0]; } @@ -1745,15 +1745,15 @@ private void Add_TimeRanges() } } } - + private void Add_TimeRange(int caTimeId, string caTimeRangeName, string cpTimeRangeName, string cpStartDateTime, string cpEndDateTime, string period = null) { - if(!caTimeRangeName.Equals(cpTimeRangeName)) + if (!caTimeRangeName.Equals(cpTimeRangeName)) { _conversionIncidents.Add( new ConversionIncident( - caTimeId, - "TITLE: object is renamed", + caTimeId, + "TITLE: object is renamed", "DESCRIPTION: object renamed from " + caTimeRangeName + " to " + cpTimeRangeName, ConversionIncidentType.Informative)); } @@ -1903,7 +1903,7 @@ private void Add_TimeRange(int caTimeId, string caTimeRangeName, string cpTimeRa private CheckPoint_Time.Weekdays WeekDayFromCiscoToCP(string weekDayCisco) { CheckPoint_Time.Weekdays weekDayCP; - switch(weekDayCisco) + switch (weekDayCisco) { case "Monday": weekDayCP = CheckPoint_Time.Weekdays.Mon; break; case "Tuesday": weekDayCP = CheckPoint_Time.Weekdays.Tue; break; @@ -1916,7 +1916,7 @@ private CheckPoint_Time.Weekdays WeekDayFromCiscoToCP(string weekDayCisco) return weekDayCP; } - + private void Add_Package() { var cpPackage = new CheckPoint_Package(); @@ -2234,7 +2234,7 @@ private void Add_Layers_And_Rules(CheckPoint_Package package) var ciscoAcl = (Cisco_AccessList)aclCommand; if (!ciscoAcl.IsRemark && ciscoAcl.ACLName == ciscoAccessGroup.AccessListName) { - var cpRule = Acl_To_CPRule(ciscoAcl); + var cpRule = Acl_To_CPRule(ciscoAcl, null); if (ciscoInterface.Shutdown) { @@ -2274,58 +2274,154 @@ private void Add_Layers_And_Rules(CheckPoint_Package package) } private void Add_Global_Rules(CheckPoint_Package package) - { - foreach (Cisco_AccessList ciscoAcl in _ciscoGlobalAclCommands) + { + if (_ciscoGlobalAclCommands.Count > 0) + { + // remove clenup rule of each sublayer if global rules exist because cleanup rule should be added after global-rules + foreach (var subpolicy in package.SubPolicies) + { + if (subpolicy.Rules.Count > 0) + { + var lastRule = subpolicy.Rules[subpolicy.Rules.Count - 1]; + if (lastRule.IsCleanupRule()) + subpolicy.Rules.Remove(lastRule); + } + } + + //remove cleanup rule of parent layer because it will be added after global rules + if (package.ParentLayer.Rules.Count > 0) + { + var lastRule = package.ParentLayer.Rules[package.ParentLayer.Rules.Count - 1]; + if (lastRule.IsCleanupRule()) + package.ParentLayer.Rules.Remove(lastRule); + } + + CheckPoint_Rule cpRule4GlobalLayer = new CheckPoint_Rule(); + cpRule4GlobalLayer.Name = ""; + cpRule4GlobalLayer.Layer = package.NameOfAccessLayer; + cpRule4GlobalLayer.Source.Add(_cpObjects.GetObject(CheckPointObject.Any)); + cpRule4GlobalLayer.Destination.Add(_cpObjects.GetObject(CheckPointObject.Any)); + cpRule4GlobalLayer.Action = CheckPoint_Rule.ActionType.SubPolicy; + cpRule4GlobalLayer.Track = CheckPoint_Rule.TrackTypes.None; + cpRule4GlobalLayer.Time.Add(_cpObjects.GetObject(CheckPointObject.Any)); + cpRule4GlobalLayer.Service.Add(_cpObjects.GetObject(CheckPointObject.Any)); + cpRule4GlobalLayer.SubPolicyName = GlobalRulesSubpolicyName; + + package.ParentLayer.Rules.Add(cpRule4GlobalLayer); + + CheckPoint_Layer cpSubLayer4GlobalRules = new CheckPoint_Layer(); + cpSubLayer4GlobalRules.ApplicationsAndUrlFiltering = true; + cpSubLayer4GlobalRules.Shared = true; + cpSubLayer4GlobalRules.Name = cpRule4GlobalLayer.SubPolicyName; + + package.SubPolicies.Insert(0, cpSubLayer4GlobalRules); // insert at the begging becuase Global Rules should be created before all policy + + foreach (var globalPolicyRule in _ciscoGlobalAclCommands) + { + // Append the global policy rules BELOW the existing sub-policies. + CheckPoint_Rule cpRule = Acl_To_CPRule(globalPolicyRule, cpSubLayer4GlobalRules.Name); + cpSubLayer4GlobalRules.Rules.Add(cpRule); + } + + //add cleanup rule after all global rules + + // Do NOT create a cleanup rule if it already exists + bool createCleanupRule = true; + if (cpSubLayer4GlobalRules.Rules.Count > 0) + { + var lastRule = cpSubLayer4GlobalRules.Rules[cpSubLayer4GlobalRules.Rules.Count - 1]; + createCleanupRule = !lastRule.IsCleanupRule(); + } + + if (createCleanupRule) + { + var cpCleanupRule = new CheckPoint_Rule(); + cpCleanupRule.Name = CheckPoint_Rule.SubPolicyCleanupRuleName; + cpCleanupRule.Action = CheckPoint_Rule.ActionType.Drop; + cpCleanupRule.Layer = cpSubLayer4GlobalRules.Name; + cpSubLayer4GlobalRules.Rules.Add(cpCleanupRule); + } + + // Fill in the shared layer with global policy rules INSIDE the existing sub-policies. + foreach (CheckPoint_Layer subPolicy in package.SubPolicies) + { + if (subPolicy.Name.Equals(cpSubLayer4GlobalRules.Name)) + { + continue; + } + + CheckPoint_Rule cpSubRule4GlobalLayer = cpRule4GlobalLayer.Clone(); + cpSubRule4GlobalLayer.Name = "Global Layer"; + cpSubRule4GlobalLayer.Layer = subPolicy.Name; + subPolicy.Rules.Add(cpSubRule4GlobalLayer); + } + + + //the last rule which is created by default by CheckPoint script importer. It is for report only. + var cpRuleCleanUp = new CheckPoint_Rule(); + cpRuleCleanUp.Name = "Cleanup rule"; + package.ParentLayer.Rules.Add(cpRuleCleanUp); + } + else { - foreach (CheckPoint_Rule cpParentRule in package.ParentLayer.Rules) + foreach (Cisco_AccessList ciscoAcl in _ciscoGlobalAclCommands) { - if (cpParentRule.Action == CheckPoint_Rule.ActionType.SubPolicy) + // Fill in the global policy rules INSIDE the existing sub-policies. + foreach (CheckPoint_Rule cpParentRule in package.ParentLayer.Rules) { - // Get into the relevant sub-policy - foreach (CheckPoint_Layer subPolicy in package.SubPolicies) + if (cpParentRule.Action == CheckPoint_Rule.ActionType.SubPolicy) { - if (subPolicy.Name == cpParentRule.SubPolicyName) + // Get into the relevant sub-policy + foreach (CheckPoint_Layer subPolicy in package.SubPolicies) { - // This is done to avoid duplication of incident reporting over all matched sub-policy rules. - ConversionIncidentType aclConversionIncident = ciscoAcl.ConversionIncidentType; - ciscoAcl.ConversionIncidentType = ConversionIncidentType.None; + if (subPolicy.Name == cpParentRule.SubPolicyName) + { + // This is done to avoid duplication of incident reporting over all matched sub-policy rules. + ConversionIncidentType aclConversionIncident = ciscoAcl.ConversionIncidentType; + ciscoAcl.ConversionIncidentType = ConversionIncidentType.None; - var cpRule = Acl_To_CPRule(ciscoAcl); - cpRule.Layer = subPolicy.Name; + var cpRule = Acl_To_CPRule(ciscoAcl, subPolicy.Name); + + cpRule.Layer = subPolicy.Name; - if (!string.IsNullOrEmpty(subPolicy.Tag) && subPolicy.Tag == "InterfaceDisabled") - { - cpRule.Enabled = false; - } + if (!string.IsNullOrEmpty(subPolicy.Tag) && subPolicy.Tag == "InterfaceDisabled") + { + cpRule.Enabled = false; + } - // If the global ACL didn't have an incident previously, - // and the incident was just encountered during this convertion, retain the incident!!! - if (ciscoAcl.ConversionIncidentType == ConversionIncidentType.None) - { - ciscoAcl.ConversionIncidentType = aclConversionIncident; - } + // If the global ACL didn't have an incident previously, + // and the incident was just encountered during this convertion, retain the incident!!! + if (ciscoAcl.ConversionIncidentType == ConversionIncidentType.None) + { + ciscoAcl.ConversionIncidentType = aclConversionIncident; + } - // Insert the global rules at the end of each sub-policy, BEFORE the cleanup rule. - int rulesCount = subPolicy.Rules.Count; - subPolicy.Rules.Insert(rulesCount - 1, cpRule); + // Insert the global rules at the end of each sub-policy, BEFORE the cleanup rule. + int rulesCount = subPolicy.Rules.Count; + subPolicy.Rules.Insert(rulesCount - 1, cpRule); - if (cpRule.ConversionIncidentType != ConversionIncidentType.None || ciscoAcl.ConversionIncidentType != ConversionIncidentType.None) - { - package.ConversionIncidentType = ConversionIncidentType.Informative; + if (cpRule.ConversionIncidentType != ConversionIncidentType.None || ciscoAcl.ConversionIncidentType != ConversionIncidentType.None) + { + package.ConversionIncidentType = ConversionIncidentType.Informative; + } } } } - } - } - } + } + } + } } - private CheckPoint_Rule Acl_To_CPRule(Cisco_AccessList ciscoAcl) + private CheckPoint_Rule Acl_To_CPRule(Cisco_AccessList ciscoAcl, string layerName) { - var cpRule = new CheckPoint_Rule(); - cpRule.Name = ciscoAcl.Description; - cpRule.Enabled = !ciscoAcl.Inactive; - cpRule.Layer = ciscoAcl.ACLName; + var cpRule = new CheckPoint_Rule(); + cpRule.Name = ciscoAcl.Description; + cpRule.Enabled = !ciscoAcl.Inactive; + if (layerName != null) + cpRule.Layer = layerName; + else + cpRule.Layer = ciscoAcl.ACLName; + cpRule.Comments = ciscoAcl.Remark; cpRule.ConversionComments = ciscoAcl.Id + ") " + ciscoAcl.Text; @@ -2341,7 +2437,7 @@ private CheckPoint_Rule Acl_To_CPRule(Cisco_AccessList ciscoAcl) _ciscoTimeNamesToCpTimeNamesDict.TryGetValue(ciscoAcl.TimeRangeName, out cpTimeNamesList); if (cpTimeNamesList != null) { - foreach(string cpTimeName in cpTimeNamesList) + foreach (string cpTimeName in cpTimeNamesList) { cpObject = GetCheckPointObjectOrCreateDummy(cpTimeName, CheckPointDummyObjectType.TimeGroup, @@ -2576,7 +2672,7 @@ private CheckPoint_Rule Acl_To_CPRule(Cisco_AccessList ciscoAcl) { Add_AclProtocols_To_CPRule(ciscoAcl, ciscoGroupReferenceObject, cpRule); } - } + } else if (ciscoProtocolReferenceCommand != null && ciscoProtocolReferenceCommand.Name() == "object") // service object { var ciscoReferenceObject = (Cisco_Object)ciscoProtocolReferenceCommand; @@ -2640,7 +2736,7 @@ private CheckPoint_Rule Acl_To_CPRule(Cisco_AccessList ciscoAcl) ciscoAcl.ConversionIncidentType = ConversionIncidentType.ManualActionRequired; _conversionIncidents.Add(new ConversionIncident(ciscoAcl.Id, - "Error creating a rule, missing information for Cisco ACL protocol", + "Error creating a rule, missing information for Cisco ACL protocol", "ACL Protocol details: " + ciscoAcl.ProtocolReference + ".", ciscoAcl.ConversionIncidentType)); } @@ -2778,7 +2874,7 @@ private void Add_AclServices_To_CPRule(Cisco_AccessList ciscoAcl, Cisco_GroupObj hasGeneralIcmpServiceMember = true; } - var dummyObjectType = (ciscoAcl.DestinationProperties.Protocol == ProtocolType.KnownOtherIpProtocol) + var dummyObjectType = (ciscoAcl.DestinationProperties.Protocol == ProtocolType.KnownOtherIpProtocol) ? CheckPointDummyObjectType.OtherService : CheckPointDummyObjectType.ServiceGroup; @@ -3034,9 +3130,9 @@ private void Add_Layers_And_Rules_For_Other_Zones(CheckPoint_Package package) { var otherCiscoInterface = (Cisco_Interface)command; - if (string.IsNullOrEmpty(otherCiscoInterface.CiscoId) || - otherCiscoInterface.CiscoId == ciscoInterface.CiscoId || - !otherCiscoInterface.HasValidIpAddress() || + if (string.IsNullOrEmpty(otherCiscoInterface.CiscoId) || + otherCiscoInterface.CiscoId == ciscoInterface.CiscoId || + !otherCiscoInterface.HasValidIpAddress() || otherCiscoInterface.ManagementOnly) { continue; @@ -3103,7 +3199,7 @@ private void DetectCheckPointFirewallRulesAffectedByInspectPolicy(CheckPoint_Pac // Go over the affected ACLs and match the fw rules by: source, destination and service fields foreach (var ciscoInspectedAcl in ciscoInspectedAclCommands) { - var inspectedRule = Acl_To_CPRule(ciscoInspectedAcl); + var inspectedRule = Acl_To_CPRule(ciscoInspectedAcl, null); if ((inspectedRule.Source.Count == 1 && inspectedRule.Source[0].Name == CheckPointObject.Any) && (inspectedRule.Destination.Count == 1 && inspectedRule.Destination[0].Name == CheckPointObject.Any) && @@ -3427,8 +3523,8 @@ private void Add_object_NAT() (cpNatRule.Service != null && cpNatRule.Service.ConversionIncidentType != ConversionIncidentType.None) || (cpNatRule.TranslatedService != null && cpNatRule.TranslatedService.ConversionIncidentType != ConversionIncidentType.None); - if (cpNatRule.ConversionIncidentType != ConversionIncidentType.None || - ciscoNat.ConversionIncidentType != ConversionIncidentType.None || + if (cpNatRule.ConversionIncidentType != ConversionIncidentType.None || + ciscoNat.ConversionIncidentType != ConversionIncidentType.None || natRuleObjectHasConversionIncident) { _hasNATConversionIncident = true; @@ -3703,7 +3799,7 @@ private void Add_NAT_Rules() // we should convert to dynamic NAT rule!!! if (cpNatRule.Method == CheckPoint_NAT_Rule.NatMethod.Static) { - if ((cpNatRule.Source.GetType() == typeof(CheckPoint_Network) || cpNatRule.Source.GetType() == typeof(CheckPoint_NetworkGroup)) && + if ((cpNatRule.Source.GetType() == typeof(CheckPoint_Network) || cpNatRule.Source.GetType() == typeof(CheckPoint_NetworkGroup)) && cpNatRule.TranslatedSource != null && cpNatRule.TranslatedSource.GetType() == typeof(CheckPoint_Host)) { cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; @@ -3720,8 +3816,8 @@ private void Add_NAT_Rules() (cpNatRule.Service != null && cpNatRule.Service.ConversionIncidentType != ConversionIncidentType.None) || (cpNatRule.TranslatedService != null && cpNatRule.TranslatedService.ConversionIncidentType != ConversionIncidentType.None); - if (cpNatRule.ConversionIncidentType != ConversionIncidentType.None || - ciscoNat.ConversionIncidentType != ConversionIncidentType.None || + if (cpNatRule.ConversionIncidentType != ConversionIncidentType.None || + ciscoNat.ConversionIncidentType != ConversionIncidentType.None || natRuleObjectHasConversionIncident) { _hasNATConversionIncident = true; @@ -3781,7 +3877,7 @@ private void Add_NAT_Rules() _cpPreorderedNatRules.Add(cpNatMirrorRule); - if (cpNatMirrorRule.ConversionIncidentType != ConversionIncidentType.None || + if (cpNatMirrorRule.ConversionIncidentType != ConversionIncidentType.None || ciscoNat.ConversionIncidentType != ConversionIncidentType.None) { _hasNATConversionIncident = true; @@ -3957,12 +4053,23 @@ private void MatchNATRulesIntoFirewallPolicy() { continue; } + + if (cpParentRule.Source[0] is CheckPoint_PredifinedObject && cpParentRule.Source[0].Name.Equals(CheckPointObject.Any)) + { + if (cpParentRule.SubPolicyName != GlobalRulesSubpolicyName) + { + continue; + } + } - var parentLayerRuleZone = (CheckPoint_Zone)cpParentRule.Source[0]; - if (parentLayerRuleZone == null) + CheckPoint_Zone parentLayerRuleZone = new CheckPoint_Zone(); + if (cpParentRule.SubPolicyName == GlobalRulesSubpolicyName) { - Console.WriteLine("Ooopppsssss..............."); // shouldn't happen... - continue; + parentLayerRuleZone.Name = "any"; + } + else + { + parentLayerRuleZone = (CheckPoint_Zone)cpParentRule.Source[0]; } // NAT rule interfaces should match on firewall rule interfaces (zones) @@ -3983,7 +4090,7 @@ private void MatchNATRulesIntoFirewallPolicy() for (int ruleNumber = 0; ruleNumber < subPolicy.Rules.Count; ruleNumber++) { var cpRule = subPolicy.Rules[ruleNumber]; - + // Do not match on cleanup rule if (cpRule.IsCleanupRule()) { @@ -4013,7 +4120,8 @@ private void MatchNATRulesIntoFirewallPolicy() CheckPointObject newRuleDest = null; bool serviceMatchedToo = false; - if (IsFirewallRuleMatchedByNATRule(parentLayerRuleZone, cpNatRule, cpRule, out newRuleDest, out serviceMatchedToo)) + //dont't check added matched NAT rules + if (!cpRule.ConversionComments.StartsWith("Matched NAT rule") && IsFirewallRuleMatchedByNATRule(parentLayerRuleZone, cpNatRule, cpRule, out newRuleDest, out serviceMatchedToo)) { string translatedSourceName = (cpNatRule.TranslatedSource != null) ? cpNatRule.TranslatedSource.Name : "original"; string translatedDestName = (cpNatRule.TranslatedDestination != null) ? cpNatRule.TranslatedDestination.Name : "original"; @@ -4048,8 +4156,21 @@ private void MatchNATRulesIntoFirewallPolicy() newRule.ConversionComments = "Matched NAT rule ((" + cpNatRule.ConvertedCommandId + ") translated source: " + translatedSourceName + ", translated dest: " + translatedDestName + ")"; } + //don't add duplicated rules + bool ruleIsAlreadyAdded = false; + foreach (var rule in subPolicy.Rules) + { + if (newRule.CompareTo(rule)) + { + ruleIsAlreadyAdded = true; + } + } + // Add a new rule ABOVE the matched rule. - subPolicy.Rules.Insert(ruleNumber, newRule); + if (!ruleIsAlreadyAdded) + { + subPolicy.Rules.Insert(ruleNumber, newRule); + } if (newRule.ConversionIncidentType != ConversionIncidentType.None) { @@ -4292,8 +4413,16 @@ private void Add_Optimized_Package() foreach (CheckPoint_Layer layer in regularPackage.SubPolicies) { string optimizedSubPolicyName = layer.Name + "_opt"; + CheckPoint_Layer optimizedLayer = RuleBaseOptimizer.Optimize(layer, optimizedSubPolicyName); - + foreach (CheckPoint_Rule subSubRule in optimizedLayer.Rules) + { + if (subSubRule.SubPolicyName.Equals(GlobalRulesSubpolicyName)) + { + //The Global sub-sub rule subpolicy name should also be renamed for consistency + subSubRule.SubPolicyName += "_opt"; + } + } if (!regular2OptimizedLayers.ContainsKey(layer.Name)) { regular2OptimizedLayers.Add(layer.Name, optimizedSubPolicyName); @@ -4405,170 +4534,7 @@ public override void Convert(bool convertNat) ConversionIncidentCategoriesCount = _conversionIncidents.GroupBy(error => error.Title).Count(); ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); - #region Processing SmartConnector - - string[] pySmartConnectorFNs = new string[] { - "lib" + Path.DirectorySeparatorChar + "__init__.py", - "lib" + Path.DirectorySeparatorChar + "api_exceptions.py", - "lib" + Path.DirectorySeparatorChar + "api_response.py", - "lib" + Path.DirectorySeparatorChar + "mgmt_api.py", - "smartconnector.py" - }; - bool isGeneratingSC = true; - foreach (var pySmartConnectorFN in pySmartConnectorFNs) - { - if(!File.Exists(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "SmartConnector" + Path.DirectorySeparatorChar + pySmartConnectorFN)) - { - isGeneratingSC = false; - break; - } - } - - if (isGeneratingSC) - { - RaiseConversionProgress(90, "Generating Smart Connector ..."); - string cpObjectsJsonFN = "cp_objects.json"; - string cpObjectsJsonFP = _targetFolder + Path.DirectorySeparatorChar + cpObjectsJsonFN; - - #region adding objects and rules to list for generating JSON - - List cpJsonObjects = new List(); - cpJsonObjects.AddRange(_cpDomains); - cpJsonObjects.AddRange(_cpHosts); - cpJsonObjects.AddRange(_cpNetworks); - cpJsonObjects.AddRange(_cpRanges); - // adding NetworkGroups and NetworkGroups with Exclusions - CheckPoint_NetworkGroup allInternal = null; - bool splitNetworkGroupsCreation = (_cpNetworkGroups.Count > 0 && _cpGroupsWithExclusion.Count > 0); - if (_cpNetworkGroups.Count > 0) - { - foreach (CheckPoint_NetworkGroup obj in _cpNetworkGroups) - { - if (obj.Name == AllInternalNetwotkGroupName) - { - allInternal = obj; - continue; - } - if (splitNetworkGroupsCreation && obj.CreateAfterGroupsWithExclusion) - { - continue; - } - - cpJsonObjects.Add(obj); - } - } - if (_cpGroupsWithExclusion.Count > 0) - { - foreach (CheckPoint_GroupWithExclusion obj in _cpGroupsWithExclusion) - { - cpJsonObjects.Add(obj); - } - } - if (splitNetworkGroupsCreation) - { - foreach (CheckPoint_NetworkGroup obj in _cpNetworkGroups) - { - if (!obj.CreateAfterGroupsWithExclusion) - { - continue; - } - cpJsonObjects.Add(obj); - } - } - if (allInternal != null) - { - cpJsonObjects.Add(allInternal); - } - // NetworkGroups and NetworkGroups with Exclusion are added - cpJsonObjects.Add(_cpSimpleGateway); - cpJsonObjects.AddRange(_cpZones); - cpJsonObjects.AddRange(_cpTcpServices); - cpJsonObjects.AddRange(_cpUdpServices); - cpJsonObjects.AddRange(_cpOtherServices); - cpJsonObjects.AddRange(_cpServiceGroups); - cpJsonObjects.AddRange(_cpTimeGroups); - // objects are added - // adding Security rules - cpJsonObjects.Add(_cpPackages[0]); - // adding NAT rules - _cpNatRules.ForEach(x => x.Package = _cpPackages[0].Name); - cpJsonObjects.AddRange(_cpNatRules); - - //remove all NULL elements - cpJsonObjects.RemoveAll(x => x == null); - #endregion - - File.WriteAllText(cpObjectsJsonFP, JsonConvert.SerializeObject(cpJsonObjects, Formatting.Indented)); - - string smartConnectorArchiveName = "smartconnector_" + _vendorFileName; - string smartConnectorArchivePath = _targetFolder + Path.DirectorySeparatorChar + smartConnectorArchiveName; - - #region preparing smarctconnector to archiving - if (Directory.Exists(smartConnectorArchivePath)) - Directory.Delete(smartConnectorArchivePath, true); - - Directory.CreateDirectory(smartConnectorArchivePath); - foreach (var pySmartConnectorFN in pySmartConnectorFNs) - { - Directory.CreateDirectory(Directory.GetParent(smartConnectorArchivePath + Path.DirectorySeparatorChar + pySmartConnectorFN).FullName); - File.Copy(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "SmartConnector" + Path.DirectorySeparatorChar + pySmartConnectorFN, - smartConnectorArchivePath + Path.DirectorySeparatorChar + pySmartConnectorFN); - } - if (!string.IsNullOrWhiteSpace(this._domainName)) // update by Domain - { - Encoding utf8Enc = new UTF8Encoding(false); - string smartConnectorSFP = smartConnectorArchivePath + Path.DirectorySeparatorChar + "smartconnector.py"; - string smartConnectorFC = File.ReadAllText(smartConnectorSFP, utf8Enc); - smartConnectorFC = smartConnectorFC.Replace( - "parser.add_argument('-d', '--domain', default=None,", - "parser.add_argument('-d', '--domain', default='" + this._domainName + "',"); - File.WriteAllText(smartConnectorSFP, smartConnectorFC, utf8Enc); - } - File.Copy(cpObjectsJsonFP, smartConnectorArchivePath + Path.DirectorySeparatorChar + cpObjectsJsonFN); - #endregion - - string compressorsDirPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "compressors"; - - ProcessStartInfo startInfo = new ProcessStartInfo(); - startInfo.UseShellExecute = false; - startInfo.CreateNoWindow = true; - Process compressProc = null; - - #region createing ZIP archive - if (File.Exists(smartConnectorArchivePath + ".zip")) - File.Delete(smartConnectorArchivePath + ".zip"); - - startInfo.FileName = Path.Combine(compressorsDirPath, "zip.exe"); - startInfo.WorkingDirectory = _targetFolder + Path.DirectorySeparatorChar + smartConnectorArchiveName; - startInfo.Arguments = "-r" + " ..\\" + smartConnectorArchiveName + ".zip" + " *"; - compressProc = Process.Start(startInfo); - compressProc.WaitForExit(); - #endregion - - #region createing TAR.GZ archive - if (File.Exists(smartConnectorArchivePath + ".tar.gz")) - File.Delete(smartConnectorArchivePath + ".tar.gz"); - - startInfo.FileName = Path.Combine(compressorsDirPath, "gtar.exe"); - startInfo.WorkingDirectory = _targetFolder + Path.DirectorySeparatorChar + smartConnectorArchiveName; - startInfo.Arguments = "cf" + " ..\\" + smartConnectorArchiveName + ".tar" + " *"; - compressProc = Process.Start(startInfo); - compressProc.WaitForExit(); - - startInfo.FileName = Path.Combine(compressorsDirPath, "gzip.exe"); - startInfo.WorkingDirectory = _targetFolder; - startInfo.Arguments = smartConnectorArchiveName + ".tar"; - compressProc = Process.Start(startInfo); - compressProc.WaitForExit(); - #endregion - - if (File.Exists(cpObjectsJsonFP)) - File.Delete(cpObjectsJsonFP); - - if (Directory.Exists(smartConnectorArchivePath)) - Directory.Delete(smartConnectorArchivePath, true); - } - #endregion + CreateSmartConnector(); } public override int RulesInConvertedPackage() @@ -4607,7 +4573,7 @@ public override void ExportConfigurationAsHtml() file.WriteLine(""); file.WriteLine(""); - file.WriteLine("

Cisco config file

"); + file.WriteLine("

Cisco config file

"); file.WriteLine(""); file.WriteLine(" "); @@ -4616,12 +4582,12 @@ public override void ExportConfigurationAsHtml() file.WriteLine(" "); file.WriteLine(" "); file.WriteLine(" "); - file.WriteLine("
Colors Legend
Unknown commands
Commands with conversion error
Commands with conversion notification
"); - - file.WriteLine("
"); - file.WriteLine(" " + HtmlAlertImageTag); - file.WriteLine(" Valid Check Point object name consists of the following characters only - \"A-Za-z0-9_.-\". Any invalid character will be replaced with a \"_\" character."); - file.WriteLine(" "); + file.WriteLine(""); + + file.WriteLine("
"); + file.WriteLine(" " + HtmlAlertImageTag); + file.WriteLine(" Valid Check Point object name consists of the following characters only - \"A-Za-z0-9_.-\". Any invalid character will be replaced with a \"_\" character."); + file.WriteLine(" "); file.WriteLine("
"); if (_conversionIncidents.Count > 0) @@ -4668,7 +4634,7 @@ public override void ExportConfigurationAsHtml() file.WriteLine("
"); file.WriteLine("

Conversion Issues

"); - bool first = true; + bool first = true; ConversionIncident prevErr = null; foreach (ConversionIncident err in _conversionIncidents.OrderByDescending(item => item.IncidentType).ThenBy(item => item.Title).ThenBy(item => item.LineNumber).ToList()) @@ -4684,8 +4650,8 @@ public override void ExportConfigurationAsHtml() file.WriteLine("

" + err.Title + "

"); } file.WriteLine(""); - } - + } + if (!first && prevErr.Title != err.Title) { file.WriteLine("
"); @@ -4699,18 +4665,18 @@ public override void ExportConfigurationAsHtml() file.WriteLine("

" + err.Title + "

"); } file.WriteLine(""); - } - - // Do not display the same description for the same line... - if (prevErr == null || prevErr.LineNumber != err.LineNumber || prevErr.Description != err.Description) - { - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - } - - first = false; + } + + // Do not display the same description for the same line... + if (prevErr == null || prevErr.LineNumber != err.LineNumber || prevErr.Description != err.Description) + { + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + } + + first = false; prevErr = err; } } @@ -4739,7 +4705,7 @@ public override void ExportPolicyPackagesAsHtml() // Generate the report body file.WriteLine("
" + err.LineNumber + "" + err.Description + "
" + err.LineNumber + "" + err.Description + "
"); file.WriteLine(" "); - file.WriteLine(" "); + file.WriteLine(" "); file.WriteLine(" "); int ruleNumber = 1; @@ -4773,12 +4739,12 @@ public override void ExportPolicyPackagesAsHtml() file.WriteLine(" "); if (isSubPolicy) { - file.WriteLine(" "); } else { - file.WriteLine(" "); + file.WriteLine(" "); } } else @@ -4786,12 +4752,12 @@ public override void ExportPolicyPackagesAsHtml() file.WriteLine(" "); if (isSubPolicy) { - file.WriteLine(" "); } else { - file.WriteLine(" "); + file.WriteLine(" "); } } file.WriteLine(" "); @@ -4815,6 +4781,26 @@ public override void ExportPolicyPackagesAsHtml() { if (subRule.Layer == rule.SubPolicyName) { + bool isSubSubPolicy = false; + string subAction = ""; + string subActionStyle = ""; + + switch (subRule.Action) + { + case CheckPoint_Rule.ActionType.Accept: + case CheckPoint_Rule.ActionType.Drop: + case CheckPoint_Rule.ActionType.Reject: + subAction = subRule.Action.ToString(); + subActionStyle = subRule.Action.ToString().ToLower(); + break; + + case CheckPoint_Rule.ActionType.SubPolicy: + isSubSubPolicy = true; + subAction = "Sub-policy: " + subRule.SubPolicyName; + subActionStyle = ""; + break; + } + var ruleConversionIncidentType = ConversionIncidentType.None; bool isInspectedRule = !string.IsNullOrEmpty(subRule.Tag); string curRuleNumber = ruleNumber + "." + subRuleNumber; @@ -4831,8 +4817,17 @@ public override void ExportPolicyPackagesAsHtml() var sbCurRuleNumberColumnTag = new StringBuilder(); sbCurRuleNumberColumnTag.Append(" "); file.WriteLine(" "); file.WriteLine(" "); - file.WriteLine(" "); + //file.WriteLine(" "); + file.WriteLine(" "); file.WriteLine(" "); file.WriteLine(" "); file.WriteLine(" "); file.WriteLine(" "); file.WriteLine(" "); + if (isSubSubPolicy) + { + foreach (CheckPoint_Layer subSubPolicy in package.SubPolicies) + { + int subSubRuleNumber = 1; + + foreach (CheckPoint_Rule subSubRule in subSubPolicy.Rules) + { + //if (subSubRule.Layer == subRule.SubPolicyName || subSubRule.Layer == subRule.SubPolicyName + "_opt") + if (subSubRule.Layer == subRule.SubPolicyName) + { + var subRuleConversionIncidentType = ConversionIncidentType.None; + string subCurRuleNumber = ruleNumber + "." + subRuleNumber + "." + subSubRuleNumber; + string subCurRuleId = ruleIdPrefix + subCurRuleNumber; + + if (subSubRule.Enabled) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + + var sbSubCurRuleNumberColumnTag = new StringBuilder(); + sbSubCurRuleNumberColumnTag.Append(" "); + file.WriteLine(sbSubCurRuleNumberColumnTag.ToString()); + + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + + subSubRuleNumber++; + + if (package.ConversionIncidentType != ConversionIncidentType.None && subRuleConversionIncidentType != ConversionIncidentType.None) + { + if (subRuleConversionIncidentType == ConversionIncidentType.ManualActionRequired) + { + rulesWithConversionErrors.Add(subCurRuleId, subSubRule); + } + else + { + rulesWithConversionInfos.Add(subCurRuleId, subSubRule); + } + } + } + } + } + } + + subRuleNumber++; if (package.ConversionIncidentType != ConversionIncidentType.None && ruleConversionIncidentType != ConversionIncidentType.None) diff --git a/CiscoMigration/CiscoParser.cs b/CiscoMigration/CiscoParser.cs index cb990e6e..63c26f82 100644 --- a/CiscoMigration/CiscoParser.cs +++ b/CiscoMigration/CiscoParser.cs @@ -1,331 +1,331 @@ -/******************************************************************** -Copyright (c) 2017, Check Point Software Technologies Ltd. -All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -********************************************************************/ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using Newtonsoft.Json; -using CommonUtils; -using MigrationBase; - -namespace CiscoMigration -{ - /// - /// Parses the Cisco ASA configuration file and creates corresponding Cisco Command objects repository. - /// - public class CiscoParser : VendorParser - { - #region Helper Classes - - private class Indentation - { - public int? Id { get; private set; } - public int Spaces { get; private set; } - - public Indentation(int? id, int spaces) - { - Id = id; - Spaces = spaces; - } - } - - #endregion - - #region Private Members - - private IList _ciscoCommands = new List(); - private Dictionary _ciscoIds = new Dictionary(); +/******************************************************************** +Copyright (c) 2017, Check Point Software Technologies Ltd. +All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +********************************************************************/ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using Newtonsoft.Json; +using CommonUtils; +using MigrationBase; + +namespace CiscoMigration +{ + /// + /// Parses the Cisco ASA configuration file and creates corresponding Cisco Command objects repository. + /// + public class CiscoParser : VendorParser + { + #region Helper Classes + + private class Indentation + { + public int? Id { get; private set; } + public int Spaces { get; private set; } + + public Indentation(int? id, int spaces) + { + Id = id; + Spaces = spaces; + } + } + + #endregion + + #region Private Members + + private IList _ciscoCommands = new List(); + private Dictionary _ciscoIds = new Dictionary(); private Dictionary _ciscoAliases = new Dictionary(); - public static bool SpreadAclRemarks = false; - - #endregion - - #region Public Methods - - public override void Parse(string filename) - { - ParseCommands(filename); // this must come first!!! - ParseVersion(null); - ParseInterfacesTopology(); - } - - public override void Export(string filename) - { - File.WriteAllText(filename, JsonConvert.SerializeObject(_ciscoCommands, Formatting.Indented)); - } - - public List Filter(string commandName = "") - { - var filter = new List(); - - foreach (CiscoCommand command in _ciscoCommands) - { - if (commandName == "" || command.Name() == commandName) - { - filter.Add(command); - } - } - - return filter; - } - - public List Flatten() - { - var flatten = new List(); - - foreach (CiscoCommand command in _ciscoCommands) - { - foreach (CiscoCommand flat in command.Flatten()) - { - flatten.Add(flat); - } - } - - return flatten; - } - - public CiscoCommand GetCommandByCiscoId(string ciscoId) - { - return (from kvp in _ciscoIds where kvp.Key == ciscoId select kvp.Value).FirstOrDefault(); - } - - #endregion - - #region Private Methods - - protected override void ParseVersion(object versionProvider) - { - foreach (Cisco_ASA asa in Filter("ASA")) - { - VendorVersion = asa.Version; - } - } - - private void ParseCommands(string filename) - { - string[] lines = File.ReadAllLines(filename); - ParsedLines = lines.Count(); - - var parents = new Stack(); - var flatList = new List(); - - parents.Push(new Indentation(null, 0)); - - int prevIndentationLevel = 0; - int lineId = 0; - - foreach (string line in lines) - { - lineId++; - - // Check for an empty line or line with just spaces. - if (line.Trim().Length == 0) - { - continue; - } - - // Check for weird stuff - if (line.StartsWith("#") || line.StartsWith("<-")) - { - continue; - } - - var command = new CiscoCommand - { - Id = lineId, - Text = line - }; - - int indentationChange = command.IndentationLevel - prevIndentationLevel; - if (indentationChange > 0) - { - parents.Push(new Indentation(flatList.Last().Id, flatList.Last().IndentationLevel)); - } - else if (indentationChange < 0 && parents.Count > 0) - { - parents.Pop(); - while ((parents.Count > 0) && (parents.Peek().Spaces > command.IndentationLevel)) - { - parents.Pop(); - } - } - - command.ParentId = (parents.Count > 0) ? parents.Peek().Id : null; - - prevIndentationLevel = command.IndentationLevel; - flatList.Add(FindCommand(command)); - } - - _ciscoCommands = flatList.BuildTree(); - - CiscoCommand prevCommand = null; - foreach (CiscoCommand command in _ciscoCommands) - { - ParseWithChildren(command, prevCommand); - prevCommand = command; - } - - // Remove duplicates - foreach (var ciscoId in _ciscoIds) - { - if (_ciscoAliases.ContainsKey(ciscoId.Key)) - { - _ciscoAliases.Remove(ciscoId.Key); - } - } - } - - private void ParseInterfacesTopology() - { - // Add related static routing information to interface topology - IEnumerable ciscoInterfaceCommands = Filter("interface"); - IEnumerable ciscoRouteCommands = Filter("route"); - - foreach (Cisco_Interface ciscoInterface in ciscoInterfaceCommands) - { - if (!string.IsNullOrEmpty(ciscoInterface.CiscoId)) - { - foreach (Cisco_Route route in ciscoRouteCommands) - { - string routeInterfaceName = CiscoCommand.InterfacePrefix + route.InterfaceName; - if (routeInterfaceName == ciscoInterface.CiscoId) - { - ciscoInterface.Topology.Add(new Cisco_Interface.Subnet(route.DestinationIp, route.DestinationNetmask)); - - if (route.DefaultRoute) - { - ciscoInterface.LeadsToInternet = true; - } - - if (route.ConversionIncidentType != ConversionIncidentType.None) - { - ciscoInterface.ConversionIncidentType = route.ConversionIncidentType; - ciscoInterface.ConversionIncidentMessage = route.ConversionIncidentMessage; - } - } - } - } - } - } - - private CiscoCommand FindCommand(CiscoCommand command) - { - string[] irrelevantCommands = - { - "!", ":", "speed", "dns-guard", "domain-name", "duplex", "passwd", "banner", "boot", "dns", "failover", "asdm", "arp", "clock", "mtu", "timeout" - }; - - if (irrelevantCommands.Contains(command.FirstWord)) - { - command.NotAnInterestingCommand = true; - } - - var ciscoCommandTypes = Assembly.GetExecutingAssembly().GetTypes().Where(commandType => commandType.GetInterfaces().Contains(typeof(ICiscoCommand))); - - foreach (Type commandType in ciscoCommandTypes) - { - object knownCommand = Activator.CreateInstance(commandType); - string knownCommandName = (string)knownCommand.GetType().GetMethod("Name").Invoke(knownCommand, null); - - if (knownCommandName == command.FirstWord) - { - ((CiscoCommand)knownCommand).CiscoId = command.CiscoId; - ((CiscoCommand)knownCommand).Id = command.Id; - ((CiscoCommand)knownCommand).Text = command.Text; - ((CiscoCommand)knownCommand).ParentId = command.ParentId; - ((CiscoCommand)knownCommand).KnownCommand = true; - ((CiscoCommand)knownCommand).NotAnInterestingCommand = false; - - return (CiscoCommand)knownCommand; - } - } - - command.KnownCommand = false; - return command; - } - - private void ParseWithChildren(CiscoCommand command, CiscoCommand prevCommand) - { - if (command.Children == null || !command.Children.Any()) - { - command.Parse(command, prevCommand, _ciscoIds, _ciscoAliases); - - if (!string.IsNullOrEmpty(command.CiscoId) && !_ciscoIds.ContainsKey(command.CiscoId)) - { - _ciscoIds.Add(command.CiscoId, command); - } - - return; - } - - CiscoCommand prevChild = null; - foreach (CiscoCommand child in command.Children) - { - ParseWithChildren(child, prevChild); - prevChild = child; - } - - command.Parse(command, prevCommand, _ciscoIds, _ciscoAliases); - - if (!string.IsNullOrEmpty(command.CiscoId) && !_ciscoIds.ContainsKey(command.CiscoId)) - { - _ciscoIds.Add(command.CiscoId, command); - } - } - - #endregion - } - - public static class GroupEnumerable - { - public static IList BuildTree(this IEnumerable source) - { - var groups = source.GroupBy(i => i.ParentId); - var roots = groups.FirstOrDefault(g => g.Key.HasValue == false).ToList(); - - if (roots.Count > 0) - { - var children = groups.Where(g => g.Key.HasValue).ToDictionary(g => g.Key.Value, g => g.ToList()); - for (int i = 0; i < roots.Count; i++) - { - AddChildren(roots[i], children); - } - } - - return roots; - } - - private static void AddChildren(CiscoCommand node, IDictionary> source) - { - if (source.ContainsKey(node.Id)) - { - node.Children = source[node.Id]; - for (int i = 0; i < node.Children.Count; i++) - { - AddChildren(node.Children[i], source); - } - } - else - { - node.Children = new List(); - } - } - } -} + public static bool SpreadAclRemarks = false; + + #endregion + + #region Public Methods + + public override void Parse(string filename) + { + ParseCommands(filename); // this must come first!!! + ParseVersion(null); + ParseInterfacesTopology(); + } + + public override void Export(string filename) + { + File.WriteAllText(filename, JsonConvert.SerializeObject(_ciscoCommands, Formatting.Indented)); + } + + public List Filter(string commandName = "") + { + var filter = new List(); + + foreach (CiscoCommand command in _ciscoCommands) + { + if (commandName == "" || command.Name() == commandName) + { + filter.Add(command); + } + } + + return filter; + } + + public List Flatten() + { + var flatten = new List(); + + foreach (CiscoCommand command in _ciscoCommands) + { + foreach (CiscoCommand flat in command.Flatten()) + { + flatten.Add(flat); + } + } + + return flatten; + } + + public CiscoCommand GetCommandByCiscoId(string ciscoId) + { + return (from kvp in _ciscoIds where kvp.Key == ciscoId select kvp.Value).FirstOrDefault(); + } + + #endregion + + #region Private Methods + + protected override void ParseVersion(object versionProvider) + { + foreach (Cisco_ASA asa in Filter("ASA")) + { + VendorVersion = asa.Version; + } + } + + private void ParseCommands(string filename) + { + string[] lines = File.ReadAllLines(filename); + ParsedLines = lines.Count(); + + var parents = new Stack(); + var flatList = new List(); + + parents.Push(new Indentation(null, 0)); + + int prevIndentationLevel = 0; + int lineId = 0; + + foreach (string line in lines) + { + lineId++; + + // Check for an empty line or line with just spaces. + if (line.Trim().Length == 0) + { + continue; + } + + // Check for weird stuff + if (line.StartsWith("#") || line.StartsWith("<-")) + { + continue; + } + + var command = new CiscoCommand + { + Id = lineId, + Text = line + }; + + int indentationChange = command.IndentationLevel - prevIndentationLevel; + if (indentationChange > 0) + { + parents.Push(new Indentation(flatList.Last().Id, flatList.Last().IndentationLevel)); + } + else if (indentationChange < 0 && parents.Count > 0) + { + parents.Pop(); + while ((parents.Count > 0) && (parents.Peek().Spaces > command.IndentationLevel)) + { + parents.Pop(); + } + } + + command.ParentId = (parents.Count > 0) ? parents.Peek().Id : null; + + prevIndentationLevel = command.IndentationLevel; + flatList.Add(FindCommand(command)); + } + + _ciscoCommands = flatList.BuildTree(); + + CiscoCommand prevCommand = null; + foreach (CiscoCommand command in _ciscoCommands) + { + ParseWithChildren(command, prevCommand); + prevCommand = command; + } + + // Remove duplicates + foreach (var ciscoId in _ciscoIds) + { + if (_ciscoAliases.ContainsKey(ciscoId.Key)) + { + _ciscoAliases.Remove(ciscoId.Key); + } + } + } + + private void ParseInterfacesTopology() + { + // Add related static routing information to interface topology + IEnumerable ciscoInterfaceCommands = Filter("interface"); + IEnumerable ciscoRouteCommands = Filter("route"); + + foreach (Cisco_Interface ciscoInterface in ciscoInterfaceCommands) + { + if (!string.IsNullOrEmpty(ciscoInterface.CiscoId)) + { + foreach (Cisco_Route route in ciscoRouteCommands) + { + string routeInterfaceName = CiscoCommand.InterfacePrefix + route.InterfaceName; + if (routeInterfaceName == ciscoInterface.CiscoId) + { + ciscoInterface.Topology.Add(new Cisco_Interface.Subnet(route.DestinationIp, route.DestinationNetmask)); + + if (route.DefaultRoute) + { + ciscoInterface.LeadsToInternet = true; + } + + if (route.ConversionIncidentType != ConversionIncidentType.None) + { + ciscoInterface.ConversionIncidentType = route.ConversionIncidentType; + ciscoInterface.ConversionIncidentMessage = route.ConversionIncidentMessage; + } + } + } + } + } + } + + private CiscoCommand FindCommand(CiscoCommand command) + { + string[] irrelevantCommands = + { + "!", ":", "speed", "dns-guard", "domain-name", "duplex", "passwd", "banner", "boot", "dns", "failover", "asdm", "arp", "clock", "mtu", "timeout" + }; + + if (irrelevantCommands.Contains(command.FirstWord)) + { + command.NotAnInterestingCommand = true; + } + + var ciscoCommandTypes = Assembly.GetExecutingAssembly().GetTypes().Where(commandType => commandType.GetInterfaces().Contains(typeof(ICiscoCommand))); + + foreach (Type commandType in ciscoCommandTypes) + { + object knownCommand = Activator.CreateInstance(commandType); + string knownCommandName = (string)knownCommand.GetType().GetMethod("Name").Invoke(knownCommand, null); + + if (knownCommandName == command.FirstWord) + { + ((CiscoCommand)knownCommand).CiscoId = command.CiscoId; + ((CiscoCommand)knownCommand).Id = command.Id; + ((CiscoCommand)knownCommand).Text = command.Text; + ((CiscoCommand)knownCommand).ParentId = command.ParentId; + ((CiscoCommand)knownCommand).KnownCommand = true; + ((CiscoCommand)knownCommand).NotAnInterestingCommand = false; + + return (CiscoCommand)knownCommand; + } + } + + command.KnownCommand = false; + return command; + } + + private void ParseWithChildren(CiscoCommand command, CiscoCommand prevCommand) + { + if (command.Children == null || !command.Children.Any()) + { + command.Parse(command, prevCommand, _ciscoIds, _ciscoAliases); + + if (!string.IsNullOrEmpty(command.CiscoId) && !_ciscoIds.ContainsKey(command.CiscoId)) + { + _ciscoIds.Add(command.CiscoId, command); + } + + return; + } + + CiscoCommand prevChild = null; + foreach (CiscoCommand child in command.Children) + { + ParseWithChildren(child, prevChild); + prevChild = child; + } + + command.Parse(command, prevCommand, _ciscoIds, _ciscoAliases); + + if (!string.IsNullOrEmpty(command.CiscoId) && !_ciscoIds.ContainsKey(command.CiscoId)) + { + _ciscoIds.Add(command.CiscoId, command); + } + } + + #endregion + } + + public static class GroupEnumerable + { + public static IList BuildTree(this IEnumerable source) + { + var groups = source.GroupBy(i => i.ParentId); + var roots = groups.FirstOrDefault(g => g.Key.HasValue == false).ToList(); + + if (roots.Count > 0) + { + var children = groups.Where(g => g.Key.HasValue).ToDictionary(g => g.Key.Value, g => g.ToList()); + for (int i = 0; i < roots.Count; i++) + { + AddChildren(roots[i], children); + } + } + + return roots; + } + + private static void AddChildren(CiscoCommand node, IDictionary> source) + { + if (source.ContainsKey(node.Id)) + { + node.Children = source[node.Id]; + for (int i = 0; i < node.Children.Count; i++) + { + AddChildren(node.Children[i], source); + } + } + else + { + node.Children = new List(); + } + } + } +} diff --git a/FortinetMigration/FortiGateConverter.cs b/FortinetMigration/FortiGateConverter.cs index 5c6c84f6..dcfcebeb 100644 --- a/FortinetMigration/FortiGateConverter.cs +++ b/FortinetMigration/FortiGateConverter.cs @@ -1,96 +1,96 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using CommonUtils; -using MigrationBase; -using CheckPointObjects; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Net; - -namespace FortiGateMigration -{ - public class FortiGateConverter : VendorConverter - { - #region GUI params - - 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 - - #endregion - - #region Private Members - - private FortiGateParser _fortiGateParser; - - private HashSet _vDomNames = new HashSet(); - - 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> _interfacesMapperFgCp = new Dictionary>(); //storing information about interfaces - - private Dictionary _intfAliasNamesMapper = new Dictionary(); //storing information about interfaces aliases - - private Dictionary _vipPortForwardEnabledMapper = new Dictionary(); //storing VIP which has port_forward - - private List _localIntrazonesList = new List(); //storing all Intrazones - - private Dictionary _interfacesFgDict = new Dictionary(); //storing Fortigate interfaces by their names - - private Dictionary> _localFgVipGrpsDict = new Dictionary>(); //storing Fortigate VIP groups with native members - private Dictionary> _localFgZoneIntfDict = new Dictionary>(); //storing Fortigate Interfaces list for each Zone - private Dictionary> _localFgRoutesDict = new Dictionary>(); //storing Fortigate static routes by Interface name - private bool _localFgDynRoutesEnable = false; //indicate if Fortigate dynamic routing is enable - - private int _timeCutterCounter = 0; //postfix for Time objects - private int _timeGroupCutterCounter = 0; //postfix for TimeGroup objects - - private int _warningsConvertedPackage = 0; //flag - private int _errorsConvertedPackage = 0; //flag - - private int _rulesInConvertedPackage = 0; //counter - private int _rulesInNatLayer = 0; //counter - - /* - * keys for mapping Fortigate objects names to CheckPoint objects - */ - private const string FG_PREFIX_KEY_firewall_address = "firewall_address_"; - private const string FG_PREFIX_KEY_firewall_addrgrp = "firewall_addrgrp_"; - private const string FG_PREFIX_KEY_firewall_vip_extip = "firewall_vip_extip_"; - private const string FG_PREFIX_KEY_firewall_vip_mappedip = "firewall_vip_mappedip_"; - private const string FG_PREFIX_KEY_firewall_vip_grp = "firewall_vip_grp_"; - private const string FG_PREFIX_KEY_firewall_service_custom = "firewall_service_custom_"; - private const string FG_PREFIX_KEY_firewall_service_custom_vipe_ = "firewall_service_custom_VIPe_"; - private const string FG_PREFIX_KEY_firewall_service_custom_vipm_ = "firewall_service_custom_VIPm_"; - - private const string FG_PREFIX_KEY_firewall_service_group = "firewall_service_group_"; - private const string FG_PREFIX_KEY_firewall_schedule_recurring = "firewall_schedule_recurring_"; - private const string FG_PREFIX_KEY_firewall_schedule_onetime = "firewall_schedule_onetime_"; - private const string FG_PREFIX_KEY_firewall_schedule_group = "firewall_schedule_group_"; - private const string FG_PREFIX_KEY_firewall_ippool = "firewall_ippool_"; - //private const string FG_PREFIX_KEY_firewall_ippool_source = "firewall_ippool_source_"; - private const string FG_PREFIX_KEY_system_zone = "system_zone_"; - private const string FG_PREFIX_KEY_system_zone_host = "system_zone_host_"; - - private const string FG_PREFIX_KEY_user_group = "user_group_"; - - #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) - { - _fortiGateParser = (FortiGateParser)vendorParser; - if (_fortiGateParser == null) - { - throw new InvalidDataException("Unexpected!!!"); - } - base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName); +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using CommonUtils; +using MigrationBase; +using CheckPointObjects; +using System.Globalization; +using System.Text.RegularExpressions; +using System.Net; + +namespace FortiGateMigration +{ + public class FortiGateConverter : VendorConverter + { + #region GUI params + + 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 + + #endregion + + #region Private Members + + private FortiGateParser _fortiGateParser; + + private HashSet _vDomNames = new HashSet(); + + 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> _interfacesMapperFgCp = new Dictionary>(); //storing information about interfaces + + private Dictionary _intfAliasNamesMapper = new Dictionary(); //storing information about interfaces aliases + + private Dictionary _vipPortForwardEnabledMapper = new Dictionary(); //storing VIP which has port_forward + + private List _localIntrazonesList = new List(); //storing all Intrazones + + private Dictionary _interfacesFgDict = new Dictionary(); //storing Fortigate interfaces by their names + + private Dictionary> _localFgVipGrpsDict = new Dictionary>(); //storing Fortigate VIP groups with native members + private Dictionary> _localFgZoneIntfDict = new Dictionary>(); //storing Fortigate Interfaces list for each Zone + private Dictionary> _localFgRoutesDict = new Dictionary>(); //storing Fortigate static routes by Interface name + private bool _localFgDynRoutesEnable = false; //indicate if Fortigate dynamic routing is enable + + private int _timeCutterCounter = 0; //postfix for Time objects + private int _timeGroupCutterCounter = 0; //postfix for TimeGroup objects + + private int _warningsConvertedPackage = 0; //flag + private int _errorsConvertedPackage = 0; //flag + + private int _rulesInConvertedPackage = 0; //counter + private int _rulesInNatLayer = 0; //counter + + /* + * keys for mapping Fortigate objects names to CheckPoint objects + */ + private const string FG_PREFIX_KEY_firewall_address = "firewall_address_"; + private const string FG_PREFIX_KEY_firewall_addrgrp = "firewall_addrgrp_"; + private const string FG_PREFIX_KEY_firewall_vip_extip = "firewall_vip_extip_"; + private const string FG_PREFIX_KEY_firewall_vip_mappedip = "firewall_vip_mappedip_"; + private const string FG_PREFIX_KEY_firewall_vip_grp = "firewall_vip_grp_"; + private const string FG_PREFIX_KEY_firewall_service_custom = "firewall_service_custom_"; + private const string FG_PREFIX_KEY_firewall_service_custom_vipe_ = "firewall_service_custom_VIPe_"; + private const string FG_PREFIX_KEY_firewall_service_custom_vipm_ = "firewall_service_custom_VIPm_"; + + private const string FG_PREFIX_KEY_firewall_service_group = "firewall_service_group_"; + private const string FG_PREFIX_KEY_firewall_schedule_recurring = "firewall_schedule_recurring_"; + private const string FG_PREFIX_KEY_firewall_schedule_onetime = "firewall_schedule_onetime_"; + private const string FG_PREFIX_KEY_firewall_schedule_group = "firewall_schedule_group_"; + private const string FG_PREFIX_KEY_firewall_ippool = "firewall_ippool_"; + //private const string FG_PREFIX_KEY_firewall_ippool_source = "firewall_ippool_source_"; + private const string FG_PREFIX_KEY_system_zone = "system_zone_"; + private const string FG_PREFIX_KEY_system_zone_host = "system_zone_host_"; + + private const string FG_PREFIX_KEY_user_group = "user_group_"; + + #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) + { + _fortiGateParser = (FortiGateParser)vendorParser; + if (_fortiGateParser == null) + { + throw new InvalidDataException("Unexpected!!!"); + } + base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName); } protected override bool AddCheckPointObject(CheckPointObject cpObject) @@ -105,4603 +105,4605 @@ protected override bool AddCheckPointObject(CheckPointObject cpObject) } return false; - } - - #region Methods are used for reports - - //count of converted rules. - // -1 is VDOM - public override int RulesInConvertedPackage() - { - return _rulesInConvertedPackage; - } - - //count of warnings of conversion - // -1 if VDOM - public int WarningsInConvertedPackage() - { - return _warningsConvertedPackage; - } - - //count of errors of conversion - // -1 if VDOM - public int ErrorsInConvertedPackage() - { - return _errorsConvertedPackage; - } - - public override int RulesInConvertedOptimizedPackage() - { - return 0; - } - - //count of NAT rules - // -1 if VDOM - public override int RulesInNatLayer() - { - return _rulesInNatLayer; - } - - public override void ExportConfigurationAsHtml() - { - //not used as we have vDOMs - } - - public override void ExportPolicyPackagesAsHtml() - { - //not used as we have vDOMs - } - - public void ExportPolicyPackagesAsHtmlConfig() - { - const string ruleIdPrefix = "rule_"; - - foreach (CheckPoint_Package package in _cpPackages) - { - string filename = _targetFolder + "\\" + package.Name + ".html"; - - using (var file = new StreamWriter(filename, false)) - { - var rulesWithConversionErrors = new Dictionary(); - var rulesWithConversionInfos = new Dictionary(); - var rulesWithInspection = new Dictionary>(); - - GeneratePackageHtmlReportHeaders(file, package.Name, package.ConversionIncidentType != ConversionIncidentType.None); - - // Generate the report body - file.WriteLine("
No. Name Source Destination Service Action Time Track Comments Conversion CommentsNo. Name Source Destination Service Action Time Track Comments Conversion Comments
" + + file.WriteLine(" " + string.Format(HtmlSubPolicyArrowImageTagFormat, curParentRuleId + "_img", HtmlDownArrowImageSourceData) + ruleNumber + "" + ruleNumber + "" + ruleNumber + "
" + + file.WriteLine(" " + string.Format(HtmlSubPolicyArrowImageTagFormat, curParentRuleId + "_img", HtmlDownArrowImageSourceData) + ruleNumber + HtmlDisabledImageTag + "" + ruleNumber + HtmlDisabledImageTag + "" + ruleNumber + HtmlDisabledImageTag + "" + rule.Name + ""); - sbCurRuleNumberColumnTag.Append(" "); - sbCurRuleNumberColumnTag.Append(curRuleNumber); + if (isSubSubPolicy) + { + sbCurRuleNumberColumnTag.Append(" " + + string.Format(HtmlSubPolicyArrowImageTagFormat, curRuleId + "_img", HtmlDownArrowImageSourceData) + curRuleNumber); + } + else + { + sbCurRuleNumberColumnTag.Append(" "); + sbCurRuleNumberColumnTag.Append(curRuleNumber); + } + if (isInspectedRule) { sbCurRuleNumberColumnTag.Append(BuildInspectedRuleInfo(subRule.Tag)); @@ -4853,13 +4848,85 @@ public override void ExportPolicyPackagesAsHtml() file.WriteLine(" " + RuleItemsList2Html(subRule.Source, subRule.SourceNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + RuleItemsList2Html(subRule.Destination, subRule.DestinationNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + RuleItemsList2Html(subRule.Service, false, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + subRule.Action.ToString() + "" + subRule.Action.ToString() + "" + subAction + "" + RuleItemsList2Html(subRule.Time, false, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + subRule.Track.ToString() + "" + subRule.Comments + "" + subRule.ConversionComments + "
"); + sbSubCurRuleNumberColumnTag.Append(" "); + sbSubCurRuleNumberColumnTag.Append(" "); + sbSubCurRuleNumberColumnTag.Append(subCurRuleNumber); + if (subSubRule.ConversionIncidentType != ConversionIncidentType.None) + { + sbSubCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(subSubRule.ConvertedCommandId)); + subRuleConversionIncidentType = subSubRule.ConversionIncidentType; + } + if (!subSubRule.Enabled) + { + sbSubCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); + } + sbSubCurRuleNumberColumnTag.Append("" + subSubRule.Name + "" + RuleItemsList2Html(subSubRule.Source, subSubRule.SourceNegated, CheckPointObject.Any, ref subRuleConversionIncidentType) + "" + RuleItemsList2Html(subSubRule.Destination, subSubRule.DestinationNegated, CheckPointObject.Any, ref subRuleConversionIncidentType) + "" + RuleItemsList2Html(subSubRule.Service, false, CheckPointObject.Any, ref subRuleConversionIncidentType) + "" + subSubRule.Action.ToString() + "" + RuleItemsList2Html(subSubRule.Time, false, CheckPointObject.Any, ref subRuleConversionIncidentType) + "" + subSubRule.Track.ToString() + "" + subSubRule.Comments + "" + subSubRule.ConversionComments + "
"); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - - int ruleNumber = 1; - - foreach (CheckPoint_Rule rule in package.ParentLayer.Rules) - { - bool isSubPolicy = false; - string action = ""; - string actionStyle = ""; - var dummy = ConversionIncidentType.None; - - switch (rule.Action) - { - case CheckPoint_Rule.ActionType.Accept: - case CheckPoint_Rule.ActionType.Drop: - action = rule.Action.ToString(); - actionStyle = rule.Action.ToString().ToLower(); - break; - - case CheckPoint_Rule.ActionType.SubPolicy: - isSubPolicy = true; - action = "Sub-policy: " + rule.SubPolicyName; - actionStyle = ""; - break; - } - - string curParentRuleId = string.Format("{0}{1}", ruleIdPrefix, ruleNumber); - - if (rule.Enabled) - { - file.WriteLine(" "); - if (isSubPolicy) - { - file.WriteLine(" "); - } - else - { - file.WriteLine(" "); - } - } - else - { - file.WriteLine(" "); - if (isSubPolicy) - { - file.WriteLine(" "); - } - else - { - file.WriteLine(" "); - } - } - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - - if (isSubPolicy) - { - foreach (CheckPoint_Layer subPolicy in package.SubPolicies) - { - int subRuleNumber = 1; - - foreach (CheckPoint_Rule subRule in subPolicy.Rules) - { - if (subRule.Layer == rule.SubPolicyName) - { - var ruleConversionIncidentType = ConversionIncidentType.None; - bool isInspectedRule = !string.IsNullOrEmpty(subRule.Tag); - string curRuleNumber = ruleNumber + "." + subRuleNumber; - string curRuleId = ruleIdPrefix + curRuleNumber; - - if (subRule.Enabled) - { - file.WriteLine(" "); - } - else - { - file.WriteLine(" "); - } - - var sbCurRuleNumberColumnTag = new StringBuilder(); - sbCurRuleNumberColumnTag.Append(" "); - file.WriteLine(sbCurRuleNumberColumnTag.ToString()); - - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - - subRuleNumber++; - - if (package.ConversionIncidentType != ConversionIncidentType.None && ruleConversionIncidentType != ConversionIncidentType.None) - { - if (ruleConversionIncidentType == ConversionIncidentType.ManualActionRequired) - { - rulesWithConversionErrors.Add(curRuleId, subRule); - } - else - { - rulesWithConversionInfos.Add(curRuleId, subRule); - } - } - - if (isInspectedRule) - { - string[] fortiClassMapNames = subRule.Tag.Split(','); // there may be several class-maps matching the same fw rule... - subRule.Tag = curRuleId; // replace class-map name (it is now the key of this dic) by curRuleId... - - foreach (var classMapName in fortiClassMapNames) - { - if (!rulesWithInspection.ContainsKey(classMapName)) - { - var inspectedRules = new List(); - rulesWithInspection.Add(classMapName, inspectedRules); - } - rulesWithInspection[classMapName].Add(subRule); - } - } - } - } - } - } - - ruleNumber++; - } - - file.WriteLine("
No. Name Source Destination Service Action Time Track Comments Conversion Comments
" + - string.Format(HtmlSubPolicyArrowImageTagFormat, curParentRuleId + "_img", HtmlDownArrowImageSourceData) + ruleNumber + "" + ruleNumber + "
" + - string.Format(HtmlSubPolicyArrowImageTagFormat, curParentRuleId + "_img", HtmlDownArrowImageSourceData) + ruleNumber + HtmlDisabledImageTag + "" + ruleNumber + HtmlDisabledImageTag + "" + rule.Name + "" + RuleItemsList2Html(rule.Source, rule.SourceNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(rule.Destination, rule.DestinationNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(rule.Service, false, CheckPointObject.Any, ref dummy) + "" + action + "" + RuleItemsList2Html(rule.Time, false, CheckPointObject.Any, ref dummy) + "" + rule.Track.ToString() + "" + rule.Comments + "" + rule.ConversionComments + "
"); - sbCurRuleNumberColumnTag.Append(" "); - sbCurRuleNumberColumnTag.Append(curRuleNumber); - if (isInspectedRule) - { - sbCurRuleNumberColumnTag.Append(BuildInspectedRuleInfo(subRule.Tag)); - } - if (subRule.ConversionIncidentType != ConversionIncidentType.None) - { - sbCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(subRule.ConvertedCommandId)); - ruleConversionIncidentType = subRule.ConversionIncidentType; - } - if (!subRule.Enabled) - { - sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); - } - sbCurRuleNumberColumnTag.Append("" + subRule.Name + "" + RuleItemsList2Html(subRule.Source, subRule.SourceNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + RuleItemsList2Html(subRule.Destination, subRule.DestinationNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + RuleItemsList2Html(subRule.Service, false, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + subRule.Action.ToString() + "" + RuleItemsList2Html(subRule.Time, false, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + subRule.Track.ToString() + "" + subRule.Comments + "" + subRule.ConversionComments + "
"); - - if (rulesWithConversionErrors.Count > 0 || rulesWithConversionInfos.Count > 0 || rulesWithInspection.Count > 0) - { - file.WriteLine("

Policy Conversion Issues

"); - } - - // Generate the errors report - if (rulesWithConversionErrors.Count > 0) - { - file.WriteLine(""); - - file.WriteLine("

Conversion Errors

"); - file.WriteLine(""); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - - foreach (var ruleEntry in rulesWithConversionErrors) - { - var dummy = ConversionIncidentType.None; - - if (ruleEntry.Value.Enabled) - { - file.WriteLine(" "); - } - else - { - file.WriteLine(" "); - } - - var sbCurRuleNumberColumnTag = new StringBuilder(); - sbCurRuleNumberColumnTag.Append(" "); - file.WriteLine(sbCurRuleNumberColumnTag.ToString()); - - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - } - - file.WriteLine("
No. Name Source Destination Service Action Time Track Comments Conversion Comments
"); - sbCurRuleNumberColumnTag.Append(""); - sbCurRuleNumberColumnTag.Append(ruleEntry.Key.Replace(ruleIdPrefix, "")); - sbCurRuleNumberColumnTag.Append(""); - if (ruleEntry.Value.ConversionIncidentType != ConversionIncidentType.None) - { - sbCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(ruleEntry.Value.ConvertedCommandId)); - } - if (!ruleEntry.Value.Enabled) - { - sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); - } - sbCurRuleNumberColumnTag.Append("" + ruleEntry.Value.Name + "" + RuleItemsList2Html(ruleEntry.Value.Source, ruleEntry.Value.SourceNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Destination, ruleEntry.Value.DestinationNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Service, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Action.ToString() + "" + RuleItemsList2Html(ruleEntry.Value.Time, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Track.ToString() + "" + ruleEntry.Value.Comments + "" + ruleEntry.Value.ConversionComments + "
"); - } - - if (rulesWithConversionInfos.Count > 0 || rulesWithInspection.Count > 0) - { - int counter = (rulesWithInspection.Count > 0) ? 1 : 0; - counter += rulesWithConversionInfos.Count; - - file.WriteLine(""); - file.WriteLine("

Conversion Notifications

"); - } - - // Generate the information report - if (rulesWithConversionInfos.Count > 0) - { - file.WriteLine(""); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - - foreach (var ruleEntry in rulesWithConversionInfos) - { - var dummy = ConversionIncidentType.None; - - if (ruleEntry.Value.Enabled) - { - file.WriteLine(" "); - } - else - { - file.WriteLine(" "); - } - - var sbCurRuleNumberColumnTag = new StringBuilder(); - sbCurRuleNumberColumnTag.Append(" "); - file.WriteLine(sbCurRuleNumberColumnTag.ToString()); - - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - file.WriteLine(" "); - } - - file.WriteLine("
No. Name Source Destination Service Action Time Track Comments Conversion Comments
"); - sbCurRuleNumberColumnTag.Append(""); - sbCurRuleNumberColumnTag.Append(ruleEntry.Key.Replace(ruleIdPrefix, "")); - sbCurRuleNumberColumnTag.Append(""); - if (ruleEntry.Value.ConversionIncidentType != ConversionIncidentType.None) - { - sbCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(ruleEntry.Value.ConvertedCommandId)); - } - if (!ruleEntry.Value.Enabled) - { - sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); - } - sbCurRuleNumberColumnTag.Append("" + ruleEntry.Value.Name + "" + RuleItemsList2Html(ruleEntry.Value.Source, ruleEntry.Value.SourceNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Destination, ruleEntry.Value.DestinationNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Service, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Action.ToString() + "" + RuleItemsList2Html(ruleEntry.Value.Time, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Track.ToString() + "" + ruleEntry.Value.Comments + "" + ruleEntry.Value.ConversionComments + "
"); - } - - file.WriteLine(""); - file.WriteLine(""); - } - } - } - - public string BuildInspectedRuleInfo(string fortiClassMapName) - { - string inspectTooltip = "Rule traffic is affected by FortiGate inspect policy. [class-map objects: " + fortiClassMapName + "]"; - string htmlInspectedImageTag = string.Format(HtmlAlertImageTagFormat, inspectTooltip); - return htmlInspectedImageTag; - } - - //Catalog is Root file if VDOM exists - public void CreateCatalogObjects() - { - string filename = this.ObjectsHtmlFile; - - using (var file = new StreamWriter(filename, false)) - { - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine("

List of VDOMs Objects for " + this._vendorFileName + "

"); - file.WriteLine("
    "); - foreach (string vDomName in _vDomNames) - { - if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_objects.html")) - { - file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); - } - else - { - file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); - } - } - file.WriteLine("
"); - file.WriteLine(""); - file.WriteLine(""); - } - } - - //Catalog is Root file if VDOM exists - public void CreateCatalogPolicies() - { - string filename = this.PolicyHtmlFile; - - using (var file = new StreamWriter(filename, false)) - { - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine("

List of VDOMs Policies for " + this._vendorFileName + "

"); - file.WriteLine("
    "); - foreach (string vDomName in _vDomNames) - { - if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_policy.html")) - { - file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); - } - else - { - file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); - } - } - file.WriteLine("
"); - file.WriteLine(""); - file.WriteLine(""); - } - } - - //Catalog is Root file if VDOM exists - public void CreateCatalogNATs() - { - string filename = this.NatHtmlFile; - - using (var file = new StreamWriter(filename, false)) - { - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine("

List of VDOMs NATs for " + this._vendorFileName + "

"); - file.WriteLine("
    "); - foreach (string vDomName in _vDomNames) - { - if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_NAT.html")) - { - file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); - } - else - { - file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); - } - } - file.WriteLine("
"); - file.WriteLine(""); - file.WriteLine(""); - } - } - - //Catalog is Root file if VDOM exists - public void CreateCatalogErrors() - { - string filename = this._targetFolder + "\\" + _vendorFileName + "_errors.html"; - - using (var file = new StreamWriter(filename, false)) - { - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine("

List of VDOMs Errors for " + this._vendorFileName + "

"); - file.WriteLine("
    "); - foreach (string vDomName in _vDomNames) - { - if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_errors.html")) - { - file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); - } - else - { - file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); - } - } - file.WriteLine("
"); - file.WriteLine(""); - file.WriteLine(""); - } - } - - //Catalog is Root file if VDOM exists - public void CreateCatalogWarnings() - { - string filename = this._targetFolder + "\\" + _vendorFileName + "_warnings.html"; - - using (var file = new StreamWriter(filename, false)) - { - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine("

List of VDOMs Warnings for " + this._vendorFileName + "

"); - file.WriteLine("
    "); - foreach (string vDomName in _vDomNames) - { - if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_warnings.html")) - { - file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); - } - else - { - file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); - } - } - file.WriteLine("
"); - file.WriteLine(""); - file.WriteLine(""); - } - } - - //report about Errors - public void CreateErrorsHtml(string vDomName) - { - if (_errorsList.Count > 0) - { - string filename = _targetFolder + "//" + vDomName + "_errors.html"; - - using (var file = new StreamWriter(filename, false)) - { - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine("

List of " + vDomName + " Errors

"); - file.WriteLine(""); - for (int i = 0; i < _errorsList.Count; i++) - { - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - } - file.WriteLine("
"); - file.WriteLine(i); - file.WriteLine(""); - file.WriteLine(_errorsList[i]); - file.WriteLine("
"); - file.WriteLine(""); - file.WriteLine(""); - } - } - } - - //report about Warnings - public void CreateWarningsHtml(string vDomName) - { - if (_errorsList.Count > 0) - { - string filename = _targetFolder + "//" + vDomName + "_warnings.html"; - - using (var file = new StreamWriter(filename, false)) - { - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine("

List of " + vDomName + " Warnings

"); - file.WriteLine(""); - for (int i = 0; i < _warningsList.Count; i++) - { - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - file.WriteLine(""); - } - file.WriteLine("
"); - file.WriteLine(i); - file.WriteLine(""); - file.WriteLine(_warningsList[i]); - file.WriteLine("
"); - file.WriteLine(""); - file.WriteLine(""); - } - } - } - - #endregion - - #region Converter - - //MAIN method to convert configuration file. - public override void Convert(bool convertNat) - { - string targetFileNameMain = _vendorFileName; - string targetFolderMain = _targetFolder; - - LDAP_Account_Unit = LDAPAccoutUnit.Trim(); - - bool isVDom = ConvertVDom(targetFolderMain, _fortiGateParser.FgCommandsList, convertNat); - - if (!isVDom) //if configration file does not conatin any VDOM - { - InitSystemInterfaces(_fortiGateParser.FgCommandsList); - ConvertConfig(targetFolderMain, targetFileNameMain, _fortiGateParser.FgCommandsList, convertNat); - } - else //if configuration file contains some VDOM then we can not count Errors, Warnings, Rules and NATs - { - _warningsConvertedPackage = -1; - _errorsConvertedPackage = -1; - _rulesInConvertedPackage = -1; - _rulesInNatLayer = -1; - CleanCheckPointObjectsLists(); - } - - RaiseConversionProgress(70, "Optimizing Firewall rulebase ..."); - RaiseConversionProgress(80, "Generating CLI scripts ..."); - - ChangeTargetFolder(targetFolderMain, targetFileNameMain); // chaning target folder path to folder contains config file - - if (_vDomNames.Count > 0) // create HTML files which contain links to each report - { - CreateCatalogObjects(); - CreateCatalogNATs(); - CreateCatalogPolicies(); - CreateCatalogErrors(); - CreateCatalogWarnings(); - } - - VendorHtmlFile = _vendorFilePath; - - ObjectsScriptFile = _targetFolder; - PolicyScriptFile = _targetFolder; - } - - //Convertint VDOMs to each VDOM and then Convert each VDOM as simple Configuration - public bool ConvertVDom(string targetFolderM, List fgCommandsList, bool convertNat) - { - RaiseConversionProgress(10, "Checking if vdom is present..."); - - bool isVDom = false; - - foreach (FgCommand fgCommand in fgCommandsList) - { - if (fgCommand.GetType() == typeof(FgCommand_Config)) - { - FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommand; - if (fgCommandConfig.ObjectName.Equals("vdom")) - { - isVDom = true; - - if (fgCommandConfig.SubCommandsList[0].GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandConfig.SubCommandsList[0]; - - string vdomName = fgCommandEdit.Table; - - _vDomNames.Add(vdomName); - - string targetFolderVDom = targetFolderM + "\\" + vdomName; - - System.IO.Directory.CreateDirectory(targetFolderVDom); - - ConvertConfig(targetFolderVDom, vdomName, fgCommandEdit.SubCommandsList, convertNat); - } - } - - if (fgCommandConfig.ObjectName.Equals("global") && isVDom) - { - InitSystemInterfaces(fgCommandConfig.SubCommandsList); - } - } - } - - return isVDom; - } - - //Init system Interfaces which is Global - public void InitSystemInterfaces(List fgCommandsList) - { - RaiseConversionProgress(20, "Init system interfaces..."); - - foreach (FgCommand fgCommand in fgCommandsList) - { - if (fgCommand.GetType() == typeof(FgCommand_Config)) - { - FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommand; - - if (fgCommandConfig.ObjectName.Equals("system interface")) - { - foreach (FgCommand fgCommandE in fgCommandConfig.SubCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("ip")) - { - string[] ip = fgCommandSet.Value.Split(' ').ToArray(); - - if (ip.Length > 0) - { - FgInterface fgInterface = new FgInterface(); - fgInterface.Name = fgCommandEdit.Table; - fgInterface.Ip = ip[0]; - fgInterface.Network = IPNetwork.Parse(ip[0], ip[1]).Network.ToString(); - fgInterface.Mask = ip[1]; - - _interfacesFgDict[fgInterface.Name] = fgInterface; - - CheckPoint_Host cpHost = new CheckPoint_Host(); - cpHost.Name = GetSafeName(fgCommandEdit.Table + "_intf"); - cpHost.IpAddress = ip[0]; - - List cpHostsList = null; - - if (_interfacesMapperFgCp.ContainsKey(fgCommandEdit.Table)) - { - cpHostsList = _interfacesMapperFgCp[fgCommandEdit.Table]; - } - else - { - cpHostsList = new List(); - } - - cpHostsList.Add(cpHost); - - _warningsList.Add(cpHost.Name + " new host object was created."); - - _interfacesMapperFgCp[fgCommandEdit.Table] = cpHostsList; - } - } - - if (fgCommandSet.Field.Equals("alias")) - { - if (!_intfAliasNamesMapper.ContainsKey(fgCommandEdit.Table)) - { - _intfAliasNamesMapper.Add(fgCommandEdit.Table, fgCommandSet.Value.Trim('"')); - } - } - } - } - } - } - break; - } - } - } - } - - //converting full configuration file or part which is related to VDOM - public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List fgCommandsList, bool convertNat) - { - RaiseConversionProgress(35, "Convert configuration..."); - RaiseConversionProgress(40, "Convert objects..."); - _cpObjects.Initialize(); // must be first!!! - CleanCheckPointObjectsLists(); // must be first!!! - - //change folder path for writing reports - //if it is VDOM then each report will be placed to own folder - //if it is w/o VDOM then report will be in the same folder as config file - ChangeTargetFolder(targetFolderNew, targetFileNameNew); - - if (!OptimizeConf) - { - foreach (string fgInterface in _interfacesMapperFgCp.Keys) - { - List cpHostsList = _interfacesMapperFgCp[fgInterface]; - foreach (CheckPoint_Host cpHost in cpHostsList) - { - AddCheckPointObject(cpHost); - } - } - } - - //Check if string of configuration section is related to FG Object - foreach (FgCommand fgCommand in fgCommandsList) - { - if (fgCommand.GetType() == typeof(FgCommand_Config)) - { - FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommand; - - if(fgCommandConfig.ObjectName.Equals("firewall address")) - { - Add_ConfigFirewallAddress(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("firewall vip")) - { - AddFirewallVip(fgCommandConfig.SubCommandsList); - } - else if(fgCommandConfig.ObjectName.Equals("firewall vipgrp")) - { - AddFirewallVipGroups(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("firewall addrgrp")) - { - Add_AddressGroups(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("firewall service custom")) - { - AddFirewallServices(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("firewall service group")) - { - AddFirewallServicesGroups(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("firewall schedule recurring")) - { - AddFirewallSchedule(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("firewall schedule onetime")) - { - AddFirewallScheduleOneTime(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("firewall schedule group")) - { - AddFirewallScheduleGroups(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("firewall ippool")) - { - AddFirewallIpPool(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("system zone")) - { - AddSystemZone(fgCommandConfig.SubCommandsList); - } - else if(fgCommandConfig.ObjectName.Equals("router static")) - { - AddRoutesStatic(fgCommandConfig.SubCommandsList); - } - else if(fgCommandConfig.ObjectName.Equals("router rip")) - { - CheckDynamicRoutesRip(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("router ripng")) - { - CheckDynamicRoutesRipNg(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("router ospf")) - { - CheckDynamicRoutesOspf(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("router bgp")) - { - CheckDynamicRoutesBgp(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("router isis")) - { - CheckDynamicRoutesIsis(fgCommandConfig.SubCommandsList); - } - else if (fgCommandConfig.ObjectName.Equals("user group") && ConvertUserConf) - { - AddUserGroup(fgCommandConfig.SubCommandsList); - } - } - } - - foreach (FgCommand fgCommand in fgCommandsList) - { - if (fgCommand.GetType() == typeof(FgCommand_Config)) - { - FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommand; - - if (fgCommandConfig.ObjectName.Equals("firewall policy")) - { - Add_Package(fgCommandConfig.SubCommandsList, convertNat); - } - } - } - - if (!OptimizeConf) //adding objects if Optimized configuration is not required - { - foreach (string key in _localMapperFgCp.Keys) - { - if (key.StartsWith(FG_PREFIX_KEY_user_group)) //already added because Access_Roles are added always - { - continue; - } - - List cpObjectsList = _localMapperFgCp[key]; - foreach (CheckPointObject cpObject in cpObjectsList) - { - AddCheckPointObject(cpObject); - } - } - } - - CreateObjectsScript(); - CreateObjectsHtml(); - - CreatePackagesScript(); - - CreateErrorsHtml(targetFileNameNew); - CreateWarningsHtml(targetFileNameNew); - - ExportNatLayerAsHtml(); - ExportPolicyPackagesAsHtmlConfig(); - - _warningsConvertedPackage = _warningsList.Count; - _errorsConvertedPackage = _errorsList.Count; - - // to clean; must be the last!!! - _cpObjects.ClearRepository(); - CleanSavedData(); - } - - //clean up all data in memmory to converting next VDOM configuration - public void CleanSavedData() - { - _errorsList.Clear(); - _warningsList.Clear(); - _localMapperFgCp.Clear(); - _vipPortForwardEnabledMapper.Clear(); - _localIntrazonesList.Clear(); - _localFgVipGrpsDict.Clear(); - _localFgZoneIntfDict.Clear(); - _localFgRoutesDict.Clear(); - _localFgDynRoutesEnable = false; - _timeCutterCounter = 0; - _timeGroupCutterCounter = 0; - } - - #endregion - - #region Parse Static Routes - - public void AddRoutesStatic(List fgCommandsList) - { - foreach(FgCommand fgCommandE in fgCommandsList) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - FgStaticRoute fgStaticRoute = new FgStaticRoute(); - - fgStaticRoute.Name = fgCommandEdit.Table.Trim('"').Trim(); - - fgStaticRoute.Network = "0.0.0.0"; - fgStaticRoute.Mask = "255.255.255.255"; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if(fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if(fgCommandSet.Field.Equals("dst")) - { - string[] destination = fgCommandSet.Value.Trim('"').Trim().Split(new string[] { " " }, StringSplitOptions.None).ToArray(); - - if(destination.Count() == 2) - { - fgStaticRoute.Network = destination[0]; - fgStaticRoute.Mask = destination[1]; - } - } - if (fgCommandSet.Field.Equals("gateway")) - { - fgStaticRoute.Gateway = fgCommandSet.Value.Trim('"').Trim(); - } - if(fgCommandSet.Field.Equals("device")) - { - fgStaticRoute.Device = fgCommandSet.Value.Trim('"').Trim(); - } - } - } - - List routesList = null; - - if (_localFgRoutesDict.ContainsKey(fgStaticRoute.Device)) - { - routesList = _localFgRoutesDict[fgStaticRoute.Device]; - } - else - { - routesList = new List(); - } - - routesList.Add(fgStaticRoute); - - _localFgRoutesDict[fgStaticRoute.Device] = routesList; - } - } - - #endregion - - #region Parse Dynamic Route - - public void CheckDynamicRoutesRip(List fgCommandsList) - { - foreach(FgCommand fgCommandC in fgCommandsList) - { - if(fgCommandC.GetType() == typeof(FgCommand_Config)) - { - FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommandC; - if(fgCommandConfig.ObjectName.Equals("interface")) - { - _localFgDynRoutesEnable = true; - } - } - } - } - - public void CheckDynamicRoutesRipNg(List fgCommandsList) - { - foreach (FgCommand fgCommandC in fgCommandsList) - { - if (fgCommandC.GetType() == typeof(FgCommand_Config)) - { - FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommandC; - if (fgCommandConfig.ObjectName.Equals("interface")) - { - _localFgDynRoutesEnable = true; - } - } - } - } - - public void CheckDynamicRoutesOspf(List fgCommandsList) - { - foreach(FgCommand fgCommandS in fgCommandsList) - { - if(fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - if(fgCommandSet.Field.Equals("router-id")) - { - _localFgDynRoutesEnable = true; - } - } - } - } - - public void CheckDynamicRoutesBgp(List fgCommandsList) - { - foreach (FgCommand fgCommandC in fgCommandsList) - { - if (fgCommandC.GetType() == typeof(FgCommand_Config)) - { - FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommandC; - if (fgCommandConfig.ObjectName.Equals("neighbor")) - { - _localFgDynRoutesEnable = true; - } - } - } - } - - public void CheckDynamicRoutesIsis(List fgCommandsList) - { - foreach (FgCommand fgCommandC in fgCommandsList) - { - if (fgCommandC.GetType() == typeof(FgCommand_Config)) - { - FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommandC; - if (fgCommandConfig.ObjectName.Equals("isis-interface")) - { - _localFgDynRoutesEnable = true; - } - } - } - } - - #endregion - - #region Convert Services - - public void AddFirewallServices(List fgCommandsList) - { - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - if (fgCommandEdit.Table.Equals("webproxy")) - { - _errorsList.Add("FortiGate Service of type webproxy was not created."); - continue; - } - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("tcp-portrange")) - { - if (fgCommandSet.Value.Contains(" ")) - { - string[] portRanges = fgCommandSet.Value.Split(' ').ToArray(); - foreach (string portRange in portRanges) - { - AddTcpService(portRange, fgCommandEdit.Table); - } - } - else - { - AddTcpService(fgCommandSet.Value, fgCommandEdit.Table); - } - } - - if (fgCommandSet.Field.Equals("udp-portrange")) - { - if (fgCommandSet.Value.Contains(" ")) - { - string[] portRanges = fgCommandSet.Value.Split(' ').ToArray(); - foreach (string portRange in portRanges) - { - AddUdpService(portRange, fgCommandEdit.Table); - } - } - else - { - AddUdpService(fgCommandSet.Value, fgCommandEdit.Table); - } - } - - if (fgCommandSet.Field.Equals("sctp-portrange")) - { - if (fgCommandSet.Value.Contains(" ")) - { - string[] portRanges = fgCommandSet.Value.Split(' ').ToArray(); - foreach (string portRange in portRanges) - { - AddSctpService(portRange, fgCommandEdit.Table); - } - } - else - { - AddSctpService(fgCommandSet.Value, fgCommandEdit.Table); - } - } - - if (fgCommandSet.Field.Equals("protocol") && fgCommandSet.Value.Equals("ICMP")) - { - AddIcmpService(fgCommandEdit); - break; - } - - if (fgCommandSet.Field.Equals("protocol") && fgCommandSet.Value.Equals("IP")) - { - AddOtherService(fgCommandEdit); - break; - } - } - } - } - } - } - - public void AddOtherService(FgCommand_Edit fgCommandEdit) - { - string protocolNumber = ""; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("protocol-number")) - { - protocolNumber = fgCommandSet.Value; - } - } - } - - if (protocolNumber.Equals("")) - return; - - bool isFound = false; - string cpServiceName = _cpObjects.GetKnownServiceName("OTHER_" + protocolNumber, out isFound); - - CheckPointObject cpObj; - - if (isFound) - { - cpObj = _cpObjects.GetObject(cpServiceName); - } - else - { - CheckPoint_OtherService cpOtherService = new CheckPoint_OtherService(); - cpOtherService.Name = GetSafeName(fgCommandEdit.Table); - cpOtherService.IpProtocol = protocolNumber; - - cpObj = cpOtherService; - } - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + fgCommandEdit.Table, cpObj); - } - - public void AddIcmpService(FgCommand_Edit fgCommandEdit) - { - string type = "99"; - string code = ""; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("icmptype")) - { - type = fgCommandSet.Value; - } - - if (fgCommandSet.Field.Equals("icmpcode")) - { - code = fgCommandSet.Value; - } - } - } - - bool isFound = false; - string cpServiceName = ""; - if (code.Equals("")) - { - cpServiceName = _cpObjects.GetKnownServiceName("ICMP_" + type, out isFound); - } - - CheckPointObject cpObj; - - if (isFound) - { - cpObj = _cpObjects.GetObject(cpServiceName); - } - else - { - CheckPoint_IcmpService cpIcmpService = new CheckPoint_IcmpService(); - cpIcmpService.Name = GetSafeName(fgCommandEdit.Table); - cpIcmpService.Type = type; - if (!code.Equals("")) - { - cpIcmpService.Code = code; - } - - cpObj = cpIcmpService; - } - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + fgCommandEdit.Table, cpObj); - } - - public void AddTcpService(string portRange, string nameEdit) - { - string dest; - string src; - if (portRange.Contains(":")) - { - dest = portRange.Split(':').ToArray()[0]; - src = portRange.Split(':').ToArray()[1]; - } - else - { - dest = portRange; - src = ""; - } - - if (src.StartsWith("0")) - { - src = "1" + src.Substring(1); - } - - if (dest.StartsWith("0")) - { - dest = "1" + dest.Substring(1); - } - - bool isFound; - string cpServiceName = _cpObjects.GetKnownServiceName("TCP_" + dest, out isFound); - - CheckPointObject cpObj; - - if (isFound) - { - cpObj = _cpObjects.GetObject(cpServiceName); - } - else - { - CheckPoint_TcpService cpTcpService = new CheckPoint_TcpService(); - cpTcpService.Name = GetSafeName(nameEdit); - cpTcpService.Port = dest; - if (!src.Equals("")) - { - cpTcpService.SourcePort = src; - } - - cpObj = cpTcpService; - } - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameEdit, cpObj); - } - - public void AddUdpService(string portRange, string nameEdit) - { - string dest; - string src; - if (portRange.Contains(":")) - { - dest = portRange.Split(':').ToArray()[0]; - src = portRange.Split(':').ToArray()[1]; - } - else - { - dest = portRange; - src = ""; - } - - if (src.StartsWith("0")) - { - src = "1" + src.Substring(1); - } - - if (dest.StartsWith("0")) - { - dest = "1" + dest.Substring(1); - } - - bool isFound; - string cpServiceName = _cpObjects.GetKnownServiceName("UDP_" + dest, out isFound); - - CheckPointObject cpObj; - - if (isFound) - { - cpObj = _cpObjects.GetObject(cpServiceName); - } - else - { - CheckPoint_UdpService cpUdpService = new CheckPoint_UdpService(); - cpUdpService.Name = GetSafeName(nameEdit); - cpUdpService.Port = dest; - if (!src.Equals("")) - { - cpUdpService.SourcePort = src; - } - - cpObj = cpUdpService; - } - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameEdit, cpObj); - } - - public void AddSctpService(string portRange, string nameEdit) - { - string dest; - string src; - if (portRange.Contains(":")) - { - dest = portRange.Split(':').ToArray()[0]; - src = portRange.Split(':').ToArray()[1]; - } - else - { - dest = portRange; - src = ""; - } - - if (src.StartsWith("0")) - { - src = "1" + src.Substring(1); - } - - if (dest.StartsWith("0")) - { - dest = "1" + dest.Substring(1); - } - - bool isFound; - string cpServiceName = _cpObjects.GetKnownServiceName("SCTP_" + dest, out isFound); - - CheckPointObject cpObj; - - if (isFound) - { - cpObj = _cpObjects.GetObject(cpServiceName); - } - else - { - CheckPoint_SctpService cpSctpService = new CheckPoint_SctpService(); - cpSctpService.Name = GetSafeName(nameEdit); - cpSctpService.Port = dest; - if (!src.Equals("")) - { - cpSctpService.SourcePort = src; - } - - cpObj = cpSctpService; - } - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameEdit, cpObj); - } - - #endregion - - #region Convert Services Groups - - public void AddFirewallServicesGroups(List fgCommandsList) - { - Dictionary checkingSrvGrps = new Dictionary(); - - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - CheckPoint_ServiceGroup cpServiceGroup = new CheckPoint_ServiceGroup(); - cpServiceGroup.Name = GetSafeName(fgCommandEdit.Table); - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - if (fgCommandSet.Field.Equals("member")) - { - string[] members = fgCommandSet.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - foreach (string member in members) - { - string memberC = member.Trim('"'); - - cpServiceGroup.Members.Add(memberC); - } - } - - if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) - { - cpServiceGroup.Comments = fgCommandSet.Value.Trim('"'); - } - } - } - - checkingSrvGrps.Add(fgCommandEdit.Table, cpServiceGroup); - } - } - - while (checkingSrvGrps.Keys.Count > 0) - { - AddFirewallServicesGroupsRecurs(checkingSrvGrps.Keys.First(), checkingSrvGrps); - } - } - - public void AddFirewallServicesGroupsRecurs(string cpSrvGrpName, Dictionary checkingSrvGrps) - { - List errorsList = new List(); - - CheckPoint_ServiceGroup cpSrvGrp = checkingSrvGrps[cpSrvGrpName]; - - checkingSrvGrps.Remove(cpSrvGrpName); - - CheckPoint_ServiceGroup cpSrvGrpAdd = new CheckPoint_ServiceGroup(); - - cpSrvGrpAdd.Name = cpSrvGrp.Name; - - for (int i = 0; i < cpSrvGrp.Members.Count; i++) - { - string member = cpSrvGrp.Members[i]; - - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_service_custom + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_service_custom + member]; - - if (list.Count > 0) - { - cpSrvGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_service_group + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_service_group + member]; - if (list.Count > 0) - { - cpSrvGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - else if (checkingSrvGrps.ContainsKey(member)) - { - AddFirewallServicesGroupsRecurs(member, checkingSrvGrps); - - cpSrvGrpAdd.Members.Add(member); - } - else - { - errorsList.Add(cpSrvGrpAdd.Name + " service group " + - "can not been converted becuase it contains non-existing member: " + member); - } - - if (checkingSrvGrps.ContainsKey(member)) - { - checkingSrvGrps.Remove(member); - } - } - - if (errorsList.Count == 0) - { - //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_group + cpSrvGrpAdd.Name, cpSrvGrpAdd); - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_group + cpSrvGrpName, cpSrvGrpAdd); - } - else - { - _errorsList.AddRange(errorsList); - } - } - - #endregion - - #region Convert Schedules - - public void AddFirewallSchedule(List fgCommandsList) - { - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - if (fgCommandEdit.Table.Equals("always")) - { - if (!_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_schedule_recurring + "always")) - { - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_recurring + "always", _cpObjects.GetObject(CheckPointObject.Any)); - } - continue; - } - - CheckPoint_Time cpTime = new CheckPoint_Time(); - - cpTime.Name = fgCommandEdit.Table; - - cpTime.StartNow = true; - cpTime.EndNever = true; - - string timeStart = null; - string timeEnd = null; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("day")) - { - List cpDays = new List(); - string[] days = fgCommandSet.Value.Split(' '); - foreach (string day in days) - { - switch (day) - { - case "sunday": - cpDays.Add(CheckPoint_Time.Weekdays.Sun); - break; - case "monday": - cpDays.Add(CheckPoint_Time.Weekdays.Mon); - break; - case "tuesday": - cpDays.Add(CheckPoint_Time.Weekdays.Tue); - break; - case "wednesday": - cpDays.Add(CheckPoint_Time.Weekdays.Wed); - break; - case "thursday": - cpDays.Add(CheckPoint_Time.Weekdays.Thu); - break; - case "friday": - cpDays.Add(CheckPoint_Time.Weekdays.Fri); - break; - case "saturday": - cpDays.Add(CheckPoint_Time.Weekdays.Sat); - break; - } - } - cpTime.RecurrenceWeekdays = cpDays; - } - - if (fgCommandSet.Field.Equals("start")) - { - timeStart = fgCommandSet.Value; - } - - if (fgCommandSet.Field.Equals("end")) - { - timeEnd = fgCommandSet.Value; - } - - if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) - { - cpTime.Comments = fgCommandSet.Value.Trim('"'); - } - } - } - - //... - if (timeStart != null || timeEnd != null) - { - if (timeStart == null) - { - timeStart = "00:00"; - } - if (timeEnd == null) - { - timeEnd = "00:00"; - } - if (TimeSpan.Parse(timeStart) <= TimeSpan.Parse(timeEnd)) - { - cpTime.HoursRangesEnabled_1 = true; - cpTime.HoursRangesFrom_1 = timeStart; - cpTime.HoursRangesTo_1 = timeEnd; - } - else - { - cpTime.HoursRangesEnabled_1 = true; - cpTime.HoursRangesFrom_1 = timeStart; - cpTime.HoursRangesTo_1 = "23:59"; - - cpTime.HoursRangesEnabled_2 = true; - cpTime.HoursRangesFrom_2 = "00:00"; - cpTime.HoursRangesTo_2 = timeEnd; - } - } - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_recurring + fgCommandEdit.Table, cpTime); - } - } - } - - public void AddFirewallScheduleOneTime(List fgCommandsList) - { - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - CheckPoint_Time cpTime = new CheckPoint_Time(); - - cpTime.Name = fgCommandEdit.Table; - - cpTime.StartNow = false; - cpTime.EndNever = false; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("start")) - { - DateTime date = DateTime.ParseExact(fgCommandSet.Value.Trim('"'), "HH:mm yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); - - cpTime.StartDate = date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture); - cpTime.StartTime = date.ToString("HH:mm"); - } - - if (fgCommandSet.Field.Equals("end")) - { - DateTime date = DateTime.ParseExact(fgCommandSet.Value.Trim('"'), "HH:mm yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); - - cpTime.EndDate = date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture); - cpTime.EndTime = date.ToString("HH:mm"); - } - - if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) - { - cpTime.Comments = fgCommandSet.Value.Trim('"'); - } - } - } - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_onetime + fgCommandEdit.Table, cpTime); - } - } - } - - #endregion - - #region Convert Schedules Groups - - public void AddFirewallScheduleGroups(List fgCommandsList) - { - Dictionary checkingTimeGrps = new Dictionary(); - - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - CheckPoint_TimeGroup cpTimeGroup = new CheckPoint_TimeGroup(); - cpTimeGroup.Name = GetSafeName(fgCommandEdit.Table); - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - if (fgCommandSet.Field.Equals("member")) - { - string[] members = fgCommandSet.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - foreach (string member in members) - { - string memberC = member.Trim('"'); - cpTimeGroup.Members.Add(memberC); - } - } - - if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) - { - cpTimeGroup.Comments = fgCommandSet.Value.Trim('"'); - } - } - } - - checkingTimeGrps.Add(fgCommandEdit.Table, cpTimeGroup); - } - } - - while (checkingTimeGrps.Keys.Count > 0) - { - AddFirewallScheduleGroupsRecurs(checkingTimeGrps.Keys.First(), checkingTimeGrps); - } - } - - public void AddFirewallScheduleGroupsRecurs(string cpTimeGrpName, Dictionary checkingTimeGrps) - { - List errorsList = new List(); - - CheckPoint_TimeGroup cpTimeGrp = checkingTimeGrps[cpTimeGrpName]; - - checkingTimeGrps.Remove(cpTimeGrpName); - - CheckPoint_TimeGroup cpTimeGrpAdd = new CheckPoint_TimeGroup(); - - cpTimeGrpAdd.Name = cpTimeGrp.Name; - - for (int i = 0; i < cpTimeGrp.Members.Count; i++) - { - string member = cpTimeGrp.Members[i]; - - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_schedule_recurring + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_schedule_recurring + member]; - if (list.Count > 0) - { - cpTimeGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_schedule_onetime + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_schedule_onetime + member]; - if (list.Count > 0) - { - cpTimeGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_schedule_group + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_schedule_group + member]; - if (list.Count > 0) - { - cpTimeGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - else if (checkingTimeGrps.ContainsKey(member)) - { - AddFirewallScheduleGroupsRecurs(member, checkingTimeGrps); - - cpTimeGrpAdd.Members.Add(member); - } - else - { - errorsList.Add(cpTimeGrpAdd.Name + " schedule group " + - "can not been converted becuase it contains non-existing member: " + member); - } - - if (checkingTimeGrps.ContainsKey(member)) - { - checkingTimeGrps.Remove(member); - } - } - - if (errorsList.Count == 0) - { - //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_group + cpTimeGrp.Name, cpTimeGrpAdd); - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_group + cpTimeGrpName, cpTimeGrpAdd); - } - else - { - _errorsList.AddRange(errorsList); - } - } - - #endregion - - #region Convert IpPool - - public void AddFirewallIpPool(List fgCommandsList) - { - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - CheckPoint_Range cpRange = new CheckPoint_Range(); - cpRange.Name = GetSafeName(fgCommandEdit.Table); - cpRange.RangeFrom = ""; - cpRange.RangeTo = ""; - - CheckPoint_Range cpRangeSrc = new CheckPoint_Range(); - cpRangeSrc.Name = GetSafeName(fgCommandEdit.Table); - cpRangeSrc.RangeFrom = ""; - cpRangeSrc.RangeTo = ""; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - switch (fgCommandSet.Field) - { - case "startip": - cpRange.RangeFrom = fgCommandSet.Value; - break; - case "endip": - cpRange.RangeTo = fgCommandSet.Value; - break; - case "source-startip": - cpRangeSrc.RangeFrom = fgCommandSet.Value; - break; - case "source-endip": - cpRangeSrc.RangeTo = fgCommandSet.Value; - break; - } - } - } - - if (!cpRange.RangeFrom.Equals("") && !cpRange.RangeTo.Equals("")) - { - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_ippool + fgCommandEdit.Table, cpRange); - } - - if (!cpRangeSrc.RangeFrom.Equals("") && !cpRangeSrc.RangeTo.Equals("")) - { - //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_ippool_source + fgCommandEdit.Table, cpRangeSrc); - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_ippool + fgCommandEdit.Table, cpRangeSrc); - } - } - } - } - - #endregion - - #region Convert System Zone - - public void AddSystemZone(List fgCommandsList) - { - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - CheckPoint_Zone cpZone = new CheckPoint_Zone(); - cpZone.Name = GetSafeName(fgCommandEdit.Table); - - bool isIntraZone = false; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("intrazone") && fgCommandSet.Value.Equals("allow")) - { - isIntraZone = true; - } - - if (fgCommandSet.Field.Equals("interface")) - { - string[] zoneInterfaces = fgCommandSet.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - - _localFgZoneIntfDict[fgCommandEdit.Table] = zoneInterfaces.ToList(); - - foreach (string zoneInterface in zoneInterfaces) - { - if(_interfacesMapperFgCp.ContainsKey(zoneInterface)) - { - List cpObjsList = _interfacesMapperFgCp[zoneInterface]; - foreach (CheckPoint_Host cpObj in cpObjsList) - { - AddCpObjectToLocalMapper(FG_PREFIX_KEY_system_zone_host + fgCommandEdit.Table, cpObj); - } - } - } - } - } - } - - if (isIntraZone) - { - _localIntrazonesList.Add(cpZone); - } - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_system_zone + fgCommandEdit.Table, cpZone); - } - } - } - - #endregion - - #region Convert Users Groups - - public void AddUserGroup(List fgCommandsList) - { - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - bool isFSSOService = false; - - string membersStr = ""; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("group-type") && fgCommandSet.Value.Equals("fsso-service")) - { - isFSSOService = true; - } - - if (fgCommandSet.Field.Equals("member")) - { - membersStr = fgCommandSet.Value.Trim('"'); - } - } - } - - if (isFSSOService) - { - CheckPoint_AccessRole cpAccessRole = new CheckPoint_AccessRole(); - cpAccessRole.Name = GetSafeName(fgCommandEdit.Table); - - string[] members = membersStr.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - foreach (string member in members) - { - if (string.IsNullOrWhiteSpace(member)) - continue; - - if (member.Contains(",")) - { - List values = new List(); - member.Split(new string[] { "," }, StringSplitOptions.None).ToList().ForEach(x => values.Add(x.Trim().Substring(x.IndexOf("=") + 1))); - - AccessRoleUser arUser = new AccessRoleUser(); - arUser.Name = values[0]; - arUser.BaseDn = member; - - cpAccessRole.Users.Add(arUser); - } - else if (member.Contains("\\")) - { - AccessRoleUser arUser = new AccessRoleUser(); - arUser.Name = member.Substring(member.IndexOf("\\") + 1); - - cpAccessRole.Users.Add(arUser); - } - else - { - AccessRoleUser arUser = new AccessRoleUser(); - arUser.Name = member; - - cpAccessRole.Users.Add(arUser); - } - } - - if (cpAccessRole.Users.Count > 0) - { - AddCpObjectToLocalMapper(FG_PREFIX_KEY_user_group + fgCommandEdit.Table, cpAccessRole); - AddCheckPointObject(cpAccessRole); - } - } - } - } - } - - #endregion - - #region Convert Addresses - - public void Add_ConfigFirewallAddress(List fgCommandsList) - { - foreach(FgCommand fgCommand in fgCommandsList) - { - if (fgCommand.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommand; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - CheckPointObject cpObject = null; - - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("type")) - { - switch (fgCommandSet.Value) - { - case "fqdn": - cpObject = Add_Domain(fgCommandEdit, false); - break; - case "wildcard-fqdn": - cpObject = Add_Domain(fgCommandEdit, true); - break; - case "iprange": - cpObject = Add_IpRange(fgCommandEdit); - break; - } - } - else if (fgCommandSet.Field.Equals("subnet")) - { - cpObject = Add_Subnet(fgCommandEdit); - } - - if (cpObject != null) - { - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_address + fgCommandEdit.Table, cpObject); - } - } - } - } - } - } - - public CheckPointObject Add_Domain(FgCommand_Edit fgCommandEdit, bool isSubDomain) - { - CheckPoint_Domain cpDomain = new CheckPoint_Domain(); - cpDomain.IsSubDomain = isSubDomain; - - string comment = ""; - - foreach (FgCommand fgCommand in fgCommandEdit.SubCommandsList) - { - if (fgCommand.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommand; - if (fgCommandSet.Field.Equals("fqdn")) - { - cpDomain.Name = GetSafeName("." + fgCommandSet.Value); - } - else if (fgCommandSet.Field.Equals("wildcard-fqdn")) - { - int indStar = fgCommandSet.Value.Trim('"').LastIndexOf("*"); - - string subDomain = fgCommandSet.Value.Trim('"').Substring(indStar + 1); - if (!subDomain.StartsWith(".")) - { - subDomain = "." + subDomain; - } - - cpDomain.Name = GetSafeName(subDomain); - } - - if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) - { - comment = fgCommandSet.Value.Trim('"'); - } - } - } - - cpDomain.Comments = comment; - - return cpDomain; - } - - public CheckPointObject Add_IpRange(FgCommand_Edit fgCommandEdit) - { - CheckPoint_Range cpRange = new CheckPoint_Range(); - cpRange.Name = GetSafeName(fgCommandEdit.Table); - - string comment = ""; - - foreach (FgCommand fgCommand in fgCommandEdit.SubCommandsList) - { - if (fgCommand.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommand; - if (fgCommandSet.Field.Equals("start-ip")) - { - cpRange.RangeFrom = fgCommandSet.Value; - } - if (fgCommandSet.Field.Equals("end-ip")) - { - cpRange.RangeTo = fgCommandSet.Value; - } - if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) - { - comment = fgCommandSet.Value.Trim('"'); - } - } - } - - cpRange.Comments = comment; - - return cpRange; - } - - public CheckPointObject Add_Subnet(FgCommand_Edit fgCommandEdit) - { - CheckPointObject cpObjectRet = null; - string comment = ""; - - foreach (FgCommand fgCommand in fgCommandEdit.SubCommandsList) - { - if (fgCommand.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommand; - if (fgCommandSet.Field.Equals("subnet")) - { - string ipAddress = fgCommandSet.Value.Substring(0, fgCommandSet.Value.IndexOf(" ")).Trim(); - string ipMask = fgCommandSet.Value.Substring(fgCommandSet.Value.IndexOf(" ")).Trim(); - - if (ipMask.Equals("255.255.255.255")) - { - CheckPoint_Host cpHost = new CheckPoint_Host(); - cpHost.Name = GetSafeName(fgCommandEdit.Table); - cpHost.IpAddress = ipAddress; - cpObjectRet = cpHost; - } - else - { - CheckPoint_Network cpNetwork = new CheckPoint_Network(); - cpNetwork.Name = GetSafeName(fgCommandEdit.Table); - cpNetwork.Subnet = ipAddress; - cpNetwork.Netmask = ipMask; - cpObjectRet = cpNetwork; - } - } - if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) - { - comment = fgCommandSet.Value.Trim('"'); - } - } - } - - cpObjectRet.Comments = comment; - - return cpObjectRet; - } - - #endregion - - #region Convert VIP - - public void AddFirewallVip(List fgCommandsList) - { - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - bool isPortForwardEnabled = false; - string protocol = "tcp"; - - string portExt = ""; - string portMap = ""; - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("extip")) - { - string[] addressesArray = fgCommandSet.Value.Trim('"').Split('-').ToArray(); - if (addressesArray.Length == 1) - { - CheckPoint_Host cpHost = new CheckPoint_Host(); - cpHost.Name = GetSafeName(fgCommandEdit.Table + "_vip_extip"); - cpHost.IpAddress = addressesArray[0]; - - _warningsList.Add(cpHost.Name + " new host was created from " + fgCommandEdit.Table + " VIP (ext-ip)."); - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_extip + fgCommandEdit.Table, cpHost); - } - else - { - CheckPoint_Range cpRange = new CheckPoint_Range(); - cpRange.Name = GetSafeName(fgCommandEdit.Table + "_vip_extip"); - - _warningsList.Add(cpRange.Name + " new range was created from " + fgCommandEdit.Table + " VIP (ext-ip)."); - - cpRange.RangeFrom = addressesArray[0]; - cpRange.RangeTo = addressesArray[1]; - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_extip + fgCommandEdit.Table, cpRange); - } - } - - if (fgCommandSet.Field.Equals("mappedip")) - { - string[] addressesArray = fgCommandSet.Value.Trim('"').Split('-').ToArray(); - if (addressesArray.Length == 1) - { - CheckPoint_Host cpHost = new CheckPoint_Host(); - cpHost.Name = GetSafeName(fgCommandEdit.Table + "_vip_mappedip"); - - _warningsList.Add(cpHost.Name + " new host was created from " + fgCommandEdit.Table + " VIP (mapped-ip)."); - - cpHost.IpAddress = addressesArray[0]; - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_mappedip + fgCommandEdit.Table, cpHost); - } - else - { - CheckPoint_Range cpRange = new CheckPoint_Range(); - cpRange.Name = GetSafeName(fgCommandEdit.Table + "_vip_mappedip"); - - _warningsList.Add(cpRange.Name + " new range was created from " + fgCommandEdit.Table + " VIP (mapped-ip)."); - - cpRange.RangeFrom = addressesArray[0]; - cpRange.RangeTo = addressesArray[1]; - - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_mappedip + fgCommandEdit.Table, cpRange); - } - } - - if (fgCommandSet.Field.Equals("portforward") && fgCommandSet.Value.Equals("enable")) - { - isPortForwardEnabled = true; - _vipPortForwardEnabledMapper[fgCommandEdit.Table] = true; - } - - if (fgCommandSet.Field.Equals("extport")) - { - portExt = fgCommandSet.Value; - } - - if (fgCommandSet.Field.Equals("mappedport")) - { - portMap = fgCommandSet.Value; - } - - if (fgCommandSet.Field.Equals("protocol")) - { - protocol = fgCommandSet.Value; - } - } - } - - - if (isPortForwardEnabled) - { - string nameVipE = "VIPe_" + fgCommandEdit.Table; - string nameVipM = "VIPm_" + fgCommandEdit.Table; - switch (protocol) - { - case "tcp": - if (!portExt.Equals("")) - { - AddTcpService(portExt, nameVipE); - } - if (!portMap.Equals("")) - { - AddTcpService(portMap, nameVipM); - } - break; - case "udp": - if (!portExt.Equals("")) - { - AddUdpService(portExt, nameVipE); - } - if (!portMap.Equals("")) - { - AddUdpService(portMap, nameVipM); - } - break; - case "sctp": - if (!portExt.Equals("")) - { - AddSctpService(portExt, nameVipE); - } - if (!portMap.Equals("")) - { - AddSctpService(portMap, nameVipM); - } - 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; - } - } - } - } - } - - #endregion - - #region Convert VIP Groups - - public void AddFirewallVipGroups(List fgCommandsList) - { - Dictionary checkingVipGrps = new Dictionary(); - - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - CheckPoint_NetworkGroup cpVipGroup = new CheckPoint_NetworkGroup(); - cpVipGroup.Name = GetSafeName(fgCommandEdit.Table); - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - if (fgCommandSet.Field.Equals("member")) - { - string[] members = fgCommandSet.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - foreach (string member in members) - { - string memberC = member.Trim('"'); - cpVipGroup.Members.Add(memberC); - } - } - - if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) - { - cpVipGroup.Comments = fgCommandSet.Value.Trim('"'); - } - } - } - - checkingVipGrps.Add(fgCommandEdit.Table, cpVipGroup); - - _localFgVipGrpsDict[fgCommandEdit.Table] = cpVipGroup.Members; - } - } - - while (checkingVipGrps.Keys.Count > 0) - { - Add_VipGroupsRecurs(checkingVipGrps.Keys.First(), checkingVipGrps); - } - } - - public void Add_VipGroupsRecurs(string cpVipGrpName, Dictionary checkingVipGrps) - { - List errorsList = new List(); - - CheckPoint_NetworkGroup cpVipGrp = checkingVipGrps[cpVipGrpName]; - - checkingVipGrps.Remove(cpVipGrpName); - - CheckPoint_NetworkGroup cpVipGrpAdd = new CheckPoint_NetworkGroup(); - - cpVipGrpAdd.Name = cpVipGrp.Name; - - for (int i = 0; i < cpVipGrp.Members.Count; i++) - { - string member = cpVipGrp.Members[i]; - - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + member) || _localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + member)) - { - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_vip_extip + member]; - - if (list.Count > 0) - { - cpVipGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_vip_mappedip + member]; - - if (list.Count > 0) - { - cpVipGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - } - else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_grp + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_vip_grp + member]; - - if (list.Count > 0) - { - cpVipGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - else if (checkingVipGrps.ContainsKey(member)) - { - Add_VipGroupsRecurs(member, checkingVipGrps); - - cpVipGrpAdd.Members.Add(member); - } - else - { - errorsList.Add(cpVipGrpAdd.Name + " network group " + - "can not been converted becuase it contains non-existing member: " + member); - } - - if (checkingVipGrps.ContainsKey(member)) - { - checkingVipGrps.Remove(member); - } - } - - if (errorsList.Count == 0) - { - //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_grp + cpVipGrp.Name, cpVipGrpAdd); - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_grp + cpVipGrpName, cpVipGrpAdd); - } - else - { - _errorsList.AddRange(errorsList); - } - } - - #endregion - - #region Convert Addresses Groups - - public void Add_AddressGroups(List fgCommandsList) - { - Dictionary checkingAddrGrps = new Dictionary(); - - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; - - CheckPoint_NetworkGroup cpAddrGroup = new CheckPoint_NetworkGroup(); - cpAddrGroup.Name = GetSafeName(fgCommandEdit.Table); - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - if (fgCommandSet.Field.Equals("member")) - { - string[] members = fgCommandSet.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - foreach (string member in members) - { - string memberC = member.Trim('"'); - cpAddrGroup.Members.Add(memberC); - } - } - - if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) - { - cpAddrGroup.Comments = fgCommandSet.Value.Trim('"'); - } - } - } - - checkingAddrGrps.Add(fgCommandEdit.Table, cpAddrGroup); - } - } - - while (checkingAddrGrps.Keys.Count > 0) - { - Add_AddressGroupsRecurs(checkingAddrGrps.Keys.First(), checkingAddrGrps); - } - } - - public void Add_AddressGroupsRecurs(string cpAddrGrpName, Dictionary checkingAddrGrps) - { - List errorsList = new List(); - - CheckPoint_NetworkGroup cpAddrGrp = checkingAddrGrps[cpAddrGrpName]; - - checkingAddrGrps.Remove(cpAddrGrpName); - - CheckPoint_NetworkGroup cpAddrGrpAdd = new CheckPoint_NetworkGroup(); - - cpAddrGrpAdd.Name = cpAddrGrp.Name; - - for (int i = 0; i < cpAddrGrp.Members.Count; i++) - { - string member = cpAddrGrp.Members[i]; - - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_address + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_address + member]; - - if (list.Count > 0) - { - cpAddrGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_addrgrp + member)) - { - List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_addrgrp + member]; - - if (list.Count > 0) - { - cpAddrGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); - } - } - else if (checkingAddrGrps.ContainsKey(member)) - { - Add_AddressGroupsRecurs(member, checkingAddrGrps); - - cpAddrGrpAdd.Members.Add(member); - } - else - { - errorsList.Add(cpAddrGrpAdd.Name + " address group " + - "can not been converted becuase it contains non-existing member: " + member); - } - - if (checkingAddrGrps.ContainsKey(member)) - { - checkingAddrGrps.Remove(member); - } - } - - if (errorsList.Count == 0) - { - //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_addrgrp + cpAddrGrp.Name, cpAddrGrpAdd); - AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_addrgrp + cpAddrGrpName, cpAddrGrpAdd); - } - else - { - _errorsList.AddRange(errorsList); - } - } - - #endregion - - #region Convert Policy Rules && prepare for NATs converting - - public void Add_Package(List fgCommandsList, bool convertNat) - { - RaiseConversionProgress(70, "Convert policy..."); - - var cpPackage = new CheckPoint_Package(); - cpPackage.Name = _policyPackageName; - - Add_ParentLayer(cpPackage, fgCommandsList, convertNat); - - AddCheckPointObject(cpPackage); - } - - public void Add_ParentLayer(CheckPoint_Package package, List fgCommandsList, bool convertNat) - { - package.ParentLayer.Name = package.NameOfAccessLayer; - - List rootRulesList = new List(); - Dictionary rootLayersMap = new Dictionary(); - Dictionary extraZonesMap = new Dictionary(); - List extraZonesWarnMsgsList = new List(); - List realRulesList = new List(); //is used if 'plain' policy should be converted - - //add main rule from Intrazone - //add sub policy layer - //add rule from Intrazone - - foreach(CheckPoint_Zone cpZoneIntra in _localIntrazonesList) - { - string warnMessage = CheckZoneForReservedWords(cpZoneIntra); - - if(warnMessage != null) - { - _warningsList.Add(warnMessage); - } - - AddCheckPointObject(cpZoneIntra); - - CheckPoint_Rule cpRuleZone = new CheckPoint_Rule(); - cpRuleZone.Name = GetSafeName(cpZoneIntra.Name); //"Intrazone_" + cpZoneIntra.Name; - cpRuleZone.Layer = package.NameOfAccessLayer; - cpRuleZone.Source.Add(cpZoneIntra); - cpRuleZone.Destination.Add(cpZoneIntra); - cpRuleZone.Action = CheckPoint_Rule.ActionType.SubPolicy; - cpRuleZone.Track = CheckPoint_Rule.TrackTypes.Log; - cpRuleZone.Time.Add(_cpObjects.GetObject(CheckPointObject.Any)); - cpRuleZone.Service.Add(_cpObjects.GetObject(CheckPointObject.Any)); - cpRuleZone.SubPolicyName = GetSafeName(cpZoneIntra.Name + "_internal"); - - package.ParentLayer.Rules.Add(cpRuleZone); - - CheckPoint_Layer cpRuleLayer = new CheckPoint_Layer(); - cpRuleLayer.Name = cpRuleZone.SubPolicyName; - - package.SubPolicies.Add(cpRuleLayer); - - CheckPoint_Rule cpSubRuleZone = new CheckPoint_Rule(); - cpSubRuleZone.Name = ""; //"intrazone_sr_" + cpZoneIntra.Name; - cpSubRuleZone.Layer = cpRuleLayer.Name; - cpSubRuleZone.Source.Add(_cpObjects.GetObject(CheckPointObject.Any)); - cpSubRuleZone.Destination.Add(_cpObjects.GetObject(CheckPointObject.Any)); - cpSubRuleZone.Action = CheckPoint_Rule.ActionType.Accept; - cpSubRuleZone.Track = CheckPoint_Rule.TrackTypes.Log; - cpSubRuleZone.Time.Add(_cpObjects.GetObject(CheckPointObject.Any)); - cpSubRuleZone.Service.Add(_cpObjects.GetObject(CheckPointObject.Any)); - - cpRuleLayer.Rules.Add(cpSubRuleZone); - } - - bool isIntfContainsAny = false; - - foreach (FgCommand fgCommandE in fgCommandsList) - { - if (fgCommandE.GetType() == typeof(FgCommand_Edit)) - { - FgCommand_Edit fgCommand_Edit = (FgCommand_Edit)fgCommandE; - - var cpRule = new CheckPoint_Rule(); - - cpRule.ConversionComments = "Matched rule " + fgCommand_Edit.Table; - - string[] fgSrcIntfs = new string[]{}; - string[] fgDstIntfs = new string[]{}; - - cpRule.Track = CheckPoint_Rule.TrackTypes.Log; - - List errorsList = new List(); - - bool isNatEnabled = false; - bool isIpPoolEnabled = false; - - List fgDstAddrList = new List(); - - List cpUsersGroupsList = new List(); - - foreach (FgCommand fgCommandS in fgCommand_Edit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommand_Set = (FgCommand_Set)fgCommandS; - - if(fgCommand_Set.Field.Equals("name")) - { - cpRule.Name = GetSafeName(fgCommand_Set.Value); - } - - if (fgCommand_Set.Field.Equals("action") && fgCommand_Set.Value.Equals("accept") && (cpRule.Action == CheckPoint_Rule.ActionType.Drop)) - { - cpRule.Action = CheckPoint_Rule.ActionType.Accept; - } - - if (fgCommand_Set.Field.Equals("status") && fgCommand_Set.Value.Trim().ToLower().Equals("disable")) - { - cpRule.Enabled = false; - } - - if (fgCommand_Set.Field.Equals("learning-mode") && fgCommand_Set.Value.Equals("enable")) - { - 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) - { - isIntfContainsAny = true; - } - } - - if (fgCommand_Set.Field.Equals("dstintf")) - { - fgDstIntfs = fgCommand_Set.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - - if (Array.IndexOf(fgDstIntfs.Select(s => s.ToLowerInvariant()).ToArray(), "any") > -1) - { - isIntfContainsAny = true; - } - } - - if (fgCommand_Set.Field.Equals("srcaddr")) - { - if (fgCommand_Set.Value.Equals("all")) - { - cpRule.Source.Add(_cpObjects.GetObject(CheckPointObject.Any)); - } - else - { - List list = fgCommand_Set.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToList(); - foreach (string str in list) - { - string name = str.Trim('"'); - - bool isAdded = false; - - string[] fgPrefixes = new string[] - { - FG_PREFIX_KEY_firewall_address, - FG_PREFIX_KEY_firewall_addrgrp, - FG_PREFIX_KEY_firewall_vip_extip, - FG_PREFIX_KEY_firewall_vip_grp - }; - - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + name)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + name]; - - foreach (CheckPointObject cpObj in cpObjsList) - { - cpRule.Source.Add(cpObj); - isAdded = true; - if (OptimizeConf) - { - AddCheckPointObject(cpObj); - } - } - } - } - - if(!isAdded) - { - errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'srcaddr' field with non-existing reference to: " + name + " and was not created."); - } - } - } - } - - if (fgCommand_Set.Field.Equals("dstaddr")) - { - if (fgCommand_Set.Value.Equals("all")) - { - cpRule.Destination.Add(_cpObjects.GetObject(CheckPointObject.Any)); - fgDstAddrList.Add("all"); - } - else - { - List list = fgCommand_Set.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToList(); - foreach (string str in list) - { - string name = str.Trim('"'); - - bool isAdded = false; - - string[] fgPrefixes = new string[] - { - FG_PREFIX_KEY_firewall_address, - FG_PREFIX_KEY_firewall_addrgrp, - FG_PREFIX_KEY_firewall_vip_extip, - FG_PREFIX_KEY_firewall_vip_grp - }; - - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + name)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + name]; - - foreach (CheckPointObject cpObj in cpObjsList) - { - cpRule.Destination.Add(cpObj); - isAdded = true; - if (OptimizeConf) - { - AddCheckPointObject(cpObj); - } - } - } - } - - if(!isAdded) - { - errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'dstaddr' field with non-existing reference to: " + name + " and was not created."); - } - - fgDstAddrList.Add(name); - } - } - } - - if (fgCommand_Set.Field.Equals("internet-service") && fgCommand_Set.Value.Equals("enable")) - { - errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'internet-service' field as destination" + " and was not created."); - } - - if (fgCommand_Set.Field.Equals("internet-service-id")) - { - errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'internet-service' field with " + fgCommand_Set.Value + " id" + " and was not created."); - } - if (fgCommand_Set.Field.Equals("schedule")) - { - string fgScheduleRule = fgCommand_Set.Value.Trim('"'); - - bool isAdded = false; - - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_schedule_recurring, FG_PREFIX_KEY_firewall_schedule_onetime, FG_PREFIX_KEY_firewall_schedule_group }; - - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgScheduleRule)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgScheduleRule]; - foreach(CheckPointObject cpObj in cpObjsList) { - cpRule.Time.Add(cpObj); - if (OptimizeConf) - { - AddCheckPointObject(cpObj); - } - isAdded = true; - } - } - } - - if(!isAdded) - { - errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'schedule' field with unrecognized value: " + fgScheduleRule + " and was not created"); - } - } - if (fgCommand_Set.Field.Equals("service")) - { - string[] fgServicesNames = fgCommand_Set.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - foreach (string fgServiceName in fgServicesNames) - { - string fgSrvName = fgServiceName.Trim('"'); - - if (fgSrvName.ToUpper().Equals("ALL")) - { - cpRule.Service.Add(_cpObjects.GetObject(CheckPointObject.Any)); - } - else - { - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_service_custom, FG_PREFIX_KEY_firewall_service_group }; - - bool isAdded = false; - - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgSrvName)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgSrvName]; - foreach (CheckPointObject cpObj in cpObjsList) - { - cpRule.Service.Add(cpObj); - if (OptimizeConf) - { - AddCheckPointObject(cpObj); - } - isAdded = true; - } - } - } - - if (!isAdded) - { - errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'service' field with unrecognized value: " + fgSrvName + " and was not created"); - } - } - } - } - - if (fgCommand_Set.Field.Equals("groups")) - { - string[] fgGroups = fgCommand_Set.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - - foreach (string fgGroup in fgGroups) - { - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_user_group + fgGroup)) - { - List cpObjsList = _localMapperFgCp[FG_PREFIX_KEY_user_group + fgGroup]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - cpUsersGroupsList.AddRange(cpObjsList); - } - } - } - } - - if (fgCommand_Set.Field.Equals("logtraffic") && fgCommand_Set.Value.Equals("disable")) - { - cpRule.Track = CheckPoint_Rule.TrackTypes.None; - } - - if (fgCommand_Set.Field.Equals("comment") || fgCommand_Set.Field.Equals("comments")) - { - cpRule.Comments = fgCommand_Set.Value; - } - - if (fgCommand_Set.Field.Equals("nat") && fgCommand_Set.Value.Equals("enable")) - { - isNatEnabled = true; - } - - if (fgCommand_Set.Field.Equals("ippool") && fgCommand_Set.Value.Equals("enable")) - { - isIpPoolEnabled = true; - } - } - } - - if (errorsList.Count == 0) - { - CheckPoint_Layer rootLayer = null; - - string rootLayerName = ""; - - List fgSrcIntfsList = new List(); - List fgDstIntfsList = new List(); - - foreach (string fgSrcIntf in fgSrcIntfs) - { - string fgSrcIntf_Appendix = ""; - - if (_intfAliasNamesMapper.ContainsKey(fgSrcIntf)) - { - fgSrcIntf_Appendix = _intfAliasNamesMapper[fgSrcIntf] + "_"; - } - - rootLayerName += fgSrcIntf_Appendix + fgSrcIntf + "_"; - - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_system_zone + fgSrcIntf)) - { - fgSrcIntfsList.AddRange(_localMapperFgCp[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]); - } - else - { - CheckPoint_Zone cpZoneSrc = new CheckPoint_Zone(); - cpZoneSrc.Name = GetSafeName(fgSrcIntf_Appendix + fgSrcIntf); - - string warnMessage = CheckZoneForReservedWords(cpZoneSrc); - if(warnMessage != null) - { - extraZonesWarnMsgsList.Add(warnMessage); - } - - fgSrcIntfsList.Add(cpZoneSrc); - - extraZonesMap.Add(FG_PREFIX_KEY_system_zone + fgSrcIntf, cpZoneSrc); - } - } - - rootLayerName += "_"; - - foreach (string fgDstIntf in fgDstIntfs) - { - string fgDstIntf_Appendix = ""; - - if (_intfAliasNamesMapper.ContainsKey(fgDstIntf)) - { - fgDstIntf_Appendix = _intfAliasNamesMapper[fgDstIntf] + "_"; - } - - rootLayerName += fgDstIntf_Appendix + fgDstIntf + "_"; - - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_system_zone + fgDstIntf)) - { - fgDstIntfsList.AddRange(_localMapperFgCp[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]); - } - else - { - CheckPoint_Zone cpZoneDst = new CheckPoint_Zone(); - cpZoneDst.Name = GetSafeName(fgDstIntf_Appendix + fgDstIntf); - - string warnMessage = CheckZoneForReservedWords(cpZoneDst); - if (warnMessage != null) - { - extraZonesWarnMsgsList.Add(warnMessage); - } - - fgDstIntfsList.Add(cpZoneDst); - - extraZonesMap.Add(FG_PREFIX_KEY_system_zone + fgDstIntf, cpZoneDst); - } - } - - rootLayerName = GetSafeName(rootLayerName.Substring(0, (rootLayerName.Length - 1))); - - //--- - - if (rootLayersMap.ContainsKey(rootLayerName)) - { - rootLayer = rootLayersMap[rootLayerName]; - } - else - { - CheckPoint_Rule rootRule = new CheckPoint_Rule(); - rootRule.Name = rootLayerName; - rootRule.Layer = package.NameOfAccessLayer; - rootRule.Source.AddRange(fgSrcIntfsList); - rootRule.Destination.AddRange(fgDstIntfsList); - rootRule.Action = CheckPoint_Rule.ActionType.SubPolicy; - rootRule.Track = CheckPoint_Rule.TrackTypes.Log; - rootRule.Time.Add(_cpObjects.GetObject(CheckPointObject.Any)); - rootRule.Service.Add(_cpObjects.GetObject(CheckPointObject.Any)); - rootRule.SubPolicyName = rootLayerName; - - rootRulesList.Add(rootRule); - - rootLayer = new CheckPoint_Layer(); - rootLayer.Name = rootLayerName; - - rootLayersMap.Add(rootLayerName, rootLayer); - } - - cpRule.Layer = rootLayer.Name; - - //add rule for Users Groups - - CheckPoint_Rule cpRuleUG = null; - - if (cpUsersGroupsList.Count > 0) - { - cpRuleUG = cpRule.Clone(); - cpRuleUG.Name += "_UG"; - cpRuleUG.Source.Clear(); - cpRuleUG.Source.AddRange(cpUsersGroupsList); - - cpRule.Enabled = false; - cpRule.Comments = "Disabled for reason it is replaced by the same rule with Users Groups"; - - } - - rootLayer.Rules.Add(cpRule); - realRulesList.Add(cpRule); - - _rulesInConvertedPackage += 1; - - if (cpRuleUG != null) - { - rootLayer.Rules.Add(cpRuleUG); - - _rulesInConvertedPackage += 1; - } - - rootLayersMap[rootLayer.Name] = rootLayer; - - //NAT conversion reagrding design which is described in other doc - - if(convertNat) - { - int counterNatRules = -1; - - foreach (string fgDstAddr in fgDstAddrList) - { - if (isNatEnabled) - { - 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)) - { - CheckPoint_NetworkGroup cpVipGrp = (CheckPoint_NetworkGroup)cpVipGrpI; - - List cpVipMembersOrig = GetVipGroupMembers(fgDstAddr); - - foreach (string cpVipI in cpVipMembersOrig) - { - 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); - } - } - } - } - } - 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); - } - else if (isIpPoolEnabled) - { - counterNatRules = AddNatRuleIpPool(fgCommand_Edit, fgDstAddr, counterNatRules); - } - else - { - counterNatRules = AddNatRuleSimple(fgCommand_Edit, fgDstAddr, counterNatRules); - } - } - else - { - 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)) - { - CheckPoint_NetworkGroup cpVipGrp = (CheckPoint_NetworkGroup)cpVipGrpI; - - List cpVipMembersOrig = GetVipGroupMembers(fgDstAddr); - - foreach (string cpVipI in cpVipMembersOrig) - { - if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + cpVipI) || - _localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + cpVipI)) - { - counterNatRules = AddNatRuleVipNatDisable(fgCommand_Edit, cpVipI, counterNatRules); - } - } - } - } - } - else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + fgDstAddr) || - _localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + fgDstAddr)) - { - counterNatRules = AddNatRuleVipNatDisable(fgCommand_Edit, fgDstAddr, counterNatRules); - } - } - } - } - } - else - { - - foreach(string error in errorsList) - { - _errorsList.Add(error); - } - } - } - } - - //if Src or Dst Intf DO NOT contain ANY then we create sub-layers - //otherwise policy is plain - if (!isIntfContainsAny) - { - package.ParentLayer.Rules.AddRange(rootRulesList); - - foreach (string key in extraZonesMap.Keys) - { - AddCpObjectToLocalMapper(key, extraZonesMap[key]); - AddCheckPointObject(extraZonesMap[key]); - } - - _warningsList.AddRange(extraZonesWarnMsgsList); - - foreach (string key in rootLayersMap.Keys) - { - CheckPoint_Layer cpLayer = rootLayersMap[key]; - - CheckPoint_Rule cpRuleCU = new CheckPoint_Rule(); - cpRuleCU.Name = "Sub-Policy Cleanup"; - cpRuleCU.Layer = cpLayer.Name; - - cpLayer.Rules.Add(cpRuleCU); - - package.SubPolicies.Add(cpLayer); - } - } - else - { - foreach (CheckPoint_Rule ruleAdd in realRulesList) - { - ruleAdd.Layer = package.ParentLayer.Name; - package.ParentLayer.Rules.Add(ruleAdd); - } - } - - var cpRuleFake = new CheckPoint_Rule(); - cpRuleFake.Name = "Cleanup rule"; //the last rule which is created by default by CheckPoint script importer. It is for report only. - package.ParentLayer.Rules.Add(cpRuleFake); - } - - #endregion - - #region Converting NATs - - public List GetFgSrcAddrsList(FgCommand_Set fgCommandSet) - { - List fgSrcAddrsList = new List(); - - string[] fgSrcAddrsNames = fgCommandSet.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); - foreach (string fgSrcAddrName in fgSrcAddrsNames) - { - string fgSrcAddr = fgSrcAddrName.Trim('"'); - - if (fgSrcAddr.ToLower().Equals("all")) - { - fgSrcAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); - continue; - } - - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_address, FG_PREFIX_KEY_firewall_addrgrp }; - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgSrcAddr)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgSrcAddr]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - fgSrcAddrsList.AddRange(cpObjsList); - } - } - } - } - - return fgSrcAddrsList; - } - - public List GetFgDstAddrsAsVipExtIpList(string fgDstAddr) - { - List fgDstAddrsList = new List(); - - if (fgDstAddr.ToLower().Equals("all")) - { - fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); - } - else - { - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_vip_extip }; - - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - fgDstAddrsList.AddRange(cpObjsList); - } - } - } - } - - return fgDstAddrsList; - } - - public List GetFgDstAddrsAsVipMappedIpList(string fgDstAddr) - { - List fgDstAddrsList = new List(); - - if (fgDstAddr.ToLower().Equals("all")) - { - fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); - } - else - { - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_vip_mappedip }; - - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - fgDstAddrsList.AddRange(cpObjsList); - } - } - } - } - - return fgDstAddrsList; - } - - public List GetFgDstAddrToOSAsVipExtIpList(string fgDstAddr) - { - List fgDstAddrsList = new List(); - - if (fgDstAddr.Equals("all")) - { - fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); - } - else - { - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_service_custom_vipe_ }; - - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - fgDstAddrsList.AddRange(cpObjsList); - } - } - } - } - - return fgDstAddrsList; - } - - public List GetFgDstAddrToOSAsVipMapIpList(string fgDstAddr) - { - List fgDstAddrsList = new List(); - if (fgDstAddr.Equals("all")) - { - fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); - } - else - { - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_service_custom_vipm_ }; - - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - fgDstAddrsList.AddRange(cpObjsList); - } - } - } - } - - return fgDstAddrsList; - } - - public List GetFgServicesList(FgCommand_Set fgCommandSet) - { - List fgServicesList = new List(); - - List fgServicesNames = fgCommandSet.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToList(); - for(int i = 0; i < fgServicesNames.Count; i++) - { - string fgServiceName = fgServicesNames[i]; - - string fgSrvName = fgServiceName.Trim('"'); - - if (fgSrvName.ToLower().Equals("all")) - { - fgServicesList.Add(_cpObjects.GetObject(CheckPointObject.Any)); - continue; - } - - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_service_custom, FG_PREFIX_KEY_firewall_service_group }; - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgSrvName)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgSrvName]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - foreach (CheckPointObject cpObj in cpObjsList) - { - //to skip illegal services for NAT - //--- - // 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)) || - (cpObj.GetType() == typeof(CheckPoint_OtherService))) - { - continue; - } - - if (cpObj.GetType() == typeof(CheckPoint_ServiceGroup)) - { - CheckPoint_ServiceGroup cpServGrp = (CheckPoint_ServiceGroup)cpObj; - foreach (string member in cpServGrp.Members) - { - if (!fgServicesNames.Contains(member)) - { - fgServicesNames.Add(member); - } - } - continue; - } - fgServicesList.Add(cpObj); - } - } - } - } - } - - return fgServicesList; - } - - public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int counterNatRules) - { - string cpNatRuleId = fgCommandEdit.Table; - string cpNatRuleName = ""; - - string cpNatRuleComments = ""; - bool isNatEnable = true; - - List fgDstIntfsList = new List(); - - List fgSrcAddrsList = new List(); - - List fgDstAddrsList = new List(); - - if (fgDstAddr.Equals("all")) - { - fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); - } - else - { - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_address, FG_PREFIX_KEY_firewall_addrgrp }; - - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - fgDstAddrsList.AddRange(cpObjsList); - } - } - } - } - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("name")) - { - cpNatRuleName = fgCommandSet.Value.Trim('"'); - } - if (fgCommandSet.Field.Equals("dstintf")) - { - 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 - { - if (fgDstAddr.Equals("all")) - { - continue; //don't process "all" for FG dstaddr because we can't route for "all" addresses - } - if(fgDstAddrsList.Count != 1) - { - continue; //don't process "multi" FG objects - } - - //get destaddr Object to get its IP address - string fgDstAddrChecking = null; - CheckPointObject checkPointObject = fgDstAddrsList[0]; - - if(checkPointObject.GetType() == typeof(CheckPoint_Range)) - { - fgDstAddrChecking = ((CheckPoint_Range)checkPointObject).RangeFrom; - } - else if (checkPointObject.GetType() == typeof(CheckPoint_Host)) - { - fgDstAddrChecking = ((CheckPoint_Host)checkPointObject).IpAddress; - } - else if (checkPointObject.GetType() == typeof(CheckPoint_Network)) - { - fgDstAddrChecking = ((CheckPoint_Network)checkPointObject).Subnet; - } - if (fgDstAddrChecking == null) - { - continue; - } - IPAddress ipaddress = IPAddress.Parse(fgDstAddrChecking); - //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) - { - fgDstIntfsList.AddRange(cpObjsList); - } - //if Zone contains multi Interface: we should to check: - // 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) - { - string intfName = null; - int netCidr = -1; - string intfNameDefault = null; - string zoneName = fgCommandSet.Value.Trim('"').Trim(); - foreach (string interfaceNameFg in _localFgZoneIntfDict[zoneName]) //check each interface in Zone - { - if (_interfacesFgDict.ContainsKey(interfaceNameFg)) - { - 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 - { - intfName = interfaceNameFg; - netCidr = ipnetwork.Cidr; - } - } - - if (_localFgRoutesDict.ContainsKey(interfaceNameFg)) //check static route - { - foreach (FgStaticRoute fgStaticRoute in _localFgRoutesDict[interfaceNameFg]) - { - if(fgStaticRoute.Network.Equals("0.0.0.0") && intfNameDefault == null) - { - intfNameDefault = fgStaticRoute.Device; - continue; - } - IPNetwork ipnetwork = IPNetwork.Parse(fgStaticRoute.Network, fgStaticRoute.Mask); - if (IPNetwork.Contains(ipnetwork, ipaddress) && netCidr < ipnetwork.Cidr) - { - intfName = interfaceNameFg; - netCidr = ipnetwork.Cidr; - } - } - } - } - if (intfName == null) - { - intfName = intfNameDefault; - } - if(intfName != null) - { - if(_interfacesMapperFgCp.ContainsKey(intfName)) - { - fgDstIntfsList.AddRange(_interfacesMapperFgCp[intfName]); - } - } - } - } - } - - if (fgCommandSet.Field.Equals("srcaddr")) - { - fgSrcAddrsList.AddRange(GetFgSrcAddrsList(fgCommandSet)); - } - - if(fgCommandSet.Field.Equals("comments")) - { - cpNatRuleComments = fgCommandSet.Value.Trim('"'); - } - - if (fgCommandSet.Field.Equals("status") && fgCommandSet.Value.Equals("disable")) - { - isNatEnable = false; - } - } - } - foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) - { - foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) - { - //don't create NAT Rule for Domain objects - if(cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) - { - _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); - continue; - } - - foreach (CheckPointObject cpObjDstAddr in fgDstAddrsList) - { - //don't create NAT Rule for Domain objects - if (cpObjDstAddr.GetType() == typeof(CheckPoint_Domain)) - { - _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjDstAddr.Name + " domain object."); - continue; - } - - CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); - - cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); - cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; - - cpNatRule.Comments += cpNatRuleComments; - cpNatRule.Enabled = isNatEnable; - - cpNatRule.Source = cpObjSrcAddr; - cpNatRule.Destination = cpObjDstAddr; - cpNatRule.Service = _cpObjects.GetObject(CheckPointObject.Any); // we change all nat hide rules service field to Any for simplicity - cpNatRule.TranslatedSource = cpObjDstIntf; - cpNatRule.TranslatedDestination = null; - cpNatRule.TranslatedService = null; - cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; - - _cpNatRules.Add(cpNatRule); - _rulesInNatLayer += 1; - - if (OptimizeConf) - { - _cpObjects.AddObject(cpObjSrcAddr); - _cpObjects.AddObject(cpObjDstAddr); - _cpObjects.AddObject(cpObjDstIntf); - } - } - } - } - return counterNatRules; - } - - public int AddNatRuleIpPool(FgCommand_Edit fgCommandEdit, string fgDstAddr, int counterNatRules) - { - string cpNatRuleId = fgCommandEdit.Table; - string cpNatRuleName = ""; - - string cpNatRuleComments = ""; - bool isNatEnable = true; - - List fgDstIntfsList = new List(); - - List fgSrcAddrsList = new List(); - List fgDstAddrsList = new List(); - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("name")) - { - cpNatRuleName = fgCommandSet.Value.Trim('"'); - } - - if (fgCommandSet.Field.Equals("poolname")) - { - string fgDstIntf = fgCommandSet.Value.Trim('"'); - - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_ippool }; - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstIntf)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgDstIntf]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - fgDstIntfsList.AddRange(cpObjsList); - } - } - } - } - - if (fgCommandSet.Field.Equals("srcaddr")) - { - fgSrcAddrsList.AddRange(GetFgSrcAddrsList(fgCommandSet)); - } - - if (fgCommandSet.Field.Equals("comments")) - { - cpNatRuleComments = fgCommandSet.Value.Trim('"'); - } - - if (fgCommandSet.Field.Equals("status") && fgCommandSet.Value.Equals("disable")) - { - isNatEnable = false; - } - } - } - - if (fgDstAddr.Equals("all")) - { - fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); - } - else - { - foreach (string fgPrefix in (new string[] { FG_PREFIX_KEY_firewall_address, FG_PREFIX_KEY_firewall_addrgrp })) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - fgDstAddrsList.AddRange(cpObjsList); - } - } - } - } - - foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) - { - foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) - { - //don't create NAT Rule for Domain objects - if (cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) - { - _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); - continue; - } - - foreach (CheckPointObject cpObjDstAddr in fgDstAddrsList) - { - //don't create NAT Rule for Domain objects - if (cpObjDstAddr.GetType() == typeof(CheckPoint_Domain)) - { - _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjDstAddr.Name + " Domain object."); - continue; - } - - CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); - - cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); - cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; - - cpNatRule.Comments += cpNatRuleComments; - cpNatRule.Enabled = isNatEnable; - - cpNatRule.Source = cpObjSrcAddr; - cpNatRule.Destination = cpObjDstAddr; - cpNatRule.Service = _cpObjects.GetObject(CheckPointObject.Any); // we change all nat hide rules service field to Any for simplicity - cpNatRule.TranslatedSource = cpObjDstIntf; - cpNatRule.TranslatedDestination = null; - cpNatRule.TranslatedService = null; - cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; - - _cpNatRules.Add(cpNatRule); - _rulesInNatLayer += 1; - - if (OptimizeConf) - { - _cpObjects.AddObject(cpObjSrcAddr); - _cpObjects.AddObject(cpObjDstAddr); - _cpObjects.AddObject(cpObjDstIntf); - } - } - } - } - return counterNatRules; - } - - public int AddNatRuleVipNatEnable(FgCommand_Edit fgCommandEdit, string fgDstAddr, int counterNatRules) - { - string cpNatRuleId = fgCommandEdit.Table; - string cpNatRuleName = ""; - - string cpNatRuleComments = ""; - bool isNatEnable = true; - - bool isIpPoolEnabled = false; - - List fgDstIntfsList = new List(); - - List fgSrcAddrsList = new List(); - - List fgServicesList = new List(); - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("name")) - { - cpNatRuleName = fgCommandSet.Value.Trim('"'); - } - - if (fgCommandSet.Field.Equals("dstintf")) - { - if (!isIpPoolEnabled) - { - 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 - { - if (fgDstAddr.Equals("all")) - { - continue; //don't process "all" for FG dstaddr because we can't route for "all" addresses - } - - List fgDstAddrsList = new List(); - - fgDstAddrsList.AddRange(GetFgDstAddrsAsVipExtIpList(fgDstAddr)); - fgDstAddrsList.AddRange(GetFgDstAddrsAsVipMappedIpList(fgDstAddr)); - - if (fgDstAddrsList.Count != 1) - { - continue; //don't process "multi" FG objects - } - - //get destaddr Object to get its IP address - string fgDstAddrChecking = null; - CheckPointObject checkPointObject = fgDstAddrsList[0]; - - if (checkPointObject.GetType() == typeof(CheckPoint_Range)) - { - fgDstAddrChecking = ((CheckPoint_Range)checkPointObject).RangeFrom; - } - else if (checkPointObject.GetType() == typeof(CheckPoint_Host)) - { - fgDstAddrChecking = ((CheckPoint_Host)checkPointObject).IpAddress; - } - else if (checkPointObject.GetType() == typeof(CheckPoint_Network)) - { - fgDstAddrChecking = ((CheckPoint_Network)checkPointObject).Subnet; - } - if (fgDstAddrChecking == null) - { - continue; - } - IPAddress ipaddress = IPAddress.Parse(fgDstAddrChecking); - //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) - { - fgDstIntfsList.AddRange(cpObjsList); - } - //if Zone contains multi Interface: we should to check: - // 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) - { - string intfName = null; - int netCidr = -1; - string intfNameDefault = null; - string zoneName = fgCommandSet.Value.Trim('"').Trim(); - foreach (string interfaceNameFg in _localFgZoneIntfDict[zoneName]) //check each interface in Zone - { - if (_interfacesFgDict.ContainsKey(interfaceNameFg)) - { - 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 - { - intfName = interfaceNameFg; - netCidr = ipnetwork.Cidr; - } - } - - if (_localFgRoutesDict.ContainsKey(interfaceNameFg)) //check static route - { - foreach (FgStaticRoute fgStaticRoute in _localFgRoutesDict[interfaceNameFg]) - { - if (fgStaticRoute.Network.Equals("0.0.0.0") && intfNameDefault == null) - { - intfNameDefault = fgStaticRoute.Device; - continue; - } - IPNetwork ipnetwork = IPNetwork.Parse(fgStaticRoute.Network, fgStaticRoute.Mask); - if (IPNetwork.Contains(ipnetwork, ipaddress) && netCidr < ipnetwork.Cidr) - { - intfName = interfaceNameFg; - netCidr = ipnetwork.Cidr; - } - } - } - } - if (intfName == null) - { - intfName = intfNameDefault; - } - if (intfName != null) - { - if (_interfacesMapperFgCp.ContainsKey(intfName)) - { - fgDstIntfsList.AddRange(_interfacesMapperFgCp[intfName]); - } - } - } - } - } - } - - if (fgCommandSet.Field.Equals("srcaddr")) - { - fgSrcAddrsList.AddRange(GetFgSrcAddrsList(fgCommandSet)); - } - - if (fgCommandSet.Field.Equals("service")) - { - fgServicesList.AddRange(GetFgServicesList(fgCommandSet)); - } - - if (fgCommandSet.Field.Equals("comments")) - { - cpNatRuleComments = fgCommandSet.Value.Trim('"'); - } - - if (fgCommandSet.Field.Equals("status") && fgCommandSet.Value.Equals("disable")) - { - isNatEnable = false; - } - - if (fgCommandSet.Field.Equals("ippool") && fgCommandSet.Value.Equals("enable")) - { - isIpPoolEnabled = true; - } - - if (fgCommandSet.Field.Equals("poolname")) - { - string fgDstIntf = fgCommandSet.Value.Trim('"'); - - fgDstIntfsList.Clear(); - - string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_ippool }; - foreach (string fgPrefix in fgPrefixes) - { - if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstIntf)) - { - List cpObjsList = _localMapperFgCp[fgPrefix + fgDstIntf]; - if (cpObjsList != null && cpObjsList.Count > 0) - { - fgDstIntfsList.AddRange(cpObjsList); - } - } - } - } - } - } - - if(isIpPoolEnabled) - { - foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) - { - foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) - { - //don't create NAT Rule for Domain objects - if (cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) - { - _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); - continue; - } - - List fgDstAddrsVipExtIpList = new List(); - List fgDstAddrsVipMappedIpList = new List(); - - fgDstAddrsVipExtIpList.AddRange(GetFgDstAddrsAsVipExtIpList(fgDstAddr)); - fgDstAddrsVipMappedIpList.AddRange(GetFgDstAddrsAsVipMappedIpList(fgDstAddr)); - - bool isPortForwardEnabled = false; - - if (_vipPortForwardEnabledMapper.ContainsKey(fgDstAddr)) - { - isPortForwardEnabled = _vipPortForwardEnabledMapper[fgDstAddr]; - } - - foreach (CheckPointObject cpObjDstAddrVipExtIp in fgDstAddrsVipExtIpList) - { - foreach (CheckPointObject cpObjDstAddrVipMappedIp in fgDstAddrsVipMappedIpList) - { - if (isPortForwardEnabled) - { - List listOrigSrv = GetFgDstAddrToOSAsVipExtIpList(fgDstAddr); - List listTransSrv = GetFgDstAddrToOSAsVipMapIpList(fgDstAddr); - foreach (CheckPointObject cpOrigSrv in listOrigSrv) - { - foreach (CheckPointObject cpTransSrv in listTransSrv) - { - CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); - - cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); - cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; - - cpNatRule.Comments += cpNatRuleComments; - cpNatRule.Enabled = isNatEnable; - - cpNatRule.Source = cpObjSrcAddr; - cpNatRule.Destination = cpObjDstAddrVipExtIp; - - cpNatRule.Service = cpOrigSrv; - - cpNatRule.TranslatedSource = cpObjDstIntf; - - cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; - - cpNatRule.TranslatedService = cpTransSrv; - - cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; - - _cpNatRules.Add(cpNatRule); - - _rulesInNatLayer += 1; - - if (OptimizeConf) - { - _cpObjects.AddObject(cpObjSrcAddr); - _cpObjects.AddObject(cpObjDstAddrVipExtIp); - _cpObjects.AddObject(cpObjDstAddrVipMappedIp); - _cpObjects.AddObject(cpOrigSrv); - _cpObjects.AddObject(cpTransSrv); - _cpObjects.AddObject(cpObjDstIntf); - } - } - } - } - else - { - foreach (CheckPointObject cpObjSrv in fgServicesList) - { - CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); - - cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); - cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; - - cpNatRule.Comments += cpNatRuleComments; - cpNatRule.Enabled = isNatEnable; - - cpNatRule.Source = cpObjSrcAddr; - cpNatRule.Destination = cpObjDstAddrVipExtIp; - - cpNatRule.Service = cpObjSrv; - - cpNatRule.TranslatedSource = cpObjDstIntf; - cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; - - cpNatRule.TranslatedService = null; - - cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; - - _cpNatRules.Add(cpNatRule); - _rulesInNatLayer += 1; - - if (OptimizeConf) - { - _cpObjects.AddObject(cpObjSrcAddr); - _cpObjects.AddObject(cpObjDstAddrVipExtIp); - _cpObjects.AddObject(cpObjDstAddrVipMappedIp); - _cpObjects.AddObject(cpObjSrv); - _cpObjects.AddObject(cpObjDstIntf); - } - } - } - } - } - } - } - } - else - { - foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) - { - foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) - { - //don't create NAT Rule for Domain objects - if (cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) - { - _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); - continue; - } - - List fgDstAddrsVipExtIpList = new List(); - List fgDstAddrsVipMappedIpList = new List(); - - fgDstAddrsVipExtIpList.AddRange(GetFgDstAddrsAsVipExtIpList(fgDstAddr)); - fgDstAddrsVipMappedIpList.AddRange(GetFgDstAddrsAsVipMappedIpList(fgDstAddr)); - - bool isPortForwardEnabled = false; - - if (_vipPortForwardEnabledMapper.ContainsKey(fgDstAddr)) - { - isPortForwardEnabled = _vipPortForwardEnabledMapper[fgDstAddr]; - } - - foreach (CheckPointObject cpObjDstAddrVipExtIp in fgDstAddrsVipExtIpList) - { - foreach (CheckPointObject cpObjDstAddrVipMappedIp in fgDstAddrsVipMappedIpList) - { - if (isPortForwardEnabled) - { - List listOrigSrv = GetFgDstAddrToOSAsVipExtIpList(fgDstAddr); - List listTransSrv = GetFgDstAddrToOSAsVipMapIpList(fgDstAddr); - foreach (CheckPointObject cpOrigSrv in listOrigSrv) - { - foreach (CheckPointObject cpTransSrv in listTransSrv) - { - CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); - - cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); - cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; - - cpNatRule.Comments += cpNatRuleComments; - cpNatRule.Enabled = isNatEnable; - - cpNatRule.Source = cpObjSrcAddr; - cpNatRule.Destination = cpObjDstAddrVipExtIp; - - cpNatRule.Service = cpOrigSrv; - - cpNatRule.TranslatedSource = cpObjDstIntf; - - cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; - - cpNatRule.TranslatedService = cpTransSrv; - - cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; - - _cpNatRules.Add(cpNatRule); - - _rulesInNatLayer += 1; - - if (OptimizeConf) - { - _cpObjects.AddObject(cpObjSrcAddr); - _cpObjects.AddObject(cpObjDstAddrVipExtIp); - _cpObjects.AddObject(cpObjDstAddrVipMappedIp); - _cpObjects.AddObject(cpOrigSrv); - _cpObjects.AddObject(cpTransSrv); - } - } - } - } - else - { - foreach (CheckPointObject cpObjSrv in fgServicesList) - { - CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); - - cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); - cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; - - cpNatRule.Comments += cpNatRuleComments; - cpNatRule.Enabled = isNatEnable; - - cpNatRule.Source = cpObjSrcAddr; - cpNatRule.Destination = cpObjDstAddrVipExtIp; - - cpNatRule.Service = cpObjSrv; - - cpNatRule.TranslatedSource = cpObjDstIntf; - cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; - - cpNatRule.TranslatedService = null; - - cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; - - _cpNatRules.Add(cpNatRule); - _rulesInNatLayer += 1; - - if (OptimizeConf) - { - _cpObjects.AddObject(cpObjSrcAddr); - _cpObjects.AddObject(cpObjDstAddrVipExtIp); - _cpObjects.AddObject(cpObjDstAddrVipMappedIp); - _cpObjects.AddObject(cpObjSrv); - } - } - } - } - } - } - } - } - return counterNatRules; - } - - public int AddNatRuleVipNatDisable(FgCommand_Edit fgCommandEdit, string fgDstAddr, int counterNatRules) - { - string cpNatRuleId = fgCommandEdit.Table; - string cpNatRuleName = ""; - - string cpNatRuleComments = ""; - bool isNatEnable = true; - - List fgSrcAddrsList = new List(); - - List fgServicesList = new List(); - - foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) - { - if (fgCommandS.GetType() == typeof(FgCommand_Set)) - { - FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; - - if (fgCommandSet.Field.Equals("name")) - { - cpNatRuleName = fgCommandSet.Value.Trim('"'); - } - - if (fgCommandSet.Field.Equals("srcaddr")) - { - fgSrcAddrsList.AddRange(GetFgSrcAddrsList(fgCommandSet)); - } - - if (fgCommandSet.Field.Equals("service")) - { - fgServicesList.AddRange(GetFgServicesList(fgCommandSet)); - } - - if (fgCommandSet.Field.Equals("comments")) - { - cpNatRuleComments = fgCommandSet.Value.Trim('"'); - } - - if (fgCommandSet.Field.Equals("status") && fgCommandSet.Value.Equals("disable")) - { - isNatEnable = false; - } - } - } - - foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) - { - //don't create NAT Rule for Domain objects - if (cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) - { - _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); - continue; - } - - List fgDstAddrsVipExtIpList = new List(); - List fgDstAddrsVipMappedIpList = new List(); - - fgDstAddrsVipExtIpList.AddRange(GetFgDstAddrsAsVipExtIpList(fgDstAddr)); - fgDstAddrsVipMappedIpList.AddRange(GetFgDstAddrsAsVipMappedIpList(fgDstAddr)); - - bool isPortForwardEnabled = false; - - if (_vipPortForwardEnabledMapper.ContainsKey(fgDstAddr)) - { - isPortForwardEnabled = _vipPortForwardEnabledMapper[fgDstAddr]; - } - - foreach (CheckPointObject cpObjDstAddrVipExtIp in fgDstAddrsVipExtIpList) - { - foreach (CheckPointObject cpObjDstAddrVipMappedIp in fgDstAddrsVipMappedIpList) - { - if (isPortForwardEnabled) - { - List listOrigSrv = GetFgDstAddrToOSAsVipExtIpList(fgDstAddr); - List listTransSrv = GetFgDstAddrToOSAsVipMapIpList(fgDstAddr); - foreach (CheckPointObject cpOrigSrv in listOrigSrv) - { - foreach (CheckPointObject cpTransSrv in listTransSrv) - { - CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); - - cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); - cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; - - cpNatRule.Comments += cpNatRuleComments; - cpNatRule.Enabled = isNatEnable; - - cpNatRule.Source = cpObjSrcAddr; - cpNatRule.Destination = cpObjDstAddrVipExtIp; - - cpNatRule.Service = cpOrigSrv; - - cpNatRule.TranslatedSource = null; - - cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; - - cpNatRule.TranslatedService = cpTransSrv; - - cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Static; - - _cpNatRules.Add(cpNatRule); - - _rulesInNatLayer += 1; - - if (OptimizeConf) - { - _cpObjects.AddObject(cpObjSrcAddr); - _cpObjects.AddObject(cpObjDstAddrVipExtIp); - _cpObjects.AddObject(cpObjDstAddrVipMappedIp); - _cpObjects.AddObject(cpOrigSrv); - _cpObjects.AddObject(cpTransSrv); - } - } - } - } - else { - foreach (CheckPointObject cpObjSrv in fgServicesList) - { - CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); - - cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); - cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; - - cpNatRule.Comments += cpNatRuleComments; - cpNatRule.Enabled = isNatEnable; - - cpNatRule.Source = cpObjSrcAddr; - cpNatRule.Destination = cpObjDstAddrVipExtIp; - - cpNatRule.Service = cpObjSrv; - - cpNatRule.TranslatedSource = null; - cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; - - cpNatRule.TranslatedService = null; - - cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Static; - - _cpNatRules.Add(cpNatRule); - _rulesInNatLayer += 1; - - if (OptimizeConf) - { - _cpObjects.AddObject(cpObjSrcAddr); - _cpObjects.AddObject(cpObjDstAddrVipExtIp); - _cpObjects.AddObject(cpObjDstAddrVipMappedIp); - _cpObjects.AddObject(cpObjSrv); - } - } - } - } - } - } - return counterNatRules; - } - - #endregion - - #region Converter Common methods - - //method checks if some part of Zone Name contains reservered word - // return null if not - // return message if yes - - public string CheckZoneForReservedWords(CheckPoint_Zone inZone) - { - string retMessage = null; - - string inZoneNameNew = ""; - - string[] inZoneNameParts = inZone.Name.Split('-').ToArray(); - - string[] reservedWords = new string[] - { - "all", "All", "and", "any", "Any", - "apr", "Apr", "april", "April", "aug", "Aug", "august", "August", - "black", "blackboxs", "blue", "broadcasts", "call", "comment", - "conn", "date", "day", "debug", "dec", "Dec", "december", "December", - "deffunc", "define", "delete", "delstate", "direction", "do", "domains", - "drop", "dst", "dynamic", "else", "expcall", "expires", "export", "fcall", - "feb", "Feb", "february", "February", "firebrick", "foreground", "forest", - "format", "fri", "Fri", "friday", "Friday", "from", "fw1", "FW1", "fwline", - "fwrule", "gateways", "get", "getstate", "gold", "gray", "green", "hashsize", - "hold", "host", "hosts", "if", "ifaddr", "ifid", "implies", "in", "inbound", - "instate", "interface", "interfaces", "ipsecdata", "ipsecmethods", "is", - "jan", "Jan", "january", "January", "jul", "Jul", "july", "July", "jun", - "Jun", "june", "June", "kbuf", "keep", "limit", "local", "localhost", "log", - "LOG", "logics", "magenta", "mar", "Mar", "march", "March", "may", "May", - "mday", "medium", "modify", "mon", "Mon", "monday", "Monday", "month", - "mortrap", "navy", "netof", "nets", "nexpires", "not", "nov", "Nov", - "november", "November", "oct", "Oct", "october", "October", "or", - "orange", "origdport", "origdst", "origsport", "origsrc", "other", - "outbound", "packet", "packetid", "packetlen", "pass", "r_arg", - "r_call_counter", "r_cdir", "r_cflags", "r_chandler", "r_client_community", - "r_client_ifs_grp", "r_community_left", "r_connarg", "r_crule", "r_ctimeout", - "r_ctype", "r_curr_feature_id", "r_data_offset", "r_dtmatch", "r_dtmflags", - "r_entry", "r_g_offset", "r_ipv6", "r_mapped_ip", "r_mflags", "r_mhandler", - "r_mtimeout", "r_oldcdir", "r_pflags", "r_profile_id", "r_ro_client_community", - "r_ro_dst_sr", "r_ro_server_community", "r_ro_src_sr", "r_scvres", - "r_server_community", "r_server_ifs_grp", "r_service_id", "r_simple_hdrlen", - "r_spii_ret", "r_spii_tcpseq", "r_spii_uuid1", "r_spii_uuid2", "r_spii_uuid3", - "r_spii_uuid4", "r_str_dport", "r_str_dst", "r_str_ipp", "r_str_sport", - "r_str_src", "r_user", "record", "red", "refresh", "reject", "routers", - "sat", "Sat", "saturday", "Saturday", "second", "sep", "Sep", "september", - "September", "set", "setstate", "skipme", "skippeer", "sr", "src", "static", - "sun", "Sun", "sunday", "Sunday", "switchs", "sync", "targets", "thu", "Thu", - "thursday", "Thursday", "to", "tod", "tue", "Tue", "tuesday", "Tuesday", "ufp", - "vanish", "vars", "wasskipped", "wed", "Wed", "wednesday", "Wednesday", - "while", "xlatedport", "xlatedst", "xlatemethod", "xlatesport", "xlatesrc", - "xor", "year", "zero", "zero_ip", "mon", "Mon", "monday", "Monday", "tue", - "Tue", "tuesday", "Tuesday", "wed", "Wed", "wednesday", "Wednesday", "thu", - "Thu", "thursday", "Thursday", "fri", "Fri", "friday", "Friday", "sat", "Sat", - "saturday", "Saturday", "sun", "Sun", "sunday", "Sunday", "jan", "Jan", - "january", "January", "feb", "Feb", "february", "February", "mar", "Mar", - "march", "March", "apr", "Apr", "april", "April", "may", "May", "jun", "Jun", - "june", "June", "jul", "Jul", "july", "July", "aug", "Aug", "august", "August", - "sep", "Sep", "september", "September", "oct", "Oct", "october", "October", - "nov", "Nov", "november", "November", "dec", "Dec", "december", "December", - "date", "day", "month", "year", "black", "blue", "cyan", "dark", "firebrick", - "foreground", "forest", "gold", "gray", "green", "magenta", "medium", "navy", - "orange", "red", "sienna", "yellow", "dark", "light", "medium" - }; - - foreach(string inZoneNamePart in inZoneNameParts) - { - if(reservedWords.Contains(inZoneNamePart)) - { - inZoneNameNew += "_" + inZoneNamePart; - } - else - { - if(!inZoneNameNew.Equals("")) - { - inZoneNameNew += "-"; - } - - inZoneNameNew += inZoneNamePart; - } - } - - if(!inZone.Name.Equals(inZoneNameNew)) - { - retMessage = inZone.Name + " zone was renamed to " + inZoneNameNew + " for solving 'reserved words' issue."; - inZone.Name = inZoneNameNew; - } - - return retMessage; - } - - public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObject) - { - List cpObjectsList = null; - if (_localMapperFgCp.ContainsKey(fgObjectName)) - { - cpObjectsList = _localMapperFgCp[fgObjectName]; - } - else - { - cpObjectsList = new List(); - } - - //check the name of Object - if(cpObject.GetType() == typeof(CheckPoint_TcpService)) - { - 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)) - { - if (!char.IsLetter(cpObject.Name, 0)) - { - string newName = "UDP_" + cpObject.Name; - _warningsList.Add(cpObject.Name + " udp-service was renamed to " + newName); - cpObject.Name = newName; - } - } - else if(cpObject.GetType() == typeof(CheckPoint_SctpService)) - { - 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)) - { - if (!char.IsLetter(cpObject.Name, 0)) - { - string newName = "ICMP_" + cpObject.Name; - _warningsList.Add(cpObject.Name + " icmp-service was renamed to " + newName); - cpObject.Name = newName; - } - } - else if (cpObject.GetType() == typeof(CheckPoint_OtherService)) - { - if (!char.IsLetter(cpObject.Name, 0)) - { - string newName = "OTHER_" + cpObject.Name; - _warningsList.Add(cpObject.Name + " other-service was renamed to " + newName); - cpObject.Name = newName; - } - } - else if(cpObject.GetType() == typeof(CheckPoint_Time)) - { - string cpTimeName = cpObject.Name; - - if (cpTimeName.Length > 11) - { - cpTimeName = cpTimeName.Substring(0, 6) + "_c" + _timeCutterCounter++; - } - - if (!cpTimeName.Equals(cpObject.Name)) - { - _warningsList.Add(cpObject.Name + " time object was renamed to " + cpTimeName); - cpObject.Name = cpTimeName; - } - } - else if(cpObject.GetType() == typeof(CheckPoint_TimeGroup)) - { - string cpTimeGrpName = cpObject.Name; - - if (cpTimeGrpName.Length > 11) - { - cpTimeGrpName = cpTimeGrpName.Substring(0, 6) + "_c" + _timeGroupCutterCounter++; - } - - if(!cpTimeGrpName.Equals(cpObject.Name)) - { - _warningsList.Add(cpObject.Name + " time group object was renamed to " + cpTimeGrpName); - cpObject.Name = cpTimeGrpName; - } - } - - bool isNameExist = true; - - int zIndex = 0; - - string cpObjectName = cpObject.Name; - - while (isNameExist) - { - isNameExist = false; - - foreach (CheckPointObject cpObj in cpObjectsList) - { - if (cpObj.Name.Trim().ToLower().Equals(cpObjectName.Trim().ToLower())) - { - isNameExist = true; - - zIndex += 1; - - cpObjectName = cpObject.Name + "_" + zIndex; - - break; - } - } - } - - if(!cpObject.Name.Equals(cpObjectName)) - { - _warningsList.Add(cpObject.Name + " object was renamed to " + cpObjectName + " for solving duplicate names issue."); - cpObject.Name = cpObjectName; - } - - cpObjectsList.Add(cpObject); - - _localMapperFgCp[fgObjectName] = cpObjectsList; - } - - #endregion - - public static string GetSafeName(string name) - { - if (name != null && !name.Trim().Equals("")) - { - return Regex.Replace(name, @"[^A-Za-z0-9_.-]", "_"); - } - else - { - return name; - } - } - - public List GetVipGroupMembers(string vipGrpName) - { - List retList = new List(); - - List vipGrpMembers = _localFgVipGrpsDict[vipGrpName]; - - foreach(string vipGrpMember in vipGrpMembers) - { - 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)) - { - retList.AddRange(GetVipGroupMembers(vipGrpMember)); - } - } - - return retList; - } - - protected override string GetVendorName() - { - return Vendor.FortiGate.ToString(); - } - } - - public class FgInterface - { - public string Name { get; set; } - public string Ip { get; set; } - public string Network { get; set; } - public string Mask { get; set; } - } - - public class FgStaticRoute - { - public string Name { get; set; } - public string Network { get; set; } - public string Mask { get; set; } - public string Gateway { get; set; } - public string Device { get; set; } - } -} + } + + #region Methods are used for reports + + //count of converted rules. + // -1 is VDOM + public override int RulesInConvertedPackage() + { + return _rulesInConvertedPackage; + } + + //count of warnings of conversion + // -1 if VDOM + public int WarningsInConvertedPackage() + { + return _warningsConvertedPackage; + } + + //count of errors of conversion + // -1 if VDOM + public int ErrorsInConvertedPackage() + { + return _errorsConvertedPackage; + } + + public override int RulesInConvertedOptimizedPackage() + { + return 0; + } + + //count of NAT rules + // -1 if VDOM + public override int RulesInNatLayer() + { + return _rulesInNatLayer; + } + + public override void ExportConfigurationAsHtml() + { + //not used as we have vDOMs + } + + public override void ExportPolicyPackagesAsHtml() + { + //not used as we have vDOMs + } + + public void ExportPolicyPackagesAsHtmlConfig() + { + const string ruleIdPrefix = "rule_"; + + foreach (CheckPoint_Package package in _cpPackages) + { + string filename = _targetFolder + "\\" + package.Name + ".html"; + + using (var file = new StreamWriter(filename, false)) + { + var rulesWithConversionErrors = new Dictionary(); + var rulesWithConversionInfos = new Dictionary(); + var rulesWithInspection = new Dictionary>(); + + GeneratePackageHtmlReportHeaders(file, package.Name, package.ConversionIncidentType != ConversionIncidentType.None); + + // Generate the report body + file.WriteLine(""); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + + int ruleNumber = 1; + + foreach (CheckPoint_Rule rule in package.ParentLayer.Rules) + { + bool isSubPolicy = false; + string action = ""; + string actionStyle = ""; + var dummy = ConversionIncidentType.None; + + switch (rule.Action) + { + case CheckPoint_Rule.ActionType.Accept: + case CheckPoint_Rule.ActionType.Drop: + action = rule.Action.ToString(); + actionStyle = rule.Action.ToString().ToLower(); + break; + + case CheckPoint_Rule.ActionType.SubPolicy: + isSubPolicy = true; + action = "Sub-policy: " + rule.SubPolicyName; + actionStyle = ""; + break; + } + + string curParentRuleId = string.Format("{0}{1}", ruleIdPrefix, ruleNumber); + + if (rule.Enabled) + { + file.WriteLine(" "); + if (isSubPolicy) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + } + else + { + file.WriteLine(" "); + if (isSubPolicy) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + } + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + + if (isSubPolicy) + { + foreach (CheckPoint_Layer subPolicy in package.SubPolicies) + { + int subRuleNumber = 1; + + foreach (CheckPoint_Rule subRule in subPolicy.Rules) + { + if (subRule.Layer == rule.SubPolicyName) + { + var ruleConversionIncidentType = ConversionIncidentType.None; + bool isInspectedRule = !string.IsNullOrEmpty(subRule.Tag); + string curRuleNumber = ruleNumber + "." + subRuleNumber; + string curRuleId = ruleIdPrefix + curRuleNumber; + + if (subRule.Enabled) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + + var sbCurRuleNumberColumnTag = new StringBuilder(); + sbCurRuleNumberColumnTag.Append(" "); + file.WriteLine(sbCurRuleNumberColumnTag.ToString()); + + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + + subRuleNumber++; + + if (package.ConversionIncidentType != ConversionIncidentType.None && ruleConversionIncidentType != ConversionIncidentType.None) + { + if (ruleConversionIncidentType == ConversionIncidentType.ManualActionRequired) + { + rulesWithConversionErrors.Add(curRuleId, subRule); + } + else + { + rulesWithConversionInfos.Add(curRuleId, subRule); + } + } + + if (isInspectedRule) + { + string[] fortiClassMapNames = subRule.Tag.Split(','); // there may be several class-maps matching the same fw rule... + subRule.Tag = curRuleId; // replace class-map name (it is now the key of this dic) by curRuleId... + + foreach (var classMapName in fortiClassMapNames) + { + if (!rulesWithInspection.ContainsKey(classMapName)) + { + var inspectedRules = new List(); + rulesWithInspection.Add(classMapName, inspectedRules); + } + rulesWithInspection[classMapName].Add(subRule); + } + } + } + } + } + } + + ruleNumber++; + } + + file.WriteLine("
No. Name Source Destination Service Action Time Track Comments Conversion Comments
" + + string.Format(HtmlSubPolicyArrowImageTagFormat, curParentRuleId + "_img", HtmlDownArrowImageSourceData) + ruleNumber + "" + ruleNumber + "
" + + string.Format(HtmlSubPolicyArrowImageTagFormat, curParentRuleId + "_img", HtmlDownArrowImageSourceData) + ruleNumber + HtmlDisabledImageTag + "" + ruleNumber + HtmlDisabledImageTag + "" + rule.Name + "" + RuleItemsList2Html(rule.Source, rule.SourceNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(rule.Destination, rule.DestinationNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(rule.Service, false, CheckPointObject.Any, ref dummy) + "" + action + "" + RuleItemsList2Html(rule.Time, false, CheckPointObject.Any, ref dummy) + "" + rule.Track.ToString() + "" + rule.Comments + "" + rule.ConversionComments + "
"); + sbCurRuleNumberColumnTag.Append(" "); + sbCurRuleNumberColumnTag.Append(curRuleNumber); + if (isInspectedRule) + { + sbCurRuleNumberColumnTag.Append(BuildInspectedRuleInfo(subRule.Tag)); + } + if (subRule.ConversionIncidentType != ConversionIncidentType.None) + { + sbCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(subRule.ConvertedCommandId)); + ruleConversionIncidentType = subRule.ConversionIncidentType; + } + if (!subRule.Enabled) + { + sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); + } + sbCurRuleNumberColumnTag.Append("" + subRule.Name + "" + RuleItemsList2Html(subRule.Source, subRule.SourceNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + RuleItemsList2Html(subRule.Destination, subRule.DestinationNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + RuleItemsList2Html(subRule.Service, false, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + subRule.Action.ToString() + "" + RuleItemsList2Html(subRule.Time, false, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + subRule.Track.ToString() + "" + subRule.Comments + "" + subRule.ConversionComments + "
"); + + if (rulesWithConversionErrors.Count > 0 || rulesWithConversionInfos.Count > 0 || rulesWithInspection.Count > 0) + { + file.WriteLine("

Policy Conversion Issues

"); + } + + // Generate the errors report + if (rulesWithConversionErrors.Count > 0) + { + file.WriteLine(""); + + file.WriteLine("

Conversion Errors

"); + file.WriteLine(""); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + + foreach (var ruleEntry in rulesWithConversionErrors) + { + var dummy = ConversionIncidentType.None; + + if (ruleEntry.Value.Enabled) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + + var sbCurRuleNumberColumnTag = new StringBuilder(); + sbCurRuleNumberColumnTag.Append(" "); + file.WriteLine(sbCurRuleNumberColumnTag.ToString()); + + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + } + + file.WriteLine("
No. Name Source Destination Service Action Time Track Comments Conversion Comments
"); + sbCurRuleNumberColumnTag.Append(""); + sbCurRuleNumberColumnTag.Append(ruleEntry.Key.Replace(ruleIdPrefix, "")); + sbCurRuleNumberColumnTag.Append(""); + if (ruleEntry.Value.ConversionIncidentType != ConversionIncidentType.None) + { + sbCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(ruleEntry.Value.ConvertedCommandId)); + } + if (!ruleEntry.Value.Enabled) + { + sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); + } + sbCurRuleNumberColumnTag.Append("" + ruleEntry.Value.Name + "" + RuleItemsList2Html(ruleEntry.Value.Source, ruleEntry.Value.SourceNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Destination, ruleEntry.Value.DestinationNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Service, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Action.ToString() + "" + RuleItemsList2Html(ruleEntry.Value.Time, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Track.ToString() + "" + ruleEntry.Value.Comments + "" + ruleEntry.Value.ConversionComments + "
"); + } + + if (rulesWithConversionInfos.Count > 0 || rulesWithInspection.Count > 0) + { + int counter = (rulesWithInspection.Count > 0) ? 1 : 0; + counter += rulesWithConversionInfos.Count; + + file.WriteLine(""); + file.WriteLine("

Conversion Notifications

"); + } + + // Generate the information report + if (rulesWithConversionInfos.Count > 0) + { + file.WriteLine(""); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + + foreach (var ruleEntry in rulesWithConversionInfos) + { + var dummy = ConversionIncidentType.None; + + if (ruleEntry.Value.Enabled) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + + var sbCurRuleNumberColumnTag = new StringBuilder(); + sbCurRuleNumberColumnTag.Append(" "); + file.WriteLine(sbCurRuleNumberColumnTag.ToString()); + + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + } + + file.WriteLine("
No. Name Source Destination Service Action Time Track Comments Conversion Comments
"); + sbCurRuleNumberColumnTag.Append(""); + sbCurRuleNumberColumnTag.Append(ruleEntry.Key.Replace(ruleIdPrefix, "")); + sbCurRuleNumberColumnTag.Append(""); + if (ruleEntry.Value.ConversionIncidentType != ConversionIncidentType.None) + { + sbCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(ruleEntry.Value.ConvertedCommandId)); + } + if (!ruleEntry.Value.Enabled) + { + sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); + } + sbCurRuleNumberColumnTag.Append("" + ruleEntry.Value.Name + "" + RuleItemsList2Html(ruleEntry.Value.Source, ruleEntry.Value.SourceNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Destination, ruleEntry.Value.DestinationNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Service, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Action.ToString() + "" + RuleItemsList2Html(ruleEntry.Value.Time, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Track.ToString() + "" + ruleEntry.Value.Comments + "" + ruleEntry.Value.ConversionComments + "
"); + } + + file.WriteLine(""); + file.WriteLine(""); + } + } + } + + public string BuildInspectedRuleInfo(string fortiClassMapName) + { + string inspectTooltip = "Rule traffic is affected by FortiGate inspect policy. [class-map objects: " + fortiClassMapName + "]"; + string htmlInspectedImageTag = string.Format(HtmlAlertImageTagFormat, inspectTooltip); + return htmlInspectedImageTag; + } + + //Catalog is Root file if VDOM exists + public void CreateCatalogObjects() + { + string filename = this.ObjectsHtmlFile; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of VDOMs Objects for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string vDomName in _vDomNames) + { + if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_objects.html")) + { + file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //Catalog is Root file if VDOM exists + public void CreateCatalogPolicies() + { + string filename = this.PolicyHtmlFile; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of VDOMs Policies for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string vDomName in _vDomNames) + { + if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_policy.html")) + { + file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //Catalog is Root file if VDOM exists + public void CreateCatalogNATs() + { + string filename = this.NatHtmlFile; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of VDOMs NATs for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string vDomName in _vDomNames) + { + if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_NAT.html")) + { + file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //Catalog is Root file if VDOM exists + public void CreateCatalogErrors() + { + string filename = this._targetFolder + "\\" + _vendorFileName + "_errors.html"; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of VDOMs Errors for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string vDomName in _vDomNames) + { + if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_errors.html")) + { + file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //Catalog is Root file if VDOM exists + public void CreateCatalogWarnings() + { + string filename = this._targetFolder + "\\" + _vendorFileName + "_warnings.html"; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of VDOMs Warnings for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string vDomName in _vDomNames) + { + if (File.Exists(this._targetFolder + vDomName + "\\" + vDomName + "_warnings.html")) + { + file.WriteLine("
  • " + "" + "

    " + vDomName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + vDomName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //report about Errors + public void CreateErrorsHtml(string vDomName) + { + if (_errorsList.Count > 0) + { + string filename = _targetFolder + "//" + vDomName + "_errors.html"; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of " + vDomName + " Errors

"); + file.WriteLine(""); + for (int i = 0; i < _errorsList.Count; i++) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + } + file.WriteLine("
"); + file.WriteLine(i); + file.WriteLine(""); + file.WriteLine(_errorsList[i]); + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + } + + //report about Warnings + public void CreateWarningsHtml(string vDomName) + { + if (_errorsList.Count > 0) + { + string filename = _targetFolder + "//" + vDomName + "_warnings.html"; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of " + vDomName + " Warnings

"); + file.WriteLine(""); + for (int i = 0; i < _warningsList.Count; i++) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + } + file.WriteLine("
"); + file.WriteLine(i); + file.WriteLine(""); + file.WriteLine(_warningsList[i]); + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + } + + #endregion + + #region Converter + + //MAIN method to convert configuration file. + public override void Convert(bool convertNat) + { + string targetFileNameMain = _vendorFileName; + string targetFolderMain = _targetFolder; + + LDAP_Account_Unit = LDAPAccoutUnit.Trim(); + + bool isVDom = ConvertVDom(targetFolderMain, _fortiGateParser.FgCommandsList, convertNat); + + if (!isVDom) //if configration file does not conatin any VDOM + { + InitSystemInterfaces(_fortiGateParser.FgCommandsList); + ConvertConfig(targetFolderMain, targetFileNameMain, _fortiGateParser.FgCommandsList, convertNat); + } + else //if configuration file contains some VDOM then we can not count Errors, Warnings, Rules and NATs + { + _warningsConvertedPackage = -1; + _errorsConvertedPackage = -1; + _rulesInConvertedPackage = -1; + _rulesInNatLayer = -1; + CleanCheckPointObjectsLists(); + } + + RaiseConversionProgress(70, "Optimizing Firewall rulebase ..."); + RaiseConversionProgress(80, "Generating CLI scripts ..."); + + ChangeTargetFolder(targetFolderMain, targetFileNameMain); // chaning target folder path to folder contains config file + + if (_vDomNames.Count > 0) // create HTML files which contain links to each report + { + CreateCatalogObjects(); + CreateCatalogNATs(); + CreateCatalogPolicies(); + CreateCatalogErrors(); + CreateCatalogWarnings(); + } + + VendorHtmlFile = _vendorFilePath; + + ObjectsScriptFile = _targetFolder; + PolicyScriptFile = _targetFolder; + } + + //Convertint VDOMs to each VDOM and then Convert each VDOM as simple Configuration + public bool ConvertVDom(string targetFolderM, List fgCommandsList, bool convertNat) + { + RaiseConversionProgress(10, "Checking if vdom is present..."); + + bool isVDom = false; + + foreach (FgCommand fgCommand in fgCommandsList) + { + if (fgCommand.GetType() == typeof(FgCommand_Config)) + { + FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommand; + if (fgCommandConfig.ObjectName.Equals("vdom")) + { + isVDom = true; + + if (fgCommandConfig.SubCommandsList[0].GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandConfig.SubCommandsList[0]; + + string vdomName = fgCommandEdit.Table; + + _vDomNames.Add(vdomName); + + string targetFolderVDom = targetFolderM + "\\" + vdomName; + + System.IO.Directory.CreateDirectory(targetFolderVDom); + + ConvertConfig(targetFolderVDom, vdomName, fgCommandEdit.SubCommandsList, convertNat); + } + } + + if (fgCommandConfig.ObjectName.Equals("global") && isVDom) + { + InitSystemInterfaces(fgCommandConfig.SubCommandsList); + } + } + } + + return isVDom; + } + + //Init system Interfaces which is Global + public void InitSystemInterfaces(List fgCommandsList) + { + RaiseConversionProgress(20, "Init system interfaces..."); + + foreach (FgCommand fgCommand in fgCommandsList) + { + if (fgCommand.GetType() == typeof(FgCommand_Config)) + { + FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommand; + + if (fgCommandConfig.ObjectName.Equals("system interface")) + { + foreach (FgCommand fgCommandE in fgCommandConfig.SubCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("ip")) + { + string[] ip = fgCommandSet.Value.Split(' ').ToArray(); + + if (ip.Length > 0) + { + FgInterface fgInterface = new FgInterface(); + fgInterface.Name = fgCommandEdit.Table; + fgInterface.Ip = ip[0]; + fgInterface.Network = IPNetwork.Parse(ip[0], ip[1]).Network.ToString(); + fgInterface.Mask = ip[1]; + + _interfacesFgDict[fgInterface.Name] = fgInterface; + + CheckPoint_Host cpHost = new CheckPoint_Host(); + cpHost.Name = GetSafeName(fgCommandEdit.Table + "_intf"); + cpHost.IpAddress = ip[0]; + + List cpHostsList = null; + + if (_interfacesMapperFgCp.ContainsKey(fgCommandEdit.Table)) + { + cpHostsList = _interfacesMapperFgCp[fgCommandEdit.Table]; + } + else + { + cpHostsList = new List(); + } + + cpHostsList.Add(cpHost); + + _warningsList.Add(cpHost.Name + " new host object was created."); + + _interfacesMapperFgCp[fgCommandEdit.Table] = cpHostsList; + } + } + + if (fgCommandSet.Field.Equals("alias")) + { + if (!_intfAliasNamesMapper.ContainsKey(fgCommandEdit.Table)) + { + _intfAliasNamesMapper.Add(fgCommandEdit.Table, fgCommandSet.Value.Trim('"')); + } + } + } + } + } + } + break; + } + } + } + } + + //converting full configuration file or part which is related to VDOM + public void ConvertConfig(string targetFolderNew, string targetFileNameNew, List fgCommandsList, bool convertNat) + { + RaiseConversionProgress(35, "Convert configuration..."); + RaiseConversionProgress(40, "Convert objects..."); + _cpObjects.Initialize(); // must be first!!! + CleanCheckPointObjectsLists(); // must be first!!! + + //change folder path for writing reports + //if it is VDOM then each report will be placed to own folder + //if it is w/o VDOM then report will be in the same folder as config file + ChangeTargetFolder(targetFolderNew, targetFileNameNew); + + if (!OptimizeConf) + { + foreach (string fgInterface in _interfacesMapperFgCp.Keys) + { + List cpHostsList = _interfacesMapperFgCp[fgInterface]; + foreach (CheckPoint_Host cpHost in cpHostsList) + { + AddCheckPointObject(cpHost); + } + } + } + + //Check if string of configuration section is related to FG Object + foreach (FgCommand fgCommand in fgCommandsList) + { + if (fgCommand.GetType() == typeof(FgCommand_Config)) + { + FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommand; + + if(fgCommandConfig.ObjectName.Equals("firewall address")) + { + Add_ConfigFirewallAddress(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("firewall vip")) + { + AddFirewallVip(fgCommandConfig.SubCommandsList); + } + else if(fgCommandConfig.ObjectName.Equals("firewall vipgrp")) + { + AddFirewallVipGroups(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("firewall addrgrp")) + { + Add_AddressGroups(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("firewall service custom")) + { + AddFirewallServices(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("firewall service group")) + { + AddFirewallServicesGroups(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("firewall schedule recurring")) + { + AddFirewallSchedule(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("firewall schedule onetime")) + { + AddFirewallScheduleOneTime(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("firewall schedule group")) + { + AddFirewallScheduleGroups(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("firewall ippool")) + { + AddFirewallIpPool(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("system zone")) + { + AddSystemZone(fgCommandConfig.SubCommandsList); + } + else if(fgCommandConfig.ObjectName.Equals("router static")) + { + AddRoutesStatic(fgCommandConfig.SubCommandsList); + } + else if(fgCommandConfig.ObjectName.Equals("router rip")) + { + CheckDynamicRoutesRip(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("router ripng")) + { + CheckDynamicRoutesRipNg(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("router ospf")) + { + CheckDynamicRoutesOspf(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("router bgp")) + { + CheckDynamicRoutesBgp(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("router isis")) + { + CheckDynamicRoutesIsis(fgCommandConfig.SubCommandsList); + } + else if (fgCommandConfig.ObjectName.Equals("user group") && ConvertUserConf) + { + AddUserGroup(fgCommandConfig.SubCommandsList); + } + } + } + + foreach (FgCommand fgCommand in fgCommandsList) + { + if (fgCommand.GetType() == typeof(FgCommand_Config)) + { + FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommand; + + if (fgCommandConfig.ObjectName.Equals("firewall policy")) + { + Add_Package(fgCommandConfig.SubCommandsList, convertNat); + } + } + } + + if (!OptimizeConf) //adding objects if Optimized configuration is not required + { + foreach (string key in _localMapperFgCp.Keys) + { + if (key.StartsWith(FG_PREFIX_KEY_user_group)) //already added because Access_Roles are added always + { + continue; + } + + List cpObjectsList = _localMapperFgCp[key]; + foreach (CheckPointObject cpObject in cpObjectsList) + { + AddCheckPointObject(cpObject); + } + } + } + + CreateObjectsScript(); + CreateObjectsHtml(); + + CreatePackagesScript(); + + CreateErrorsHtml(targetFileNameNew); + CreateWarningsHtml(targetFileNameNew); + + ExportNatLayerAsHtml(); + ExportPolicyPackagesAsHtmlConfig(); + + _warningsConvertedPackage = _warningsList.Count; + _errorsConvertedPackage = _errorsList.Count; + + CreateSmartConnector(); + + // to clean; must be the last!!! + _cpObjects.ClearRepository(); + CleanSavedData(); + } + + //clean up all data in memmory to converting next VDOM configuration + public void CleanSavedData() + { + _errorsList.Clear(); + _warningsList.Clear(); + _localMapperFgCp.Clear(); + _vipPortForwardEnabledMapper.Clear(); + _localIntrazonesList.Clear(); + _localFgVipGrpsDict.Clear(); + _localFgZoneIntfDict.Clear(); + _localFgRoutesDict.Clear(); + _localFgDynRoutesEnable = false; + _timeCutterCounter = 0; + _timeGroupCutterCounter = 0; + } + + #endregion + + #region Parse Static Routes + + public void AddRoutesStatic(List fgCommandsList) + { + foreach(FgCommand fgCommandE in fgCommandsList) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + FgStaticRoute fgStaticRoute = new FgStaticRoute(); + + fgStaticRoute.Name = fgCommandEdit.Table.Trim('"').Trim(); + + fgStaticRoute.Network = "0.0.0.0"; + fgStaticRoute.Mask = "255.255.255.255"; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if(fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if(fgCommandSet.Field.Equals("dst")) + { + string[] destination = fgCommandSet.Value.Trim('"').Trim().Split(new string[] { " " }, StringSplitOptions.None).ToArray(); + + if(destination.Count() == 2) + { + fgStaticRoute.Network = destination[0]; + fgStaticRoute.Mask = destination[1]; + } + } + if (fgCommandSet.Field.Equals("gateway")) + { + fgStaticRoute.Gateway = fgCommandSet.Value.Trim('"').Trim(); + } + if(fgCommandSet.Field.Equals("device")) + { + fgStaticRoute.Device = fgCommandSet.Value.Trim('"').Trim(); + } + } + } + + List routesList = null; + + if (_localFgRoutesDict.ContainsKey(fgStaticRoute.Device)) + { + routesList = _localFgRoutesDict[fgStaticRoute.Device]; + } + else + { + routesList = new List(); + } + + routesList.Add(fgStaticRoute); + + _localFgRoutesDict[fgStaticRoute.Device] = routesList; + } + } + + #endregion + + #region Parse Dynamic Route + + public void CheckDynamicRoutesRip(List fgCommandsList) + { + foreach(FgCommand fgCommandC in fgCommandsList) + { + if(fgCommandC.GetType() == typeof(FgCommand_Config)) + { + FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommandC; + if(fgCommandConfig.ObjectName.Equals("interface")) + { + _localFgDynRoutesEnable = true; + } + } + } + } + + public void CheckDynamicRoutesRipNg(List fgCommandsList) + { + foreach (FgCommand fgCommandC in fgCommandsList) + { + if (fgCommandC.GetType() == typeof(FgCommand_Config)) + { + FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommandC; + if (fgCommandConfig.ObjectName.Equals("interface")) + { + _localFgDynRoutesEnable = true; + } + } + } + } + + public void CheckDynamicRoutesOspf(List fgCommandsList) + { + foreach(FgCommand fgCommandS in fgCommandsList) + { + if(fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + if(fgCommandSet.Field.Equals("router-id")) + { + _localFgDynRoutesEnable = true; + } + } + } + } + + public void CheckDynamicRoutesBgp(List fgCommandsList) + { + foreach (FgCommand fgCommandC in fgCommandsList) + { + if (fgCommandC.GetType() == typeof(FgCommand_Config)) + { + FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommandC; + if (fgCommandConfig.ObjectName.Equals("neighbor")) + { + _localFgDynRoutesEnable = true; + } + } + } + } + + public void CheckDynamicRoutesIsis(List fgCommandsList) + { + foreach (FgCommand fgCommandC in fgCommandsList) + { + if (fgCommandC.GetType() == typeof(FgCommand_Config)) + { + FgCommand_Config fgCommandConfig = (FgCommand_Config)fgCommandC; + if (fgCommandConfig.ObjectName.Equals("isis-interface")) + { + _localFgDynRoutesEnable = true; + } + } + } + } + + #endregion + + #region Convert Services + + public void AddFirewallServices(List fgCommandsList) + { + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + if (fgCommandEdit.Table.Equals("webproxy")) + { + _errorsList.Add("FortiGate Service of type webproxy was not created."); + continue; + } + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("tcp-portrange")) + { + if (fgCommandSet.Value.Contains(" ")) + { + string[] portRanges = fgCommandSet.Value.Split(' ').ToArray(); + foreach (string portRange in portRanges) + { + AddTcpService(portRange, fgCommandEdit.Table); + } + } + else + { + AddTcpService(fgCommandSet.Value, fgCommandEdit.Table); + } + } + + if (fgCommandSet.Field.Equals("udp-portrange")) + { + if (fgCommandSet.Value.Contains(" ")) + { + string[] portRanges = fgCommandSet.Value.Split(' ').ToArray(); + foreach (string portRange in portRanges) + { + AddUdpService(portRange, fgCommandEdit.Table); + } + } + else + { + AddUdpService(fgCommandSet.Value, fgCommandEdit.Table); + } + } + + if (fgCommandSet.Field.Equals("sctp-portrange")) + { + if (fgCommandSet.Value.Contains(" ")) + { + string[] portRanges = fgCommandSet.Value.Split(' ').ToArray(); + foreach (string portRange in portRanges) + { + AddSctpService(portRange, fgCommandEdit.Table); + } + } + else + { + AddSctpService(fgCommandSet.Value, fgCommandEdit.Table); + } + } + + if (fgCommandSet.Field.Equals("protocol") && fgCommandSet.Value.Equals("ICMP")) + { + AddIcmpService(fgCommandEdit); + break; + } + + if (fgCommandSet.Field.Equals("protocol") && fgCommandSet.Value.Equals("IP")) + { + AddOtherService(fgCommandEdit); + break; + } + } + } + } + } + } + + public void AddOtherService(FgCommand_Edit fgCommandEdit) + { + string protocolNumber = ""; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("protocol-number")) + { + protocolNumber = fgCommandSet.Value; + } + } + } + + if (protocolNumber.Equals("")) + return; + + bool isFound = false; + string cpServiceName = _cpObjects.GetKnownServiceName("OTHER_" + protocolNumber, out isFound); + + CheckPointObject cpObj; + + if (isFound) + { + cpObj = _cpObjects.GetObject(cpServiceName); + } + else + { + CheckPoint_OtherService cpOtherService = new CheckPoint_OtherService(); + cpOtherService.Name = GetSafeName(fgCommandEdit.Table); + cpOtherService.IpProtocol = protocolNumber; + + cpObj = cpOtherService; + } + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + fgCommandEdit.Table, cpObj); + } + + public void AddIcmpService(FgCommand_Edit fgCommandEdit) + { + string type = "99"; + string code = ""; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("icmptype")) + { + type = fgCommandSet.Value; + } + + if (fgCommandSet.Field.Equals("icmpcode")) + { + code = fgCommandSet.Value; + } + } + } + + bool isFound = false; + string cpServiceName = ""; + if (code.Equals("")) + { + cpServiceName = _cpObjects.GetKnownServiceName("ICMP_" + type, out isFound); + } + + CheckPointObject cpObj; + + if (isFound) + { + cpObj = _cpObjects.GetObject(cpServiceName); + } + else + { + CheckPoint_IcmpService cpIcmpService = new CheckPoint_IcmpService(); + cpIcmpService.Name = GetSafeName(fgCommandEdit.Table); + cpIcmpService.Type = type; + if (!code.Equals("")) + { + cpIcmpService.Code = code; + } + + cpObj = cpIcmpService; + } + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + fgCommandEdit.Table, cpObj); + } + + public void AddTcpService(string portRange, string nameEdit) + { + string dest; + string src; + if (portRange.Contains(":")) + { + dest = portRange.Split(':').ToArray()[0]; + src = portRange.Split(':').ToArray()[1]; + } + else + { + dest = portRange; + src = ""; + } + + if (src.StartsWith("0")) + { + src = "1" + src.Substring(1); + } + + if (dest.StartsWith("0")) + { + dest = "1" + dest.Substring(1); + } + + bool isFound; + string cpServiceName = _cpObjects.GetKnownServiceName("TCP_" + dest, out isFound); + + CheckPointObject cpObj; + + if (isFound) + { + cpObj = _cpObjects.GetObject(cpServiceName); + } + else + { + CheckPoint_TcpService cpTcpService = new CheckPoint_TcpService(); + cpTcpService.Name = GetSafeName(nameEdit); + cpTcpService.Port = dest; + if (!src.Equals("")) + { + cpTcpService.SourcePort = src; + } + + cpObj = cpTcpService; + } + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameEdit, cpObj); + } + + public void AddUdpService(string portRange, string nameEdit) + { + string dest; + string src; + if (portRange.Contains(":")) + { + dest = portRange.Split(':').ToArray()[0]; + src = portRange.Split(':').ToArray()[1]; + } + else + { + dest = portRange; + src = ""; + } + + if (src.StartsWith("0")) + { + src = "1" + src.Substring(1); + } + + if (dest.StartsWith("0")) + { + dest = "1" + dest.Substring(1); + } + + bool isFound; + string cpServiceName = _cpObjects.GetKnownServiceName("UDP_" + dest, out isFound); + + CheckPointObject cpObj; + + if (isFound) + { + cpObj = _cpObjects.GetObject(cpServiceName); + } + else + { + CheckPoint_UdpService cpUdpService = new CheckPoint_UdpService(); + cpUdpService.Name = GetSafeName(nameEdit); + cpUdpService.Port = dest; + if (!src.Equals("")) + { + cpUdpService.SourcePort = src; + } + + cpObj = cpUdpService; + } + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameEdit, cpObj); + } + + public void AddSctpService(string portRange, string nameEdit) + { + string dest; + string src; + if (portRange.Contains(":")) + { + dest = portRange.Split(':').ToArray()[0]; + src = portRange.Split(':').ToArray()[1]; + } + else + { + dest = portRange; + src = ""; + } + + if (src.StartsWith("0")) + { + src = "1" + src.Substring(1); + } + + if (dest.StartsWith("0")) + { + dest = "1" + dest.Substring(1); + } + + bool isFound; + string cpServiceName = _cpObjects.GetKnownServiceName("SCTP_" + dest, out isFound); + + CheckPointObject cpObj; + + if (isFound) + { + cpObj = _cpObjects.GetObject(cpServiceName); + } + else + { + CheckPoint_SctpService cpSctpService = new CheckPoint_SctpService(); + cpSctpService.Name = GetSafeName(nameEdit); + cpSctpService.Port = dest; + if (!src.Equals("")) + { + cpSctpService.SourcePort = src; + } + + cpObj = cpSctpService; + } + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_custom + nameEdit, cpObj); + } + + #endregion + + #region Convert Services Groups + + public void AddFirewallServicesGroups(List fgCommandsList) + { + Dictionary checkingSrvGrps = new Dictionary(); + + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + CheckPoint_ServiceGroup cpServiceGroup = new CheckPoint_ServiceGroup(); + cpServiceGroup.Name = GetSafeName(fgCommandEdit.Table); + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + if (fgCommandSet.Field.Equals("member")) + { + string[] members = fgCommandSet.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + foreach (string member in members) + { + string memberC = member.Trim('"'); + + cpServiceGroup.Members.Add(memberC); + } + } + + if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) + { + cpServiceGroup.Comments = fgCommandSet.Value.Trim('"'); + } + } + } + + checkingSrvGrps.Add(fgCommandEdit.Table, cpServiceGroup); + } + } + + while (checkingSrvGrps.Keys.Count > 0) + { + AddFirewallServicesGroupsRecurs(checkingSrvGrps.Keys.First(), checkingSrvGrps); + } + } + + public void AddFirewallServicesGroupsRecurs(string cpSrvGrpName, Dictionary checkingSrvGrps) + { + List errorsList = new List(); + + CheckPoint_ServiceGroup cpSrvGrp = checkingSrvGrps[cpSrvGrpName]; + + checkingSrvGrps.Remove(cpSrvGrpName); + + CheckPoint_ServiceGroup cpSrvGrpAdd = new CheckPoint_ServiceGroup(); + + cpSrvGrpAdd.Name = cpSrvGrp.Name; + + for (int i = 0; i < cpSrvGrp.Members.Count; i++) + { + string member = cpSrvGrp.Members[i]; + + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_service_custom + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_service_custom + member]; + + if (list.Count > 0) + { + cpSrvGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_service_group + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_service_group + member]; + if (list.Count > 0) + { + cpSrvGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + else if (checkingSrvGrps.ContainsKey(member)) + { + AddFirewallServicesGroupsRecurs(member, checkingSrvGrps); + + cpSrvGrpAdd.Members.Add(member); + } + else + { + errorsList.Add(cpSrvGrpAdd.Name + " service group " + + "can not been converted becuase it contains non-existing member: " + member); + } + + if (checkingSrvGrps.ContainsKey(member)) + { + checkingSrvGrps.Remove(member); + } + } + + if (errorsList.Count == 0) + { + //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_group + cpSrvGrpAdd.Name, cpSrvGrpAdd); + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_service_group + cpSrvGrpName, cpSrvGrpAdd); + } + else + { + _errorsList.AddRange(errorsList); + } + } + + #endregion + + #region Convert Schedules + + public void AddFirewallSchedule(List fgCommandsList) + { + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + if (fgCommandEdit.Table.Equals("always")) + { + if (!_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_schedule_recurring + "always")) + { + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_recurring + "always", _cpObjects.GetObject(CheckPointObject.Any)); + } + continue; + } + + CheckPoint_Time cpTime = new CheckPoint_Time(); + + cpTime.Name = fgCommandEdit.Table; + + cpTime.StartNow = true; + cpTime.EndNever = true; + + string timeStart = null; + string timeEnd = null; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("day")) + { + List cpDays = new List(); + string[] days = fgCommandSet.Value.Split(' '); + foreach (string day in days) + { + switch (day) + { + case "sunday": + cpDays.Add(CheckPoint_Time.Weekdays.Sun); + break; + case "monday": + cpDays.Add(CheckPoint_Time.Weekdays.Mon); + break; + case "tuesday": + cpDays.Add(CheckPoint_Time.Weekdays.Tue); + break; + case "wednesday": + cpDays.Add(CheckPoint_Time.Weekdays.Wed); + break; + case "thursday": + cpDays.Add(CheckPoint_Time.Weekdays.Thu); + break; + case "friday": + cpDays.Add(CheckPoint_Time.Weekdays.Fri); + break; + case "saturday": + cpDays.Add(CheckPoint_Time.Weekdays.Sat); + break; + } + } + cpTime.RecurrenceWeekdays = cpDays; + } + + if (fgCommandSet.Field.Equals("start")) + { + timeStart = fgCommandSet.Value; + } + + if (fgCommandSet.Field.Equals("end")) + { + timeEnd = fgCommandSet.Value; + } + + if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) + { + cpTime.Comments = fgCommandSet.Value.Trim('"'); + } + } + } + + //... + if (timeStart != null || timeEnd != null) + { + if (timeStart == null) + { + timeStart = "00:00"; + } + if (timeEnd == null) + { + timeEnd = "00:00"; + } + if (TimeSpan.Parse(timeStart) <= TimeSpan.Parse(timeEnd)) + { + cpTime.HoursRangesEnabled_1 = true; + cpTime.HoursRangesFrom_1 = timeStart; + cpTime.HoursRangesTo_1 = timeEnd; + } + else + { + cpTime.HoursRangesEnabled_1 = true; + cpTime.HoursRangesFrom_1 = timeStart; + cpTime.HoursRangesTo_1 = "23:59"; + + cpTime.HoursRangesEnabled_2 = true; + cpTime.HoursRangesFrom_2 = "00:00"; + cpTime.HoursRangesTo_2 = timeEnd; + } + } + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_recurring + fgCommandEdit.Table, cpTime); + } + } + } + + public void AddFirewallScheduleOneTime(List fgCommandsList) + { + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + CheckPoint_Time cpTime = new CheckPoint_Time(); + + cpTime.Name = fgCommandEdit.Table; + + cpTime.StartNow = false; + cpTime.EndNever = false; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("start")) + { + DateTime date = DateTime.ParseExact(fgCommandSet.Value.Trim('"'), "HH:mm yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); + + cpTime.StartDate = date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture); + cpTime.StartTime = date.ToString("HH:mm"); + } + + if (fgCommandSet.Field.Equals("end")) + { + DateTime date = DateTime.ParseExact(fgCommandSet.Value.Trim('"'), "HH:mm yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); + + cpTime.EndDate = date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture); + cpTime.EndTime = date.ToString("HH:mm"); + } + + if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) + { + cpTime.Comments = fgCommandSet.Value.Trim('"'); + } + } + } + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_onetime + fgCommandEdit.Table, cpTime); + } + } + } + + #endregion + + #region Convert Schedules Groups + + public void AddFirewallScheduleGroups(List fgCommandsList) + { + Dictionary checkingTimeGrps = new Dictionary(); + + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + CheckPoint_TimeGroup cpTimeGroup = new CheckPoint_TimeGroup(); + cpTimeGroup.Name = GetSafeName(fgCommandEdit.Table); + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + if (fgCommandSet.Field.Equals("member")) + { + string[] members = fgCommandSet.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + foreach (string member in members) + { + string memberC = member.Trim('"'); + cpTimeGroup.Members.Add(memberC); + } + } + + if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) + { + cpTimeGroup.Comments = fgCommandSet.Value.Trim('"'); + } + } + } + + checkingTimeGrps.Add(fgCommandEdit.Table, cpTimeGroup); + } + } + + while (checkingTimeGrps.Keys.Count > 0) + { + AddFirewallScheduleGroupsRecurs(checkingTimeGrps.Keys.First(), checkingTimeGrps); + } + } + + public void AddFirewallScheduleGroupsRecurs(string cpTimeGrpName, Dictionary checkingTimeGrps) + { + List errorsList = new List(); + + CheckPoint_TimeGroup cpTimeGrp = checkingTimeGrps[cpTimeGrpName]; + + checkingTimeGrps.Remove(cpTimeGrpName); + + CheckPoint_TimeGroup cpTimeGrpAdd = new CheckPoint_TimeGroup(); + + cpTimeGrpAdd.Name = cpTimeGrp.Name; + + for (int i = 0; i < cpTimeGrp.Members.Count; i++) + { + string member = cpTimeGrp.Members[i]; + + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_schedule_recurring + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_schedule_recurring + member]; + if (list.Count > 0) + { + cpTimeGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_schedule_onetime + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_schedule_onetime + member]; + if (list.Count > 0) + { + cpTimeGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_schedule_group + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_schedule_group + member]; + if (list.Count > 0) + { + cpTimeGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + else if (checkingTimeGrps.ContainsKey(member)) + { + AddFirewallScheduleGroupsRecurs(member, checkingTimeGrps); + + cpTimeGrpAdd.Members.Add(member); + } + else + { + errorsList.Add(cpTimeGrpAdd.Name + " schedule group " + + "can not been converted becuase it contains non-existing member: " + member); + } + + if (checkingTimeGrps.ContainsKey(member)) + { + checkingTimeGrps.Remove(member); + } + } + + if (errorsList.Count == 0) + { + //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_group + cpTimeGrp.Name, cpTimeGrpAdd); + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_schedule_group + cpTimeGrpName, cpTimeGrpAdd); + } + else + { + _errorsList.AddRange(errorsList); + } + } + + #endregion + + #region Convert IpPool + + public void AddFirewallIpPool(List fgCommandsList) + { + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + CheckPoint_Range cpRange = new CheckPoint_Range(); + cpRange.Name = GetSafeName(fgCommandEdit.Table); + cpRange.RangeFrom = ""; + cpRange.RangeTo = ""; + + CheckPoint_Range cpRangeSrc = new CheckPoint_Range(); + cpRangeSrc.Name = GetSafeName(fgCommandEdit.Table); + cpRangeSrc.RangeFrom = ""; + cpRangeSrc.RangeTo = ""; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + switch (fgCommandSet.Field) + { + case "startip": + cpRange.RangeFrom = fgCommandSet.Value; + break; + case "endip": + cpRange.RangeTo = fgCommandSet.Value; + break; + case "source-startip": + cpRangeSrc.RangeFrom = fgCommandSet.Value; + break; + case "source-endip": + cpRangeSrc.RangeTo = fgCommandSet.Value; + break; + } + } + } + + if (!cpRange.RangeFrom.Equals("") && !cpRange.RangeTo.Equals("")) + { + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_ippool + fgCommandEdit.Table, cpRange); + } + + if (!cpRangeSrc.RangeFrom.Equals("") && !cpRangeSrc.RangeTo.Equals("")) + { + //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_ippool_source + fgCommandEdit.Table, cpRangeSrc); + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_ippool + fgCommandEdit.Table, cpRangeSrc); + } + } + } + } + + #endregion + + #region Convert System Zone + + public void AddSystemZone(List fgCommandsList) + { + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + CheckPoint_Zone cpZone = new CheckPoint_Zone(); + cpZone.Name = GetSafeName(fgCommandEdit.Table); + + bool isIntraZone = false; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("intrazone") && fgCommandSet.Value.Equals("allow")) + { + isIntraZone = true; + } + + if (fgCommandSet.Field.Equals("interface")) + { + string[] zoneInterfaces = fgCommandSet.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + + _localFgZoneIntfDict[fgCommandEdit.Table] = zoneInterfaces.ToList(); + + foreach (string zoneInterface in zoneInterfaces) + { + if(_interfacesMapperFgCp.ContainsKey(zoneInterface)) + { + List cpObjsList = _interfacesMapperFgCp[zoneInterface]; + foreach (CheckPoint_Host cpObj in cpObjsList) + { + AddCpObjectToLocalMapper(FG_PREFIX_KEY_system_zone_host + fgCommandEdit.Table, cpObj); + } + } + } + } + } + } + + if (isIntraZone) + { + _localIntrazonesList.Add(cpZone); + } + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_system_zone + fgCommandEdit.Table, cpZone); + } + } + } + + #endregion + + #region Convert Users Groups + + public void AddUserGroup(List fgCommandsList) + { + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + bool isFSSOService = false; + + string membersStr = ""; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("group-type") && fgCommandSet.Value.Equals("fsso-service")) + { + isFSSOService = true; + } + + if (fgCommandSet.Field.Equals("member")) + { + membersStr = fgCommandSet.Value.Trim('"'); + } + } + } + + if (isFSSOService) + { + CheckPoint_AccessRole cpAccessRole = new CheckPoint_AccessRole(); + cpAccessRole.Name = GetSafeName(fgCommandEdit.Table); + + string[] members = membersStr.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + foreach (string member in members) + { + if (string.IsNullOrWhiteSpace(member)) + continue; + + if (member.Contains(",")) + { + List values = new List(); + member.Split(new string[] { "," }, StringSplitOptions.None).ToList().ForEach(x => values.Add(x.Trim().Substring(x.IndexOf("=") + 1))); + + AccessRoleUser arUser = new AccessRoleUser(); + arUser.Name = values[0]; + arUser.BaseDn = member; + + cpAccessRole.Users.Add(arUser); + } + else if (member.Contains("\\")) + { + AccessRoleUser arUser = new AccessRoleUser(); + arUser.Name = member.Substring(member.IndexOf("\\") + 1); + + cpAccessRole.Users.Add(arUser); + } + else + { + AccessRoleUser arUser = new AccessRoleUser(); + arUser.Name = member; + + cpAccessRole.Users.Add(arUser); + } + } + + if (cpAccessRole.Users.Count > 0) + { + AddCpObjectToLocalMapper(FG_PREFIX_KEY_user_group + fgCommandEdit.Table, cpAccessRole); + AddCheckPointObject(cpAccessRole); + } + } + } + } + } + + #endregion + + #region Convert Addresses + + public void Add_ConfigFirewallAddress(List fgCommandsList) + { + foreach(FgCommand fgCommand in fgCommandsList) + { + if (fgCommand.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommand; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + CheckPointObject cpObject = null; + + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("type")) + { + switch (fgCommandSet.Value) + { + case "fqdn": + cpObject = Add_Domain(fgCommandEdit, false); + break; + case "wildcard-fqdn": + cpObject = Add_Domain(fgCommandEdit, true); + break; + case "iprange": + cpObject = Add_IpRange(fgCommandEdit); + break; + } + } + else if (fgCommandSet.Field.Equals("subnet")) + { + cpObject = Add_Subnet(fgCommandEdit); + } + + if (cpObject != null) + { + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_address + fgCommandEdit.Table, cpObject); + } + } + } + } + } + } + + public CheckPointObject Add_Domain(FgCommand_Edit fgCommandEdit, bool isSubDomain) + { + CheckPoint_Domain cpDomain = new CheckPoint_Domain(); + cpDomain.IsSubDomain = isSubDomain; + + string comment = ""; + + foreach (FgCommand fgCommand in fgCommandEdit.SubCommandsList) + { + if (fgCommand.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommand; + if (fgCommandSet.Field.Equals("fqdn")) + { + cpDomain.Name = GetSafeName("." + fgCommandSet.Value); + } + else if (fgCommandSet.Field.Equals("wildcard-fqdn")) + { + int indStar = fgCommandSet.Value.Trim('"').LastIndexOf("*"); + + string subDomain = fgCommandSet.Value.Trim('"').Substring(indStar + 1); + if (!subDomain.StartsWith(".")) + { + subDomain = "." + subDomain; + } + + cpDomain.Name = GetSafeName(subDomain); + } + + if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) + { + comment = fgCommandSet.Value.Trim('"'); + } + } + } + + cpDomain.Comments = comment; + + return cpDomain; + } + + public CheckPointObject Add_IpRange(FgCommand_Edit fgCommandEdit) + { + CheckPoint_Range cpRange = new CheckPoint_Range(); + cpRange.Name = GetSafeName(fgCommandEdit.Table); + + string comment = ""; + + foreach (FgCommand fgCommand in fgCommandEdit.SubCommandsList) + { + if (fgCommand.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommand; + if (fgCommandSet.Field.Equals("start-ip")) + { + cpRange.RangeFrom = fgCommandSet.Value; + } + if (fgCommandSet.Field.Equals("end-ip")) + { + cpRange.RangeTo = fgCommandSet.Value; + } + if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) + { + comment = fgCommandSet.Value.Trim('"'); + } + } + } + + cpRange.Comments = comment; + + return cpRange; + } + + public CheckPointObject Add_Subnet(FgCommand_Edit fgCommandEdit) + { + CheckPointObject cpObjectRet = null; + string comment = ""; + + foreach (FgCommand fgCommand in fgCommandEdit.SubCommandsList) + { + if (fgCommand.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommand; + if (fgCommandSet.Field.Equals("subnet")) + { + string ipAddress = fgCommandSet.Value.Substring(0, fgCommandSet.Value.IndexOf(" ")).Trim(); + string ipMask = fgCommandSet.Value.Substring(fgCommandSet.Value.IndexOf(" ")).Trim(); + + if (ipMask.Equals("255.255.255.255")) + { + CheckPoint_Host cpHost = new CheckPoint_Host(); + cpHost.Name = GetSafeName(fgCommandEdit.Table); + cpHost.IpAddress = ipAddress; + cpObjectRet = cpHost; + } + else + { + CheckPoint_Network cpNetwork = new CheckPoint_Network(); + cpNetwork.Name = GetSafeName(fgCommandEdit.Table); + cpNetwork.Subnet = ipAddress; + cpNetwork.Netmask = ipMask; + cpObjectRet = cpNetwork; + } + } + if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) + { + comment = fgCommandSet.Value.Trim('"'); + } + } + } + + cpObjectRet.Comments = comment; + + return cpObjectRet; + } + + #endregion + + #region Convert VIP + + public void AddFirewallVip(List fgCommandsList) + { + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + bool isPortForwardEnabled = false; + string protocol = "tcp"; + + string portExt = ""; + string portMap = ""; + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("extip")) + { + string[] addressesArray = fgCommandSet.Value.Trim('"').Split('-').ToArray(); + if (addressesArray.Length == 1) + { + CheckPoint_Host cpHost = new CheckPoint_Host(); + cpHost.Name = GetSafeName(fgCommandEdit.Table + "_vip_extip"); + cpHost.IpAddress = addressesArray[0]; + + _warningsList.Add(cpHost.Name + " new host was created from " + fgCommandEdit.Table + " VIP (ext-ip)."); + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_extip + fgCommandEdit.Table, cpHost); + } + else + { + CheckPoint_Range cpRange = new CheckPoint_Range(); + cpRange.Name = GetSafeName(fgCommandEdit.Table + "_vip_extip"); + + _warningsList.Add(cpRange.Name + " new range was created from " + fgCommandEdit.Table + " VIP (ext-ip)."); + + cpRange.RangeFrom = addressesArray[0]; + cpRange.RangeTo = addressesArray[1]; + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_extip + fgCommandEdit.Table, cpRange); + } + } + + if (fgCommandSet.Field.Equals("mappedip")) + { + string[] addressesArray = fgCommandSet.Value.Trim('"').Split('-').ToArray(); + if (addressesArray.Length == 1) + { + CheckPoint_Host cpHost = new CheckPoint_Host(); + cpHost.Name = GetSafeName(fgCommandEdit.Table + "_vip_mappedip"); + + _warningsList.Add(cpHost.Name + " new host was created from " + fgCommandEdit.Table + " VIP (mapped-ip)."); + + cpHost.IpAddress = addressesArray[0]; + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_mappedip + fgCommandEdit.Table, cpHost); + } + else + { + CheckPoint_Range cpRange = new CheckPoint_Range(); + cpRange.Name = GetSafeName(fgCommandEdit.Table + "_vip_mappedip"); + + _warningsList.Add(cpRange.Name + " new range was created from " + fgCommandEdit.Table + " VIP (mapped-ip)."); + + cpRange.RangeFrom = addressesArray[0]; + cpRange.RangeTo = addressesArray[1]; + + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_mappedip + fgCommandEdit.Table, cpRange); + } + } + + if (fgCommandSet.Field.Equals("portforward") && fgCommandSet.Value.Equals("enable")) + { + isPortForwardEnabled = true; + _vipPortForwardEnabledMapper[fgCommandEdit.Table] = true; + } + + if (fgCommandSet.Field.Equals("extport")) + { + portExt = fgCommandSet.Value; + } + + if (fgCommandSet.Field.Equals("mappedport")) + { + portMap = fgCommandSet.Value; + } + + if (fgCommandSet.Field.Equals("protocol")) + { + protocol = fgCommandSet.Value; + } + } + } + + + if (isPortForwardEnabled) + { + string nameVipE = "VIPe_" + fgCommandEdit.Table; + string nameVipM = "VIPm_" + fgCommandEdit.Table; + switch (protocol) + { + case "tcp": + if (!portExt.Equals("")) + { + AddTcpService(portExt, nameVipE); + } + if (!portMap.Equals("")) + { + AddTcpService(portMap, nameVipM); + } + break; + case "udp": + if (!portExt.Equals("")) + { + AddUdpService(portExt, nameVipE); + } + if (!portMap.Equals("")) + { + AddUdpService(portMap, nameVipM); + } + break; + case "sctp": + if (!portExt.Equals("")) + { + AddSctpService(portExt, nameVipE); + } + if (!portMap.Equals("")) + { + AddSctpService(portMap, nameVipM); + } + 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; + } + } + } + } + } + + #endregion + + #region Convert VIP Groups + + public void AddFirewallVipGroups(List fgCommandsList) + { + Dictionary checkingVipGrps = new Dictionary(); + + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + CheckPoint_NetworkGroup cpVipGroup = new CheckPoint_NetworkGroup(); + cpVipGroup.Name = GetSafeName(fgCommandEdit.Table); + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + if (fgCommandSet.Field.Equals("member")) + { + string[] members = fgCommandSet.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + foreach (string member in members) + { + string memberC = member.Trim('"'); + cpVipGroup.Members.Add(memberC); + } + } + + if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) + { + cpVipGroup.Comments = fgCommandSet.Value.Trim('"'); + } + } + } + + checkingVipGrps.Add(fgCommandEdit.Table, cpVipGroup); + + _localFgVipGrpsDict[fgCommandEdit.Table] = cpVipGroup.Members; + } + } + + while (checkingVipGrps.Keys.Count > 0) + { + Add_VipGroupsRecurs(checkingVipGrps.Keys.First(), checkingVipGrps); + } + } + + public void Add_VipGroupsRecurs(string cpVipGrpName, Dictionary checkingVipGrps) + { + List errorsList = new List(); + + CheckPoint_NetworkGroup cpVipGrp = checkingVipGrps[cpVipGrpName]; + + checkingVipGrps.Remove(cpVipGrpName); + + CheckPoint_NetworkGroup cpVipGrpAdd = new CheckPoint_NetworkGroup(); + + cpVipGrpAdd.Name = cpVipGrp.Name; + + for (int i = 0; i < cpVipGrp.Members.Count; i++) + { + string member = cpVipGrp.Members[i]; + + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + member) || _localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + member)) + { + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_vip_extip + member]; + + if (list.Count > 0) + { + cpVipGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_vip_mappedip + member]; + + if (list.Count > 0) + { + cpVipGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + } + else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_grp + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_vip_grp + member]; + + if (list.Count > 0) + { + cpVipGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + else if (checkingVipGrps.ContainsKey(member)) + { + Add_VipGroupsRecurs(member, checkingVipGrps); + + cpVipGrpAdd.Members.Add(member); + } + else + { + errorsList.Add(cpVipGrpAdd.Name + " network group " + + "can not been converted becuase it contains non-existing member: " + member); + } + + if (checkingVipGrps.ContainsKey(member)) + { + checkingVipGrps.Remove(member); + } + } + + if (errorsList.Count == 0) + { + //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_grp + cpVipGrp.Name, cpVipGrpAdd); + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_vip_grp + cpVipGrpName, cpVipGrpAdd); + } + else + { + _errorsList.AddRange(errorsList); + } + } + + #endregion + + #region Convert Addresses Groups + + public void Add_AddressGroups(List fgCommandsList) + { + Dictionary checkingAddrGrps = new Dictionary(); + + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommandEdit = (FgCommand_Edit)fgCommandE; + + CheckPoint_NetworkGroup cpAddrGroup = new CheckPoint_NetworkGroup(); + cpAddrGroup.Name = GetSafeName(fgCommandEdit.Table); + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + if (fgCommandSet.Field.Equals("member")) + { + string[] members = fgCommandSet.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + foreach (string member in members) + { + string memberC = member.Trim('"'); + cpAddrGroup.Members.Add(memberC); + } + } + + if (fgCommandSet.Field.Equals("comment") || fgCommandSet.Field.Equals("comments")) + { + cpAddrGroup.Comments = fgCommandSet.Value.Trim('"'); + } + } + } + + checkingAddrGrps.Add(fgCommandEdit.Table, cpAddrGroup); + } + } + + while (checkingAddrGrps.Keys.Count > 0) + { + Add_AddressGroupsRecurs(checkingAddrGrps.Keys.First(), checkingAddrGrps); + } + } + + public void Add_AddressGroupsRecurs(string cpAddrGrpName, Dictionary checkingAddrGrps) + { + List errorsList = new List(); + + CheckPoint_NetworkGroup cpAddrGrp = checkingAddrGrps[cpAddrGrpName]; + + checkingAddrGrps.Remove(cpAddrGrpName); + + CheckPoint_NetworkGroup cpAddrGrpAdd = new CheckPoint_NetworkGroup(); + + cpAddrGrpAdd.Name = cpAddrGrp.Name; + + for (int i = 0; i < cpAddrGrp.Members.Count; i++) + { + string member = cpAddrGrp.Members[i]; + + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_address + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_address + member]; + + if (list.Count > 0) + { + cpAddrGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_addrgrp + member)) + { + List list = _localMapperFgCp[FG_PREFIX_KEY_firewall_addrgrp + member]; + + if (list.Count > 0) + { + cpAddrGrpAdd.Members.AddRange((from o in list select o.Name).ToList()); + } + } + else if (checkingAddrGrps.ContainsKey(member)) + { + Add_AddressGroupsRecurs(member, checkingAddrGrps); + + cpAddrGrpAdd.Members.Add(member); + } + else + { + errorsList.Add(cpAddrGrpAdd.Name + " address group " + + "can not been converted becuase it contains non-existing member: " + member); + } + + if (checkingAddrGrps.ContainsKey(member)) + { + checkingAddrGrps.Remove(member); + } + } + + if (errorsList.Count == 0) + { + //AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_addrgrp + cpAddrGrp.Name, cpAddrGrpAdd); + AddCpObjectToLocalMapper(FG_PREFIX_KEY_firewall_addrgrp + cpAddrGrpName, cpAddrGrpAdd); + } + else + { + _errorsList.AddRange(errorsList); + } + } + + #endregion + + #region Convert Policy Rules && prepare for NATs converting + + public void Add_Package(List fgCommandsList, bool convertNat) + { + RaiseConversionProgress(70, "Convert policy..."); + + var cpPackage = new CheckPoint_Package(); + cpPackage.Name = _policyPackageName; + + Add_ParentLayer(cpPackage, fgCommandsList, convertNat); + + AddCheckPointObject(cpPackage); + } + + public void Add_ParentLayer(CheckPoint_Package package, List fgCommandsList, bool convertNat) + { + package.ParentLayer.Name = package.NameOfAccessLayer; + + List rootRulesList = new List(); + Dictionary rootLayersMap = new Dictionary(); + Dictionary extraZonesMap = new Dictionary(); + List extraZonesWarnMsgsList = new List(); + List realRulesList = new List(); //is used if 'plain' policy should be converted + + //add main rule from Intrazone + //add sub policy layer + //add rule from Intrazone + + foreach(CheckPoint_Zone cpZoneIntra in _localIntrazonesList) + { + string warnMessage = CheckZoneForReservedWords(cpZoneIntra); + + if(warnMessage != null) + { + _warningsList.Add(warnMessage); + } + + AddCheckPointObject(cpZoneIntra); + + CheckPoint_Rule cpRuleZone = new CheckPoint_Rule(); + cpRuleZone.Name = GetSafeName(cpZoneIntra.Name); //"Intrazone_" + cpZoneIntra.Name; + cpRuleZone.Layer = package.NameOfAccessLayer; + cpRuleZone.Source.Add(cpZoneIntra); + cpRuleZone.Destination.Add(cpZoneIntra); + cpRuleZone.Action = CheckPoint_Rule.ActionType.SubPolicy; + cpRuleZone.Track = CheckPoint_Rule.TrackTypes.Log; + cpRuleZone.Time.Add(_cpObjects.GetObject(CheckPointObject.Any)); + cpRuleZone.Service.Add(_cpObjects.GetObject(CheckPointObject.Any)); + cpRuleZone.SubPolicyName = GetSafeName(cpZoneIntra.Name + "_internal"); + + package.ParentLayer.Rules.Add(cpRuleZone); + + CheckPoint_Layer cpRuleLayer = new CheckPoint_Layer(); + cpRuleLayer.Name = cpRuleZone.SubPolicyName; + + package.SubPolicies.Add(cpRuleLayer); + + CheckPoint_Rule cpSubRuleZone = new CheckPoint_Rule(); + cpSubRuleZone.Name = ""; //"intrazone_sr_" + cpZoneIntra.Name; + cpSubRuleZone.Layer = cpRuleLayer.Name; + cpSubRuleZone.Source.Add(_cpObjects.GetObject(CheckPointObject.Any)); + cpSubRuleZone.Destination.Add(_cpObjects.GetObject(CheckPointObject.Any)); + cpSubRuleZone.Action = CheckPoint_Rule.ActionType.Accept; + cpSubRuleZone.Track = CheckPoint_Rule.TrackTypes.Log; + cpSubRuleZone.Time.Add(_cpObjects.GetObject(CheckPointObject.Any)); + cpSubRuleZone.Service.Add(_cpObjects.GetObject(CheckPointObject.Any)); + + cpRuleLayer.Rules.Add(cpSubRuleZone); + } + + bool isIntfContainsAny = false; + + foreach (FgCommand fgCommandE in fgCommandsList) + { + if (fgCommandE.GetType() == typeof(FgCommand_Edit)) + { + FgCommand_Edit fgCommand_Edit = (FgCommand_Edit)fgCommandE; + + var cpRule = new CheckPoint_Rule(); + + cpRule.ConversionComments = "Matched rule " + fgCommand_Edit.Table; + + string[] fgSrcIntfs = new string[]{}; + string[] fgDstIntfs = new string[]{}; + + cpRule.Track = CheckPoint_Rule.TrackTypes.Log; + + List errorsList = new List(); + + bool isNatEnabled = false; + bool isIpPoolEnabled = false; + + List fgDstAddrList = new List(); + + List cpUsersGroupsList = new List(); + + foreach (FgCommand fgCommandS in fgCommand_Edit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommand_Set = (FgCommand_Set)fgCommandS; + + if(fgCommand_Set.Field.Equals("name")) + { + cpRule.Name = GetSafeName(fgCommand_Set.Value); + } + + if (fgCommand_Set.Field.Equals("action") && fgCommand_Set.Value.Equals("accept") && (cpRule.Action == CheckPoint_Rule.ActionType.Drop)) + { + cpRule.Action = CheckPoint_Rule.ActionType.Accept; + } + + if (fgCommand_Set.Field.Equals("status") && fgCommand_Set.Value.Trim().ToLower().Equals("disable")) + { + cpRule.Enabled = false; + } + + if (fgCommand_Set.Field.Equals("learning-mode") && fgCommand_Set.Value.Equals("enable")) + { + 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) + { + isIntfContainsAny = true; + } + } + + if (fgCommand_Set.Field.Equals("dstintf")) + { + fgDstIntfs = fgCommand_Set.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + + if (Array.IndexOf(fgDstIntfs.Select(s => s.ToLowerInvariant()).ToArray(), "any") > -1) + { + isIntfContainsAny = true; + } + } + + if (fgCommand_Set.Field.Equals("srcaddr")) + { + if (fgCommand_Set.Value.Equals("all")) + { + cpRule.Source.Add(_cpObjects.GetObject(CheckPointObject.Any)); + } + else + { + List list = fgCommand_Set.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToList(); + foreach (string str in list) + { + string name = str.Trim('"'); + + bool isAdded = false; + + string[] fgPrefixes = new string[] + { + FG_PREFIX_KEY_firewall_address, + FG_PREFIX_KEY_firewall_addrgrp, + FG_PREFIX_KEY_firewall_vip_extip, + FG_PREFIX_KEY_firewall_vip_grp + }; + + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + name)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + name]; + + foreach (CheckPointObject cpObj in cpObjsList) + { + cpRule.Source.Add(cpObj); + isAdded = true; + if (OptimizeConf) + { + AddCheckPointObject(cpObj); + } + } + } + } + + if(!isAdded) + { + errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'srcaddr' field with non-existing reference to: " + name + " and was not created."); + } + } + } + } + + if (fgCommand_Set.Field.Equals("dstaddr")) + { + if (fgCommand_Set.Value.Equals("all")) + { + cpRule.Destination.Add(_cpObjects.GetObject(CheckPointObject.Any)); + fgDstAddrList.Add("all"); + } + else + { + List list = fgCommand_Set.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToList(); + foreach (string str in list) + { + string name = str.Trim('"'); + + bool isAdded = false; + + string[] fgPrefixes = new string[] + { + FG_PREFIX_KEY_firewall_address, + FG_PREFIX_KEY_firewall_addrgrp, + FG_PREFIX_KEY_firewall_vip_extip, + FG_PREFIX_KEY_firewall_vip_grp + }; + + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + name)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + name]; + + foreach (CheckPointObject cpObj in cpObjsList) + { + cpRule.Destination.Add(cpObj); + isAdded = true; + if (OptimizeConf) + { + AddCheckPointObject(cpObj); + } + } + } + } + + if(!isAdded) + { + errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'dstaddr' field with non-existing reference to: " + name + " and was not created."); + } + + fgDstAddrList.Add(name); + } + } + } + + if (fgCommand_Set.Field.Equals("internet-service") && fgCommand_Set.Value.Equals("enable")) + { + errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'internet-service' field as destination" + " and was not created."); + } + + if (fgCommand_Set.Field.Equals("internet-service-id")) + { + errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'internet-service' field with " + fgCommand_Set.Value + " id" + " and was not created."); + } + if (fgCommand_Set.Field.Equals("schedule")) + { + string fgScheduleRule = fgCommand_Set.Value.Trim('"'); + + bool isAdded = false; + + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_schedule_recurring, FG_PREFIX_KEY_firewall_schedule_onetime, FG_PREFIX_KEY_firewall_schedule_group }; + + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgScheduleRule)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgScheduleRule]; + foreach(CheckPointObject cpObj in cpObjsList) { + cpRule.Time.Add(cpObj); + if (OptimizeConf) + { + AddCheckPointObject(cpObj); + } + isAdded = true; + } + } + } + + if(!isAdded) + { + errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'schedule' field with unrecognized value: " + fgScheduleRule + " and was not created"); + } + } + if (fgCommand_Set.Field.Equals("service")) + { + string[] fgServicesNames = fgCommand_Set.Value.Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + foreach (string fgServiceName in fgServicesNames) + { + string fgSrvName = fgServiceName.Trim('"'); + + if (fgSrvName.ToUpper().Equals("ALL")) + { + cpRule.Service.Add(_cpObjects.GetObject(CheckPointObject.Any)); + } + else + { + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_service_custom, FG_PREFIX_KEY_firewall_service_group }; + + bool isAdded = false; + + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgSrvName)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgSrvName]; + foreach (CheckPointObject cpObj in cpObjsList) + { + cpRule.Service.Add(cpObj); + if (OptimizeConf) + { + AddCheckPointObject(cpObj); + } + isAdded = true; + } + } + } + + if (!isAdded) + { + errorsList.Add("policy rule " + fgCommand_Edit.Table + " contains 'service' field with unrecognized value: " + fgSrvName + " and was not created"); + } + } + } + } + + if (fgCommand_Set.Field.Equals("groups")) + { + string[] fgGroups = fgCommand_Set.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + + foreach (string fgGroup in fgGroups) + { + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_user_group + fgGroup)) + { + List cpObjsList = _localMapperFgCp[FG_PREFIX_KEY_user_group + fgGroup]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + cpUsersGroupsList.AddRange(cpObjsList); + } + } + } + } + + if (fgCommand_Set.Field.Equals("logtraffic") && fgCommand_Set.Value.Equals("disable")) + { + cpRule.Track = CheckPoint_Rule.TrackTypes.None; + } + + if (fgCommand_Set.Field.Equals("comment") || fgCommand_Set.Field.Equals("comments")) + { + cpRule.Comments = fgCommand_Set.Value; + } + + if (fgCommand_Set.Field.Equals("nat") && fgCommand_Set.Value.Equals("enable")) + { + isNatEnabled = true; + } + + if (fgCommand_Set.Field.Equals("ippool") && fgCommand_Set.Value.Equals("enable")) + { + isIpPoolEnabled = true; + } + } + } + + if (errorsList.Count == 0) + { + CheckPoint_Layer rootLayer = null; + + string rootLayerName = ""; + + List fgSrcIntfsList = new List(); + List fgDstIntfsList = new List(); + + foreach (string fgSrcIntf in fgSrcIntfs) + { + string fgSrcIntf_Appendix = ""; + + if (_intfAliasNamesMapper.ContainsKey(fgSrcIntf)) + { + fgSrcIntf_Appendix = _intfAliasNamesMapper[fgSrcIntf] + "_"; + } + + rootLayerName += fgSrcIntf_Appendix + fgSrcIntf + "_"; + + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_system_zone + fgSrcIntf)) + { + fgSrcIntfsList.AddRange(_localMapperFgCp[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]); + } + else + { + CheckPoint_Zone cpZoneSrc = new CheckPoint_Zone(); + cpZoneSrc.Name = GetSafeName(fgSrcIntf_Appendix + fgSrcIntf); + + string warnMessage = CheckZoneForReservedWords(cpZoneSrc); + if(warnMessage != null) + { + extraZonesWarnMsgsList.Add(warnMessage); + } + + fgSrcIntfsList.Add(cpZoneSrc); + + extraZonesMap.Add(FG_PREFIX_KEY_system_zone + fgSrcIntf, cpZoneSrc); + } + } + + rootLayerName += "_"; + + foreach (string fgDstIntf in fgDstIntfs) + { + string fgDstIntf_Appendix = ""; + + if (_intfAliasNamesMapper.ContainsKey(fgDstIntf)) + { + fgDstIntf_Appendix = _intfAliasNamesMapper[fgDstIntf] + "_"; + } + + rootLayerName += fgDstIntf_Appendix + fgDstIntf + "_"; + + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_system_zone + fgDstIntf)) + { + fgDstIntfsList.AddRange(_localMapperFgCp[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]); + } + else + { + CheckPoint_Zone cpZoneDst = new CheckPoint_Zone(); + cpZoneDst.Name = GetSafeName(fgDstIntf_Appendix + fgDstIntf); + + string warnMessage = CheckZoneForReservedWords(cpZoneDst); + if (warnMessage != null) + { + extraZonesWarnMsgsList.Add(warnMessage); + } + + fgDstIntfsList.Add(cpZoneDst); + + extraZonesMap.Add(FG_PREFIX_KEY_system_zone + fgDstIntf, cpZoneDst); + } + } + + rootLayerName = GetSafeName(rootLayerName.Substring(0, (rootLayerName.Length - 1))); + + //--- + + if (rootLayersMap.ContainsKey(rootLayerName)) + { + rootLayer = rootLayersMap[rootLayerName]; + } + else + { + CheckPoint_Rule rootRule = new CheckPoint_Rule(); + rootRule.Name = rootLayerName; + rootRule.Layer = package.NameOfAccessLayer; + rootRule.Source.AddRange(fgSrcIntfsList); + rootRule.Destination.AddRange(fgDstIntfsList); + rootRule.Action = CheckPoint_Rule.ActionType.SubPolicy; + rootRule.Track = CheckPoint_Rule.TrackTypes.Log; + rootRule.Time.Add(_cpObjects.GetObject(CheckPointObject.Any)); + rootRule.Service.Add(_cpObjects.GetObject(CheckPointObject.Any)); + rootRule.SubPolicyName = rootLayerName; + + rootRulesList.Add(rootRule); + + rootLayer = new CheckPoint_Layer(); + rootLayer.Name = rootLayerName; + + rootLayersMap.Add(rootLayerName, rootLayer); + } + + cpRule.Layer = rootLayer.Name; + + //add rule for Users Groups + + CheckPoint_Rule cpRuleUG = null; + + if (cpUsersGroupsList.Count > 0) + { + cpRuleUG = cpRule.Clone(); + cpRuleUG.Name += "_UG"; + cpRuleUG.Source.Clear(); + cpRuleUG.Source.AddRange(cpUsersGroupsList); + + cpRule.Enabled = false; + cpRule.Comments = "Disabled for reason it is replaced by the same rule with Users Groups"; + + } + + rootLayer.Rules.Add(cpRule); + realRulesList.Add(cpRule); + + _rulesInConvertedPackage += 1; + + if (cpRuleUG != null) + { + rootLayer.Rules.Add(cpRuleUG); + + _rulesInConvertedPackage += 1; + } + + rootLayersMap[rootLayer.Name] = rootLayer; + + //NAT conversion reagrding design which is described in other doc + + if(convertNat) + { + int counterNatRules = -1; + + foreach (string fgDstAddr in fgDstAddrList) + { + if (isNatEnabled) + { + 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)) + { + CheckPoint_NetworkGroup cpVipGrp = (CheckPoint_NetworkGroup)cpVipGrpI; + + List cpVipMembersOrig = GetVipGroupMembers(fgDstAddr); + + foreach (string cpVipI in cpVipMembersOrig) + { + 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); + } + } + } + } + } + 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); + } + else if (isIpPoolEnabled) + { + counterNatRules = AddNatRuleIpPool(fgCommand_Edit, fgDstAddr, counterNatRules); + } + else + { + counterNatRules = AddNatRuleSimple(fgCommand_Edit, fgDstAddr, counterNatRules); + } + } + else + { + 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)) + { + CheckPoint_NetworkGroup cpVipGrp = (CheckPoint_NetworkGroup)cpVipGrpI; + + List cpVipMembersOrig = GetVipGroupMembers(fgDstAddr); + + foreach (string cpVipI in cpVipMembersOrig) + { + if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + cpVipI) || + _localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + cpVipI)) + { + counterNatRules = AddNatRuleVipNatDisable(fgCommand_Edit, cpVipI, counterNatRules); + } + } + } + } + } + else if (_localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_extip + fgDstAddr) || + _localMapperFgCp.ContainsKey(FG_PREFIX_KEY_firewall_vip_mappedip + fgDstAddr)) + { + counterNatRules = AddNatRuleVipNatDisable(fgCommand_Edit, fgDstAddr, counterNatRules); + } + } + } + } + } + else + { + + foreach(string error in errorsList) + { + _errorsList.Add(error); + } + } + } + } + + //if Src or Dst Intf DO NOT contain ANY then we create sub-layers + //otherwise policy is plain + if (!isIntfContainsAny) + { + package.ParentLayer.Rules.AddRange(rootRulesList); + + foreach (string key in extraZonesMap.Keys) + { + AddCpObjectToLocalMapper(key, extraZonesMap[key]); + AddCheckPointObject(extraZonesMap[key]); + } + + _warningsList.AddRange(extraZonesWarnMsgsList); + + foreach (string key in rootLayersMap.Keys) + { + CheckPoint_Layer cpLayer = rootLayersMap[key]; + + CheckPoint_Rule cpRuleCU = new CheckPoint_Rule(); + cpRuleCU.Name = "Sub-Policy Cleanup"; + cpRuleCU.Layer = cpLayer.Name; + + cpLayer.Rules.Add(cpRuleCU); + + package.SubPolicies.Add(cpLayer); + } + } + else + { + foreach (CheckPoint_Rule ruleAdd in realRulesList) + { + ruleAdd.Layer = package.ParentLayer.Name; + package.ParentLayer.Rules.Add(ruleAdd); + } + } + + var cpRuleFake = new CheckPoint_Rule(); + cpRuleFake.Name = "Cleanup rule"; //the last rule which is created by default by CheckPoint script importer. It is for report only. + package.ParentLayer.Rules.Add(cpRuleFake); + } + + #endregion + + #region Converting NATs + + public List GetFgSrcAddrsList(FgCommand_Set fgCommandSet) + { + List fgSrcAddrsList = new List(); + + string[] fgSrcAddrsNames = fgCommandSet.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToArray(); + foreach (string fgSrcAddrName in fgSrcAddrsNames) + { + string fgSrcAddr = fgSrcAddrName.Trim('"'); + + if (fgSrcAddr.ToLower().Equals("all")) + { + fgSrcAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); + continue; + } + + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_address, FG_PREFIX_KEY_firewall_addrgrp }; + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgSrcAddr)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgSrcAddr]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + fgSrcAddrsList.AddRange(cpObjsList); + } + } + } + } + + return fgSrcAddrsList; + } + + public List GetFgDstAddrsAsVipExtIpList(string fgDstAddr) + { + List fgDstAddrsList = new List(); + + if (fgDstAddr.ToLower().Equals("all")) + { + fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); + } + else + { + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_vip_extip }; + + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + fgDstAddrsList.AddRange(cpObjsList); + } + } + } + } + + return fgDstAddrsList; + } + + public List GetFgDstAddrsAsVipMappedIpList(string fgDstAddr) + { + List fgDstAddrsList = new List(); + + if (fgDstAddr.ToLower().Equals("all")) + { + fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); + } + else + { + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_vip_mappedip }; + + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + fgDstAddrsList.AddRange(cpObjsList); + } + } + } + } + + return fgDstAddrsList; + } + + public List GetFgDstAddrToOSAsVipExtIpList(string fgDstAddr) + { + List fgDstAddrsList = new List(); + + if (fgDstAddr.Equals("all")) + { + fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); + } + else + { + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_service_custom_vipe_ }; + + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + fgDstAddrsList.AddRange(cpObjsList); + } + } + } + } + + return fgDstAddrsList; + } + + public List GetFgDstAddrToOSAsVipMapIpList(string fgDstAddr) + { + List fgDstAddrsList = new List(); + if (fgDstAddr.Equals("all")) + { + fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); + } + else + { + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_service_custom_vipm_ }; + + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + fgDstAddrsList.AddRange(cpObjsList); + } + } + } + } + + return fgDstAddrsList; + } + + public List GetFgServicesList(FgCommand_Set fgCommandSet) + { + List fgServicesList = new List(); + + List fgServicesNames = fgCommandSet.Value.Trim('"').Split(new string[] { "\" \"" }, StringSplitOptions.None).ToList(); + for(int i = 0; i < fgServicesNames.Count; i++) + { + string fgServiceName = fgServicesNames[i]; + + string fgSrvName = fgServiceName.Trim('"'); + + if (fgSrvName.ToLower().Equals("all")) + { + fgServicesList.Add(_cpObjects.GetObject(CheckPointObject.Any)); + continue; + } + + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_service_custom, FG_PREFIX_KEY_firewall_service_group }; + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgSrvName)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgSrvName]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + foreach (CheckPointObject cpObj in cpObjsList) + { + //to skip illegal services for NAT + //--- + // 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)) || + (cpObj.GetType() == typeof(CheckPoint_OtherService))) + { + continue; + } + + if (cpObj.GetType() == typeof(CheckPoint_ServiceGroup)) + { + CheckPoint_ServiceGroup cpServGrp = (CheckPoint_ServiceGroup)cpObj; + foreach (string member in cpServGrp.Members) + { + if (!fgServicesNames.Contains(member)) + { + fgServicesNames.Add(member); + } + } + continue; + } + fgServicesList.Add(cpObj); + } + } + } + } + } + + return fgServicesList; + } + + public int AddNatRuleSimple(FgCommand_Edit fgCommandEdit, string fgDstAddr, int counterNatRules) + { + string cpNatRuleId = fgCommandEdit.Table; + string cpNatRuleName = ""; + + string cpNatRuleComments = ""; + bool isNatEnable = true; + + List fgDstIntfsList = new List(); + + List fgSrcAddrsList = new List(); + + List fgDstAddrsList = new List(); + + if (fgDstAddr.Equals("all")) + { + fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); + } + else + { + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_address, FG_PREFIX_KEY_firewall_addrgrp }; + + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + fgDstAddrsList.AddRange(cpObjsList); + } + } + } + } + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("name")) + { + cpNatRuleName = fgCommandSet.Value.Trim('"'); + } + if (fgCommandSet.Field.Equals("dstintf")) + { + 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 + { + if (fgDstAddr.Equals("all")) + { + continue; //don't process "all" for FG dstaddr because we can't route for "all" addresses + } + if(fgDstAddrsList.Count != 1) + { + continue; //don't process "multi" FG objects + } + + //get destaddr Object to get its IP address + string fgDstAddrChecking = null; + CheckPointObject checkPointObject = fgDstAddrsList[0]; + + if(checkPointObject.GetType() == typeof(CheckPoint_Range)) + { + fgDstAddrChecking = ((CheckPoint_Range)checkPointObject).RangeFrom; + } + else if (checkPointObject.GetType() == typeof(CheckPoint_Host)) + { + fgDstAddrChecking = ((CheckPoint_Host)checkPointObject).IpAddress; + } + else if (checkPointObject.GetType() == typeof(CheckPoint_Network)) + { + fgDstAddrChecking = ((CheckPoint_Network)checkPointObject).Subnet; + } + if (fgDstAddrChecking == null) + { + continue; + } + IPAddress ipaddress = IPAddress.Parse(fgDstAddrChecking); + //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) + { + fgDstIntfsList.AddRange(cpObjsList); + } + //if Zone contains multi Interface: we should to check: + // 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) + { + string intfName = null; + int netCidr = -1; + string intfNameDefault = null; + string zoneName = fgCommandSet.Value.Trim('"').Trim(); + foreach (string interfaceNameFg in _localFgZoneIntfDict[zoneName]) //check each interface in Zone + { + if (_interfacesFgDict.ContainsKey(interfaceNameFg)) + { + 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 + { + intfName = interfaceNameFg; + netCidr = ipnetwork.Cidr; + } + } + + if (_localFgRoutesDict.ContainsKey(interfaceNameFg)) //check static route + { + foreach (FgStaticRoute fgStaticRoute in _localFgRoutesDict[interfaceNameFg]) + { + if(fgStaticRoute.Network.Equals("0.0.0.0") && intfNameDefault == null) + { + intfNameDefault = fgStaticRoute.Device; + continue; + } + IPNetwork ipnetwork = IPNetwork.Parse(fgStaticRoute.Network, fgStaticRoute.Mask); + if (IPNetwork.Contains(ipnetwork, ipaddress) && netCidr < ipnetwork.Cidr) + { + intfName = interfaceNameFg; + netCidr = ipnetwork.Cidr; + } + } + } + } + if (intfName == null) + { + intfName = intfNameDefault; + } + if(intfName != null) + { + if(_interfacesMapperFgCp.ContainsKey(intfName)) + { + fgDstIntfsList.AddRange(_interfacesMapperFgCp[intfName]); + } + } + } + } + } + + if (fgCommandSet.Field.Equals("srcaddr")) + { + fgSrcAddrsList.AddRange(GetFgSrcAddrsList(fgCommandSet)); + } + + if(fgCommandSet.Field.Equals("comments")) + { + cpNatRuleComments = fgCommandSet.Value.Trim('"'); + } + + if (fgCommandSet.Field.Equals("status") && fgCommandSet.Value.Equals("disable")) + { + isNatEnable = false; + } + } + } + foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) + { + foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) + { + //don't create NAT Rule for Domain objects + if(cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) + { + _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); + continue; + } + + foreach (CheckPointObject cpObjDstAddr in fgDstAddrsList) + { + //don't create NAT Rule for Domain objects + if (cpObjDstAddr.GetType() == typeof(CheckPoint_Domain)) + { + _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjDstAddr.Name + " domain object."); + continue; + } + + CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); + + cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); + cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; + + cpNatRule.Comments += cpNatRuleComments; + cpNatRule.Enabled = isNatEnable; + + cpNatRule.Source = cpObjSrcAddr; + cpNatRule.Destination = cpObjDstAddr; + cpNatRule.Service = _cpObjects.GetObject(CheckPointObject.Any); // we change all nat hide rules service field to Any for simplicity + cpNatRule.TranslatedSource = cpObjDstIntf; + cpNatRule.TranslatedDestination = null; + cpNatRule.TranslatedService = null; + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; + + _cpNatRules.Add(cpNatRule); + _rulesInNatLayer += 1; + + if (OptimizeConf) + { + _cpObjects.AddObject(cpObjSrcAddr); + _cpObjects.AddObject(cpObjDstAddr); + _cpObjects.AddObject(cpObjDstIntf); + } + } + } + } + return counterNatRules; + } + + public int AddNatRuleIpPool(FgCommand_Edit fgCommandEdit, string fgDstAddr, int counterNatRules) + { + string cpNatRuleId = fgCommandEdit.Table; + string cpNatRuleName = ""; + + string cpNatRuleComments = ""; + bool isNatEnable = true; + + List fgDstIntfsList = new List(); + + List fgSrcAddrsList = new List(); + List fgDstAddrsList = new List(); + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("name")) + { + cpNatRuleName = fgCommandSet.Value.Trim('"'); + } + + if (fgCommandSet.Field.Equals("poolname")) + { + string fgDstIntf = fgCommandSet.Value.Trim('"'); + + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_ippool }; + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstIntf)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgDstIntf]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + fgDstIntfsList.AddRange(cpObjsList); + } + } + } + } + + if (fgCommandSet.Field.Equals("srcaddr")) + { + fgSrcAddrsList.AddRange(GetFgSrcAddrsList(fgCommandSet)); + } + + if (fgCommandSet.Field.Equals("comments")) + { + cpNatRuleComments = fgCommandSet.Value.Trim('"'); + } + + if (fgCommandSet.Field.Equals("status") && fgCommandSet.Value.Equals("disable")) + { + isNatEnable = false; + } + } + } + + if (fgDstAddr.Equals("all")) + { + fgDstAddrsList.Add(_cpObjects.GetObject(CheckPointObject.Any)); + } + else + { + foreach (string fgPrefix in (new string[] { FG_PREFIX_KEY_firewall_address, FG_PREFIX_KEY_firewall_addrgrp })) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstAddr)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgDstAddr]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + fgDstAddrsList.AddRange(cpObjsList); + } + } + } + } + + foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) + { + foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) + { + //don't create NAT Rule for Domain objects + if (cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) + { + _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); + continue; + } + + foreach (CheckPointObject cpObjDstAddr in fgDstAddrsList) + { + //don't create NAT Rule for Domain objects + if (cpObjDstAddr.GetType() == typeof(CheckPoint_Domain)) + { + _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjDstAddr.Name + " Domain object."); + continue; + } + + CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); + + cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); + cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; + + cpNatRule.Comments += cpNatRuleComments; + cpNatRule.Enabled = isNatEnable; + + cpNatRule.Source = cpObjSrcAddr; + cpNatRule.Destination = cpObjDstAddr; + cpNatRule.Service = _cpObjects.GetObject(CheckPointObject.Any); // we change all nat hide rules service field to Any for simplicity + cpNatRule.TranslatedSource = cpObjDstIntf; + cpNatRule.TranslatedDestination = null; + cpNatRule.TranslatedService = null; + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; + + _cpNatRules.Add(cpNatRule); + _rulesInNatLayer += 1; + + if (OptimizeConf) + { + _cpObjects.AddObject(cpObjSrcAddr); + _cpObjects.AddObject(cpObjDstAddr); + _cpObjects.AddObject(cpObjDstIntf); + } + } + } + } + return counterNatRules; + } + + public int AddNatRuleVipNatEnable(FgCommand_Edit fgCommandEdit, string fgDstAddr, int counterNatRules) + { + string cpNatRuleId = fgCommandEdit.Table; + string cpNatRuleName = ""; + + string cpNatRuleComments = ""; + bool isNatEnable = true; + + bool isIpPoolEnabled = false; + + List fgDstIntfsList = new List(); + + List fgSrcAddrsList = new List(); + + List fgServicesList = new List(); + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("name")) + { + cpNatRuleName = fgCommandSet.Value.Trim('"'); + } + + if (fgCommandSet.Field.Equals("dstintf")) + { + if (!isIpPoolEnabled) + { + 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 + { + if (fgDstAddr.Equals("all")) + { + continue; //don't process "all" for FG dstaddr because we can't route for "all" addresses + } + + List fgDstAddrsList = new List(); + + fgDstAddrsList.AddRange(GetFgDstAddrsAsVipExtIpList(fgDstAddr)); + fgDstAddrsList.AddRange(GetFgDstAddrsAsVipMappedIpList(fgDstAddr)); + + if (fgDstAddrsList.Count != 1) + { + continue; //don't process "multi" FG objects + } + + //get destaddr Object to get its IP address + string fgDstAddrChecking = null; + CheckPointObject checkPointObject = fgDstAddrsList[0]; + + if (checkPointObject.GetType() == typeof(CheckPoint_Range)) + { + fgDstAddrChecking = ((CheckPoint_Range)checkPointObject).RangeFrom; + } + else if (checkPointObject.GetType() == typeof(CheckPoint_Host)) + { + fgDstAddrChecking = ((CheckPoint_Host)checkPointObject).IpAddress; + } + else if (checkPointObject.GetType() == typeof(CheckPoint_Network)) + { + fgDstAddrChecking = ((CheckPoint_Network)checkPointObject).Subnet; + } + if (fgDstAddrChecking == null) + { + continue; + } + IPAddress ipaddress = IPAddress.Parse(fgDstAddrChecking); + //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) + { + fgDstIntfsList.AddRange(cpObjsList); + } + //if Zone contains multi Interface: we should to check: + // 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) + { + string intfName = null; + int netCidr = -1; + string intfNameDefault = null; + string zoneName = fgCommandSet.Value.Trim('"').Trim(); + foreach (string interfaceNameFg in _localFgZoneIntfDict[zoneName]) //check each interface in Zone + { + if (_interfacesFgDict.ContainsKey(interfaceNameFg)) + { + 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 + { + intfName = interfaceNameFg; + netCidr = ipnetwork.Cidr; + } + } + + if (_localFgRoutesDict.ContainsKey(interfaceNameFg)) //check static route + { + foreach (FgStaticRoute fgStaticRoute in _localFgRoutesDict[interfaceNameFg]) + { + if (fgStaticRoute.Network.Equals("0.0.0.0") && intfNameDefault == null) + { + intfNameDefault = fgStaticRoute.Device; + continue; + } + IPNetwork ipnetwork = IPNetwork.Parse(fgStaticRoute.Network, fgStaticRoute.Mask); + if (IPNetwork.Contains(ipnetwork, ipaddress) && netCidr < ipnetwork.Cidr) + { + intfName = interfaceNameFg; + netCidr = ipnetwork.Cidr; + } + } + } + } + if (intfName == null) + { + intfName = intfNameDefault; + } + if (intfName != null) + { + if (_interfacesMapperFgCp.ContainsKey(intfName)) + { + fgDstIntfsList.AddRange(_interfacesMapperFgCp[intfName]); + } + } + } + } + } + } + + if (fgCommandSet.Field.Equals("srcaddr")) + { + fgSrcAddrsList.AddRange(GetFgSrcAddrsList(fgCommandSet)); + } + + if (fgCommandSet.Field.Equals("service")) + { + fgServicesList.AddRange(GetFgServicesList(fgCommandSet)); + } + + if (fgCommandSet.Field.Equals("comments")) + { + cpNatRuleComments = fgCommandSet.Value.Trim('"'); + } + + if (fgCommandSet.Field.Equals("status") && fgCommandSet.Value.Equals("disable")) + { + isNatEnable = false; + } + + if (fgCommandSet.Field.Equals("ippool") && fgCommandSet.Value.Equals("enable")) + { + isIpPoolEnabled = true; + } + + if (fgCommandSet.Field.Equals("poolname")) + { + string fgDstIntf = fgCommandSet.Value.Trim('"'); + + fgDstIntfsList.Clear(); + + string[] fgPrefixes = new string[] { FG_PREFIX_KEY_firewall_ippool }; + foreach (string fgPrefix in fgPrefixes) + { + if (_localMapperFgCp.ContainsKey(fgPrefix + fgDstIntf)) + { + List cpObjsList = _localMapperFgCp[fgPrefix + fgDstIntf]; + if (cpObjsList != null && cpObjsList.Count > 0) + { + fgDstIntfsList.AddRange(cpObjsList); + } + } + } + } + } + } + + if(isIpPoolEnabled) + { + foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) + { + foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) + { + //don't create NAT Rule for Domain objects + if (cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) + { + _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); + continue; + } + + List fgDstAddrsVipExtIpList = new List(); + List fgDstAddrsVipMappedIpList = new List(); + + fgDstAddrsVipExtIpList.AddRange(GetFgDstAddrsAsVipExtIpList(fgDstAddr)); + fgDstAddrsVipMappedIpList.AddRange(GetFgDstAddrsAsVipMappedIpList(fgDstAddr)); + + bool isPortForwardEnabled = false; + + if (_vipPortForwardEnabledMapper.ContainsKey(fgDstAddr)) + { + isPortForwardEnabled = _vipPortForwardEnabledMapper[fgDstAddr]; + } + + foreach (CheckPointObject cpObjDstAddrVipExtIp in fgDstAddrsVipExtIpList) + { + foreach (CheckPointObject cpObjDstAddrVipMappedIp in fgDstAddrsVipMappedIpList) + { + if (isPortForwardEnabled) + { + List listOrigSrv = GetFgDstAddrToOSAsVipExtIpList(fgDstAddr); + List listTransSrv = GetFgDstAddrToOSAsVipMapIpList(fgDstAddr); + foreach (CheckPointObject cpOrigSrv in listOrigSrv) + { + foreach (CheckPointObject cpTransSrv in listTransSrv) + { + CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); + + cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); + cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; + + cpNatRule.Comments += cpNatRuleComments; + cpNatRule.Enabled = isNatEnable; + + cpNatRule.Source = cpObjSrcAddr; + cpNatRule.Destination = cpObjDstAddrVipExtIp; + + cpNatRule.Service = cpOrigSrv; + + cpNatRule.TranslatedSource = cpObjDstIntf; + + cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; + + cpNatRule.TranslatedService = cpTransSrv; + + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; + + _cpNatRules.Add(cpNatRule); + + _rulesInNatLayer += 1; + + if (OptimizeConf) + { + _cpObjects.AddObject(cpObjSrcAddr); + _cpObjects.AddObject(cpObjDstAddrVipExtIp); + _cpObjects.AddObject(cpObjDstAddrVipMappedIp); + _cpObjects.AddObject(cpOrigSrv); + _cpObjects.AddObject(cpTransSrv); + _cpObjects.AddObject(cpObjDstIntf); + } + } + } + } + else + { + foreach (CheckPointObject cpObjSrv in fgServicesList) + { + CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); + + cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); + cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; + + cpNatRule.Comments += cpNatRuleComments; + cpNatRule.Enabled = isNatEnable; + + cpNatRule.Source = cpObjSrcAddr; + cpNatRule.Destination = cpObjDstAddrVipExtIp; + + cpNatRule.Service = cpObjSrv; + + cpNatRule.TranslatedSource = cpObjDstIntf; + cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; + + cpNatRule.TranslatedService = null; + + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; + + _cpNatRules.Add(cpNatRule); + _rulesInNatLayer += 1; + + if (OptimizeConf) + { + _cpObjects.AddObject(cpObjSrcAddr); + _cpObjects.AddObject(cpObjDstAddrVipExtIp); + _cpObjects.AddObject(cpObjDstAddrVipMappedIp); + _cpObjects.AddObject(cpObjSrv); + _cpObjects.AddObject(cpObjDstIntf); + } + } + } + } + } + } + } + } + else + { + foreach (CheckPointObject cpObjDstIntf in fgDstIntfsList) + { + foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) + { + //don't create NAT Rule for Domain objects + if (cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) + { + _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); + continue; + } + + List fgDstAddrsVipExtIpList = new List(); + List fgDstAddrsVipMappedIpList = new List(); + + fgDstAddrsVipExtIpList.AddRange(GetFgDstAddrsAsVipExtIpList(fgDstAddr)); + fgDstAddrsVipMappedIpList.AddRange(GetFgDstAddrsAsVipMappedIpList(fgDstAddr)); + + bool isPortForwardEnabled = false; + + if (_vipPortForwardEnabledMapper.ContainsKey(fgDstAddr)) + { + isPortForwardEnabled = _vipPortForwardEnabledMapper[fgDstAddr]; + } + + foreach (CheckPointObject cpObjDstAddrVipExtIp in fgDstAddrsVipExtIpList) + { + foreach (CheckPointObject cpObjDstAddrVipMappedIp in fgDstAddrsVipMappedIpList) + { + if (isPortForwardEnabled) + { + List listOrigSrv = GetFgDstAddrToOSAsVipExtIpList(fgDstAddr); + List listTransSrv = GetFgDstAddrToOSAsVipMapIpList(fgDstAddr); + foreach (CheckPointObject cpOrigSrv in listOrigSrv) + { + foreach (CheckPointObject cpTransSrv in listTransSrv) + { + CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); + + cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); + cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; + + cpNatRule.Comments += cpNatRuleComments; + cpNatRule.Enabled = isNatEnable; + + cpNatRule.Source = cpObjSrcAddr; + cpNatRule.Destination = cpObjDstAddrVipExtIp; + + cpNatRule.Service = cpOrigSrv; + + cpNatRule.TranslatedSource = cpObjDstIntf; + + cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; + + cpNatRule.TranslatedService = cpTransSrv; + + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; + + _cpNatRules.Add(cpNatRule); + + _rulesInNatLayer += 1; + + if (OptimizeConf) + { + _cpObjects.AddObject(cpObjSrcAddr); + _cpObjects.AddObject(cpObjDstAddrVipExtIp); + _cpObjects.AddObject(cpObjDstAddrVipMappedIp); + _cpObjects.AddObject(cpOrigSrv); + _cpObjects.AddObject(cpTransSrv); + } + } + } + } + else + { + foreach (CheckPointObject cpObjSrv in fgServicesList) + { + CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); + + cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); + cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; + + cpNatRule.Comments += cpNatRuleComments; + cpNatRule.Enabled = isNatEnable; + + cpNatRule.Source = cpObjSrcAddr; + cpNatRule.Destination = cpObjDstAddrVipExtIp; + + cpNatRule.Service = cpObjSrv; + + cpNatRule.TranslatedSource = cpObjDstIntf; + cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; + + cpNatRule.TranslatedService = null; + + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; + + _cpNatRules.Add(cpNatRule); + _rulesInNatLayer += 1; + + if (OptimizeConf) + { + _cpObjects.AddObject(cpObjSrcAddr); + _cpObjects.AddObject(cpObjDstAddrVipExtIp); + _cpObjects.AddObject(cpObjDstAddrVipMappedIp); + _cpObjects.AddObject(cpObjSrv); + } + } + } + } + } + } + } + } + return counterNatRules; + } + + public int AddNatRuleVipNatDisable(FgCommand_Edit fgCommandEdit, string fgDstAddr, int counterNatRules) + { + string cpNatRuleId = fgCommandEdit.Table; + string cpNatRuleName = ""; + + string cpNatRuleComments = ""; + bool isNatEnable = true; + + List fgSrcAddrsList = new List(); + + List fgServicesList = new List(); + + foreach (FgCommand fgCommandS in fgCommandEdit.SubCommandsList) + { + if (fgCommandS.GetType() == typeof(FgCommand_Set)) + { + FgCommand_Set fgCommandSet = (FgCommand_Set)fgCommandS; + + if (fgCommandSet.Field.Equals("name")) + { + cpNatRuleName = fgCommandSet.Value.Trim('"'); + } + + if (fgCommandSet.Field.Equals("srcaddr")) + { + fgSrcAddrsList.AddRange(GetFgSrcAddrsList(fgCommandSet)); + } + + if (fgCommandSet.Field.Equals("service")) + { + fgServicesList.AddRange(GetFgServicesList(fgCommandSet)); + } + + if (fgCommandSet.Field.Equals("comments")) + { + cpNatRuleComments = fgCommandSet.Value.Trim('"'); + } + + if (fgCommandSet.Field.Equals("status") && fgCommandSet.Value.Equals("disable")) + { + isNatEnable = false; + } + } + } + + foreach (CheckPointObject cpObjSrcAddr in fgSrcAddrsList) + { + //don't create NAT Rule for Domain objects + if (cpObjSrcAddr.GetType() == typeof(CheckPoint_Domain)) + { + _warningsList.Add("NAT rule with matched rule " + cpNatRuleId + " was not created for " + cpObjSrcAddr.Name + " domain object."); + continue; + } + + List fgDstAddrsVipExtIpList = new List(); + List fgDstAddrsVipMappedIpList = new List(); + + fgDstAddrsVipExtIpList.AddRange(GetFgDstAddrsAsVipExtIpList(fgDstAddr)); + fgDstAddrsVipMappedIpList.AddRange(GetFgDstAddrsAsVipMappedIpList(fgDstAddr)); + + bool isPortForwardEnabled = false; + + if (_vipPortForwardEnabledMapper.ContainsKey(fgDstAddr)) + { + isPortForwardEnabled = _vipPortForwardEnabledMapper[fgDstAddr]; + } + + foreach (CheckPointObject cpObjDstAddrVipExtIp in fgDstAddrsVipExtIpList) + { + foreach (CheckPointObject cpObjDstAddrVipMappedIp in fgDstAddrsVipMappedIpList) + { + if (isPortForwardEnabled) + { + List listOrigSrv = GetFgDstAddrToOSAsVipExtIpList(fgDstAddr); + List listTransSrv = GetFgDstAddrToOSAsVipMapIpList(fgDstAddr); + foreach (CheckPointObject cpOrigSrv in listOrigSrv) + { + foreach (CheckPointObject cpTransSrv in listTransSrv) + { + CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); + + cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); + cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; + + cpNatRule.Comments += cpNatRuleComments; + cpNatRule.Enabled = isNatEnable; + + cpNatRule.Source = cpObjSrcAddr; + cpNatRule.Destination = cpObjDstAddrVipExtIp; + + cpNatRule.Service = cpOrigSrv; + + cpNatRule.TranslatedSource = null; + + cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; + + cpNatRule.TranslatedService = cpTransSrv; + + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Static; + + _cpNatRules.Add(cpNatRule); + + _rulesInNatLayer += 1; + + if (OptimizeConf) + { + _cpObjects.AddObject(cpObjSrcAddr); + _cpObjects.AddObject(cpObjDstAddrVipExtIp); + _cpObjects.AddObject(cpObjDstAddrVipMappedIp); + _cpObjects.AddObject(cpOrigSrv); + _cpObjects.AddObject(cpTransSrv); + } + } + } + } + else { + foreach (CheckPointObject cpObjSrv in fgServicesList) + { + CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); + + cpNatRule.Name = GetSafeName(cpNatRuleName + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); + cpNatRule.Comments = "Matched rule ID: " + cpNatRuleId + ". "; + + cpNatRule.Comments += cpNatRuleComments; + cpNatRule.Enabled = isNatEnable; + + cpNatRule.Source = cpObjSrcAddr; + cpNatRule.Destination = cpObjDstAddrVipExtIp; + + cpNatRule.Service = cpObjSrv; + + cpNatRule.TranslatedSource = null; + cpNatRule.TranslatedDestination = cpObjDstAddrVipMappedIp; + + cpNatRule.TranslatedService = null; + + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Static; + + _cpNatRules.Add(cpNatRule); + _rulesInNatLayer += 1; + + if (OptimizeConf) + { + _cpObjects.AddObject(cpObjSrcAddr); + _cpObjects.AddObject(cpObjDstAddrVipExtIp); + _cpObjects.AddObject(cpObjDstAddrVipMappedIp); + _cpObjects.AddObject(cpObjSrv); + } + } + } + } + } + } + return counterNatRules; + } + + #endregion + + #region Converter Common methods + + //method checks if some part of Zone Name contains reservered word + // return null if not + // return message if yes + + public string CheckZoneForReservedWords(CheckPoint_Zone inZone) + { + string retMessage = null; + + string inZoneNameNew = ""; + + string[] inZoneNameParts = inZone.Name.Split('-').ToArray(); + + string[] reservedWords = new string[] + { + "all", "All", "and", "any", "Any", + "apr", "Apr", "april", "April", "aug", "Aug", "august", "August", + "black", "blackboxs", "blue", "broadcasts", "call", "comment", + "conn", "date", "day", "debug", "dec", "Dec", "december", "December", + "deffunc", "define", "delete", "delstate", "direction", "do", "domains", + "drop", "dst", "dynamic", "else", "expcall", "expires", "export", "fcall", + "feb", "Feb", "february", "February", "firebrick", "foreground", "forest", + "format", "fri", "Fri", "friday", "Friday", "from", "fw1", "FW1", "fwline", + "fwrule", "gateways", "get", "getstate", "gold", "gray", "green", "hashsize", + "hold", "host", "hosts", "if", "ifaddr", "ifid", "implies", "in", "inbound", + "instate", "interface", "interfaces", "ipsecdata", "ipsecmethods", "is", + "jan", "Jan", "january", "January", "jul", "Jul", "july", "July", "jun", + "Jun", "june", "June", "kbuf", "keep", "limit", "local", "localhost", "log", + "LOG", "logics", "magenta", "mar", "Mar", "march", "March", "may", "May", + "mday", "medium", "modify", "mon", "Mon", "monday", "Monday", "month", + "mortrap", "navy", "netof", "nets", "nexpires", "not", "nov", "Nov", + "november", "November", "oct", "Oct", "october", "October", "or", + "orange", "origdport", "origdst", "origsport", "origsrc", "other", + "outbound", "packet", "packetid", "packetlen", "pass", "r_arg", + "r_call_counter", "r_cdir", "r_cflags", "r_chandler", "r_client_community", + "r_client_ifs_grp", "r_community_left", "r_connarg", "r_crule", "r_ctimeout", + "r_ctype", "r_curr_feature_id", "r_data_offset", "r_dtmatch", "r_dtmflags", + "r_entry", "r_g_offset", "r_ipv6", "r_mapped_ip", "r_mflags", "r_mhandler", + "r_mtimeout", "r_oldcdir", "r_pflags", "r_profile_id", "r_ro_client_community", + "r_ro_dst_sr", "r_ro_server_community", "r_ro_src_sr", "r_scvres", + "r_server_community", "r_server_ifs_grp", "r_service_id", "r_simple_hdrlen", + "r_spii_ret", "r_spii_tcpseq", "r_spii_uuid1", "r_spii_uuid2", "r_spii_uuid3", + "r_spii_uuid4", "r_str_dport", "r_str_dst", "r_str_ipp", "r_str_sport", + "r_str_src", "r_user", "record", "red", "refresh", "reject", "routers", + "sat", "Sat", "saturday", "Saturday", "second", "sep", "Sep", "september", + "September", "set", "setstate", "skipme", "skippeer", "sr", "src", "static", + "sun", "Sun", "sunday", "Sunday", "switchs", "sync", "targets", "thu", "Thu", + "thursday", "Thursday", "to", "tod", "tue", "Tue", "tuesday", "Tuesday", "ufp", + "vanish", "vars", "wasskipped", "wed", "Wed", "wednesday", "Wednesday", + "while", "xlatedport", "xlatedst", "xlatemethod", "xlatesport", "xlatesrc", + "xor", "year", "zero", "zero_ip", "mon", "Mon", "monday", "Monday", "tue", + "Tue", "tuesday", "Tuesday", "wed", "Wed", "wednesday", "Wednesday", "thu", + "Thu", "thursday", "Thursday", "fri", "Fri", "friday", "Friday", "sat", "Sat", + "saturday", "Saturday", "sun", "Sun", "sunday", "Sunday", "jan", "Jan", + "january", "January", "feb", "Feb", "february", "February", "mar", "Mar", + "march", "March", "apr", "Apr", "april", "April", "may", "May", "jun", "Jun", + "june", "June", "jul", "Jul", "july", "July", "aug", "Aug", "august", "August", + "sep", "Sep", "september", "September", "oct", "Oct", "october", "October", + "nov", "Nov", "november", "November", "dec", "Dec", "december", "December", + "date", "day", "month", "year", "black", "blue", "cyan", "dark", "firebrick", + "foreground", "forest", "gold", "gray", "green", "magenta", "medium", "navy", + "orange", "red", "sienna", "yellow", "dark", "light", "medium" + }; + + foreach(string inZoneNamePart in inZoneNameParts) + { + if(reservedWords.Contains(inZoneNamePart)) + { + inZoneNameNew += "_" + inZoneNamePart; + } + else + { + if(!inZoneNameNew.Equals("")) + { + inZoneNameNew += "-"; + } + + inZoneNameNew += inZoneNamePart; + } + } + + if(!inZone.Name.Equals(inZoneNameNew)) + { + retMessage = inZone.Name + " zone was renamed to " + inZoneNameNew + " for solving 'reserved words' issue."; + inZone.Name = inZoneNameNew; + } + + return retMessage; + } + + public void AddCpObjectToLocalMapper(String fgObjectName, CheckPointObject cpObject) + { + List cpObjectsList = null; + if (_localMapperFgCp.ContainsKey(fgObjectName)) + { + cpObjectsList = _localMapperFgCp[fgObjectName]; + } + else + { + cpObjectsList = new List(); + } + + //check the name of Object + if(cpObject.GetType() == typeof(CheckPoint_TcpService)) + { + 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)) + { + if (!char.IsLetter(cpObject.Name, 0)) + { + string newName = "UDP_" + cpObject.Name; + _warningsList.Add(cpObject.Name + " udp-service was renamed to " + newName); + cpObject.Name = newName; + } + } + else if(cpObject.GetType() == typeof(CheckPoint_SctpService)) + { + 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)) + { + if (!char.IsLetter(cpObject.Name, 0)) + { + string newName = "ICMP_" + cpObject.Name; + _warningsList.Add(cpObject.Name + " icmp-service was renamed to " + newName); + cpObject.Name = newName; + } + } + else if (cpObject.GetType() == typeof(CheckPoint_OtherService)) + { + if (!char.IsLetter(cpObject.Name, 0)) + { + string newName = "OTHER_" + cpObject.Name; + _warningsList.Add(cpObject.Name + " other-service was renamed to " + newName); + cpObject.Name = newName; + } + } + else if(cpObject.GetType() == typeof(CheckPoint_Time)) + { + string cpTimeName = cpObject.Name; + + if (cpTimeName.Length > 11) + { + cpTimeName = cpTimeName.Substring(0, 6) + "_c" + _timeCutterCounter++; + } + + if (!cpTimeName.Equals(cpObject.Name)) + { + _warningsList.Add(cpObject.Name + " time object was renamed to " + cpTimeName); + cpObject.Name = cpTimeName; + } + } + else if(cpObject.GetType() == typeof(CheckPoint_TimeGroup)) + { + string cpTimeGrpName = cpObject.Name; + + if (cpTimeGrpName.Length > 11) + { + cpTimeGrpName = cpTimeGrpName.Substring(0, 6) + "_c" + _timeGroupCutterCounter++; + } + + if(!cpTimeGrpName.Equals(cpObject.Name)) + { + _warningsList.Add(cpObject.Name + " time group object was renamed to " + cpTimeGrpName); + cpObject.Name = cpTimeGrpName; + } + } + + bool isNameExist = true; + + int zIndex = 0; + + string cpObjectName = cpObject.Name; + + while (isNameExist) + { + isNameExist = false; + + foreach (CheckPointObject cpObj in cpObjectsList) + { + if (cpObj.Name.Trim().ToLower().Equals(cpObjectName.Trim().ToLower())) + { + isNameExist = true; + + zIndex += 1; + + cpObjectName = cpObject.Name + "_" + zIndex; + + break; + } + } + } + + if(!cpObject.Name.Equals(cpObjectName)) + { + _warningsList.Add(cpObject.Name + " object was renamed to " + cpObjectName + " for solving duplicate names issue."); + cpObject.Name = cpObjectName; + } + + cpObjectsList.Add(cpObject); + + _localMapperFgCp[fgObjectName] = cpObjectsList; + } + + #endregion + + public static string GetSafeName(string name) + { + if (name != null && !name.Trim().Equals("")) + { + return Regex.Replace(name, @"[^A-Za-z0-9_.-]", "_"); + } + else + { + return name; + } + } + + public List GetVipGroupMembers(string vipGrpName) + { + List retList = new List(); + + List vipGrpMembers = _localFgVipGrpsDict[vipGrpName]; + + foreach(string vipGrpMember in vipGrpMembers) + { + 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)) + { + retList.AddRange(GetVipGroupMembers(vipGrpMember)); + } + } + + return retList; + } + + protected override string GetVendorName() + { + return Vendor.FortiGate.ToString(); + } + } + + public class FgInterface + { + public string Name { get; set; } + public string Ip { get; set; } + public string Network { get; set; } + public string Mask { get; set; } + } + + public class FgStaticRoute + { + public string Name { get; set; } + public string Network { get; set; } + public string Mask { get; set; } + public string Gateway { get; set; } + public string Device { get; set; } + } +} diff --git a/JuniperMigration/JuniperConverter.cs b/JuniperMigration/JuniperConverter.cs index d7df2411..124b48e3 100644 --- a/JuniperMigration/JuniperConverter.cs +++ b/JuniperMigration/JuniperConverter.cs @@ -21,6 +21,7 @@ limitations under the License. using System.Linq; using System.Net; using System.Text; +using System.Globalization; using CheckPointObjects; using CommonUtils; using MigrationBase; @@ -33,20 +34,20 @@ namespace JuniperMigration /// public class JuniperConverter : VendorConverter { - #region Helper Classes - - private class DuplicateNameInfo - { - public bool IsJuniperApplicationFromTerm { get; set; } - public bool IsCPPredefinedName { get; private set; } - public List Zones { get; private set; } - - public DuplicateNameInfo(bool isCPPredefinedName) - { - IsJuniperApplicationFromTerm = false; - IsCPPredefinedName = isCPPredefinedName; - Zones = new List(); - } + #region Helper Classes + + private class DuplicateNameInfo + { + public bool IsJuniperApplicationFromTerm { get; set; } + public bool IsCPPredefinedName { get; private set; } + public List Zones { get; private set; } + + public DuplicateNameInfo(bool isCPPredefinedName) + { + IsJuniperApplicationFromTerm = false; + IsCPPredefinedName = isCPPredefinedName; + Zones = new List(); + } } private static class NetworkObjectNameGenerator @@ -156,8 +157,8 @@ public enum RulePriority #region Private Members - private JuniperParser _juniperParser; - + private JuniperParser _juniperParser; + private Dictionary _duplicateNamesLookup = new Dictionary(StringComparer.InvariantCultureIgnoreCase); private Dictionary _juniper2CheckpointServiceDuplicates = new Dictionary(); private Dictionary _juniperInvalidApplicationsReferences = new Dictionary(); @@ -189,20 +190,20 @@ private IEnumerable JuniperZonePolicies #endregion - #region Private Methods - - protected override bool AddCheckPointObject(CheckPointObject cpObject) - { - if (base.AddCheckPointObject(cpObject)) - { - string vendor = Vendor.JuniperJunosOS.ToString(); - if (!cpObject.Tags.Contains(vendor)) - { - cpObject.Tags.Add(vendor); - } - } - - return false; + #region Private Methods + + protected override bool AddCheckPointObject(CheckPointObject cpObject) + { + if (base.AddCheckPointObject(cpObject)) + { + string vendor = Vendor.JuniperJunosOS.ToString(); + if (!cpObject.Tags.Contains(vendor)) + { + cpObject.Tags.Add(vendor); + } + } + + return false; } private void Add_NetworkObjects() @@ -253,10 +254,10 @@ private void Add_NetworkObjects() } else { - AddCheckPointObject(cpHost); + AddCheckPointObject(cpHost); + } } } - } foreach (Juniper_Network network in _juniperParser.Filter("_Network")) { @@ -277,10 +278,10 @@ private void Add_NetworkObjects() } else { - AddCheckPointObject(cpNetwork); + AddCheckPointObject(cpNetwork); + } } } - } foreach (Juniper_Range range in _juniperParser.Filter("_Range")) { @@ -301,11 +302,11 @@ private void Add_NetworkObjects() } else { - AddCheckPointObject(cpRange); + AddCheckPointObject(cpRange); + } } - } } - + var groupsWithNonCreatedMembers = new List(); foreach (Juniper_AddressGroup group in _juniperParser.Filter("_AddressGroup")) @@ -318,23 +319,23 @@ private void Add_NetworkObjects() cpNetworkGroup.Tag = group.ZoneName; ApplyConversionIncidentOnCheckPointObject(cpNetworkGroup, group); inMultipleZones = IsNetworkObjectContainedInMultipleZones(cpNetworkGroup, group); - CheckObjectNameValidity(cpNetworkGroup, group, inMultipleZones); - - // Check if the member groups are already created to avoid "object not found" errors during the import to DB. - bool hasNonCreatedMembers = false; - if (!inMultipleZones) - { - foreach (var memberGroupName in group.MemberGroupNames) - { - bool found = _cpNetworkGroups.Any(cpGroup => cpGroup.Name == memberGroupName); - if (!found) - { - groupsWithNonCreatedMembers.Add(cpNetworkGroup); - hasNonCreatedMembers = true; - } - } - } - + CheckObjectNameValidity(cpNetworkGroup, group, inMultipleZones); + + // Check if the member groups are already created to avoid "object not found" errors during the import to DB. + bool hasNonCreatedMembers = false; + if (!inMultipleZones) + { + foreach (var memberGroupName in group.MemberGroupNames) + { + bool found = _cpNetworkGroups.Any(cpGroup => cpGroup.Name == memberGroupName); + if (!found) + { + groupsWithNonCreatedMembers.Add(cpNetworkGroup); + hasNonCreatedMembers = true; + } + } + } + if (!inMultipleZones && !hasNonCreatedMembers) { AddCheckPointObject(cpNetworkGroup); @@ -348,8 +349,8 @@ private void Add_NetworkObjects() string uniqueName = originalName + "_" + cpNetworkObject.Tag; // original name combined with the zone name cpNetworkObject.Name = uniqueName; // replace the original name with the unique one AddCheckPointObject(cpNetworkObject); - } - + } + // Add the network objects that have name duplication with zones names. foreach (var cpNetworkObject in networkAndZoneNamesDuplicates) { @@ -359,10 +360,10 @@ private void Add_NetworkObjects() AddCheckPointObject(cpNetworkObject); } - // After all groups are created, add the groups that had non created member groups. - foreach (var networkGroup in groupsWithNonCreatedMembers) - { - AddCheckPointObject(networkGroup); + // After all groups are created, add the groups that had non created member groups. + foreach (var networkGroup in groupsWithNonCreatedMembers) + { + AddCheckPointObject(networkGroup); } // Finally, search and update references in network groups, AFTER all objects are added. @@ -718,31 +719,247 @@ private void Add_ServiceObjects() cpServiceGroup.Members.AddRange(group.Members); cpServiceGroup.Members.AddRange(group.MemberGroupNames); ApplyConversionIncidentOnCheckPointObject(cpServiceGroup, group); - CheckObjectNameValidity(cpServiceGroup, group); - - // Check if the member groups are already created to avoid "object not found" errors during the import to DB. - bool hasNonCreatedMembers = false; - foreach (var memberGroupName in group.MemberGroupNames) - { - bool found = _cpServiceGroups.Any(cpGroup => cpGroup.Name == memberGroupName); - if (!found) - { - groupsWithNonCreatedMembers.Add(cpServiceGroup); - hasNonCreatedMembers = true; - } - } - - if (!hasNonCreatedMembers) - { - AddCheckPointObject(cpServiceGroup); - } - } - - // After all groups are created, add the groups that had non created member groups. - foreach (var serviceGroup in groupsWithNonCreatedMembers) - { - AddCheckPointObject(serviceGroup); + CheckObjectNameValidity(cpServiceGroup, group); + + // Check if the member groups are already created to avoid "object not found" errors during the import to DB. + bool hasNonCreatedMembers = false; + foreach (var memberGroupName in group.MemberGroupNames) + { + bool found = _cpServiceGroups.Any(cpGroup => cpGroup.Name == memberGroupName); + if (!found) + { + groupsWithNonCreatedMembers.Add(cpServiceGroup); + hasNonCreatedMembers = true; + } + } + + if (!hasNonCreatedMembers) + { + AddCheckPointObject(cpServiceGroup); + } + } + + // After all groups are created, add the groups that had non created member groups. + foreach (var serviceGroup in groupsWithNonCreatedMembers) + { + AddCheckPointObject(serviceGroup); + } + } + private void Add_Schedulers() + { + List cpTimeRangesNamesUniq = new List(); + foreach (Juniper_Scheduler scheduler in _juniperParser.Filter("_Scheduler")) + { + List timesList = new List();//will store time-objects for separate days with different hours-ranges + + int postfixIndex = 1;//postfix of time-object in case Juniper scheduler is split to several objects + + if (scheduler.StartStopDates.Count == 0) + {// check if time object has Start Time + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Comments = "Old Time Object name: " + scheduler.Name; + cpTime.StartNow = true; + cpTime.EndNever = true; + cpTime.Name = checkTimeNameLength(scheduler.Name, cpTimeRangesNamesUniq); + + Add_TimeObject(scheduler, cpTime, timesList, cpTimeRangesNamesUniq); + foreach (CheckPoint_Time time in timesList) + AddCheckPointObject(time); + } + else { + foreach (string sdate in scheduler.StartStopDates) //create separate time-object for each start-date + { + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Comments = "Old Time Object name: " + scheduler.Name; + //2020-09-06.01:01;2020-09-08.12:30 + if (scheduler.StartStopDates.Count == 1) + { + cpTime.Name = checkTimeNameLength(scheduler.Name, cpTimeRangesNamesUniq); + } + else + { + if (scheduler.Name.Length <= 8) + cpTime.Name = scheduler.Name + "_" + postfixIndex++; + else + { + cpTime.Name = scheduler.Name.Substring(0, 8) + "_" + postfixIndex++; + while (cpTimeRangesNamesUniq.Contains(cpTime.Name)) + { + cpTime.Name = scheduler.Name.Substring(0, 8) + "_" + postfixIndex++; + } + } + } + cpTime.StartNow = false; + DateTime date = DateTime.ParseExact(sdate.Substring(0, sdate.IndexOf(";")), "yyyy-MM-dd.HH:mm", CultureInfo.InvariantCulture); + cpTime.StartDate = date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture).Trim(); + cpTime.StartTime = date.ToString("HH:mm").Trim(); + + cpTime.EndNever = false; + date = DateTime.ParseExact(sdate.Substring(sdate.IndexOf(";") + 1), "yyyy-MM-dd.HH:mm", CultureInfo.InvariantCulture); + cpTime.EndDate = date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture).Trim(); + cpTime.EndTime = date.ToString("HH:mm").Trim(); + + Add_TimeObject(scheduler, cpTime, timesList, cpTimeRangesNamesUniq); + + foreach (CheckPoint_Time time in timesList) + AddCheckPointObject(time); + } + } + } + } + + /// + /// Check the length of time object name. + /// CheckPoint time object name is limited to 11 chars. In case it's more than 11 it's either truncated or truncated and completed with postfix so that to be unique. + /// + private string checkTimeNameLength(string timeName, List cpTimeRangesNamesUniq) + { + int postfixIndex = 1; + if (timeName.Length > 11) + { + timeName = timeName.Substring(0, 11); + while (cpTimeRangesNamesUniq.Contains(timeName)) + { + timeName = timeName.Substring(0, 8) + "_" + postfixIndex++; + } + return timeName; + } + else + { + return timeName; + } + } + + private List Add_TimeObject(Juniper_Scheduler scheduler, CheckPoint_Time cpTime, List timesList, List cpTimeRangesNamesUniq) + { + List daysList = new List { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" }; + + int postfixIndex = 1;//postfix of time-object in case Juniper scheduler is split to several objects + + bool dailyIsConfigured = false; + + bool daysAreAddedToPattern = false;//used for exclude statement. + //In case some day is excluded from the scheduler, RecurrencePattern is changed to weekly and all days except excluded day are added to RecurrenceWeekdays (need to be done once) + + if (scheduler.patternDictionary.Keys.Count != 0) + { + foreach (var day in scheduler.patternDictionary.Keys) + { + if (day.Equals("daily")) + { + dailyIsConfigured = true; + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Daily; + + processHoursRanges(scheduler.patternDictionary[day], cpTime); + + timesList.Add(cpTime); + cpTimeRangesNamesUniq.Add(cpTime.Name); + } + else + { + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Weekly; + + if (scheduler.patternDictionary[day][0].Equals("all-day")) + { + cpTime.RecurrenceWeekdays.Add((CheckPoint_Time.Weekdays)daysList.IndexOf(day)); + + timesList.Add(cpTime); + cpTimeRangesNamesUniq.Add(cpTime.Name); + } + else if (scheduler.patternDictionary[day][0].Equals("exclude")) + { + if (!daysAreAddedToPattern && dailyIsConfigured) + { + if (!cpTime.RecurrenceWeekdays.Contains(CheckPoint_Time.Weekdays.Sun)) + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Sun); + if (!cpTime.RecurrenceWeekdays.Contains(CheckPoint_Time.Weekdays.Mon)) + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Mon); + if (!cpTime.RecurrenceWeekdays.Contains(CheckPoint_Time.Weekdays.Tue)) + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Tue); + if (!cpTime.RecurrenceWeekdays.Contains(CheckPoint_Time.Weekdays.Wed)) + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Wed); + if (!cpTime.RecurrenceWeekdays.Contains(CheckPoint_Time.Weekdays.Thu)) + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Thu); + if (!cpTime.RecurrenceWeekdays.Contains(CheckPoint_Time.Weekdays.Fri)) + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Fri); + if (!cpTime.RecurrenceWeekdays.Contains(CheckPoint_Time.Weekdays.Sat)) + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Sat); + daysAreAddedToPattern = true; + } + cpTime.RecurrenceWeekdays.Remove((CheckPoint_Time.Weekdays)daysList.IndexOf(day)); + } + else + { + CheckPoint_Time cpTimeAdd = new CheckPoint_Time();//create separate time-object for each day in case hours ranges for day are set + + cpTimeAdd = cpTime.Clone(); + + cpTime.RecurrenceWeekdays.Remove((CheckPoint_Time.Weekdays)daysList.IndexOf(day));//remove day from the common TO because for this day separate TO is created + cpTimeAdd.RecurrenceWeekdays.Add((CheckPoint_Time.Weekdays)daysList.IndexOf(day)); + + if (cpTimeAdd.Name.Length <= 8) + cpTimeAdd.Name = cpTimeAdd.Name + "_" + postfixIndex++; + else + { + cpTimeAdd.Name = cpTimeAdd.Name.Substring(0, 8) + "_" + postfixIndex++; + while (cpTimeRangesNamesUniq.Contains(cpTimeAdd.Name)) + { + cpTimeAdd.Name = cpTimeAdd.Name.Substring(0, 8) + "_" + postfixIndex++; + } + } + + foreach (string timeRange in scheduler.patternDictionary[day]) + { + processHoursRanges(scheduler.patternDictionary[day], cpTimeAdd); + } + + timesList.Add(cpTimeAdd); + cpTimeRangesNamesUniq.Add(cpTimeAdd.Name); + } + } + } } + else + { + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.None; + timesList.Add(cpTime); + cpTimeRangesNamesUniq.Add(cpTime.Name); + } + + return timesList; + } + + /// + /// Convert Juniper scheduler start- and stop-time (in format HH:MM:SS) into CheckPoint hours-ranges parameter in required format (HH:MM) + /// + private void processHoursRanges(List timeRanges, CheckPoint_Time cpTime) + { + foreach (string timeRange in timeRanges) + { + if (timeRange.IndexOf(";") != -1) + { + string startTime = timeRange.Substring(0, timeRange.IndexOf(";")); + string stopTime = timeRange.Substring(timeRange.IndexOf(";") + 1); + + TimeSpan timeCheck0 = TimeSpan.ParseExact(startTime, "hh\\:mm\\:ss", CultureInfo.InvariantCulture); + TimeSpan timeCheck1 = TimeSpan.ParseExact(stopTime, "hh\\:mm\\:ss", CultureInfo.InvariantCulture); + + if (TimeSpan.Compare(timeCheck0, timeCheck1) == -1) + { + if (timeRanges.IndexOf(timeRange) == 0) + { + cpTime.HoursRangesEnabled_1 = true; + cpTime.HoursRangesFrom_1 = timeCheck0.ToString(@"hh\:mm").Trim(); + cpTime.HoursRangesTo_1 = timeCheck1.ToString(@"hh\:mm").Trim(); + } else + { + cpTime.HoursRangesEnabled_2 = true; + cpTime.HoursRangesFrom_2 = timeCheck0.ToString(@"hh\:mm").Trim(); + cpTime.HoursRangesTo_2 = timeCheck1.ToString(@"hh\:mm").Trim(); + } + } + } + } } private void Add_Package() @@ -864,7 +1081,7 @@ private void Add_Global_Rules(CheckPoint_Package package) { bool isZonelessGlobalRule = globalPolicyRule.SourceZones.Count == 1 && globalPolicyRule.SourceZones[0] == JuniperObject.Any && globalPolicyRule.DestinationZones.Count == 1 && globalPolicyRule.DestinationZones[0] == JuniperObject.Any; - if(isZonelessAllGlobalRules && !isZonelessGlobalRule) + if (isZonelessAllGlobalRules && !isZonelessGlobalRule) { isZonelessAllGlobalRules = false; } @@ -984,7 +1201,7 @@ private void Add_Global_Rules(CheckPoint_Package package) } } } - + // Append the global policy rules BELOW the existing sub-policies. bool isZonelessGlobalRule = globalPolicyRule.SourceZones.Count == 1 && globalPolicyRule.SourceZones[0] == JuniperObject.Any && globalPolicyRule.DestinationZones.Count == 1 && globalPolicyRule.DestinationZones[0] == JuniperObject.Any; @@ -1128,6 +1345,18 @@ private CheckPoint_Rule Juniper_To_CPRule(Juniper_PolicyRule juniperRule, string cpRule.Destination.Add(cpObject); } + + //add scheduler + foreach (var scheduler in juniperRule.Scheduler) + { + cpObject = GetCheckPointObjectOrCreateDummy(scheduler, + "Time", + juniperRule, + "Not applying time-range objects.", + "Appropriate time object should be added manually."); + cpRule.Time.Add(cpObject); + + } // Avoid general "icmp-proto" service duplicates bool hasGeneralIcmpService = false; @@ -1949,8 +2178,8 @@ private CheckPointObject GetNatSourceFromJuniperNatRule(Juniper_NatPolicy natPol // Create a network group object to wrap the network groups associated with source zones. var cpNetworkGroup = new CheckPoint_NetworkGroup(); - cpNetworkGroup.Name = NetworkObjectNameGenerator.AutoGeneratedNetworkGroupName(); - cpNetworkGroup.CreateAfterGroupsWithExclusion = true; + cpNetworkGroup.Name = NetworkObjectNameGenerator.AutoGeneratedNetworkGroupName(); + cpNetworkGroup.CreateAfterGroupsWithExclusion = true; foreach (var zoneName in natPolicy.SourceZones) { @@ -2157,8 +2386,8 @@ private CheckPointObject GetNatDestinationFromJuniperNatRule(Juniper_NatPolicy n // Create a network group object to hold the network groups associated with a destination zone. var cpNetworkGroup = new CheckPoint_NetworkGroup(); - cpNetworkGroup.Name = NetworkObjectNameGenerator.AutoGeneratedNetworkGroupName(); - cpNetworkGroup.CreateAfterGroupsWithExclusion = true; + cpNetworkGroup.Name = NetworkObjectNameGenerator.AutoGeneratedNetworkGroupName(); + cpNetworkGroup.CreateAfterGroupsWithExclusion = true; foreach (var zoneName in sourceNatPolicy.DestinationZones) { @@ -2335,7 +2564,7 @@ private CheckPointObject GetNatTranslatedSourceFromJuniperSourceNatPool(IEnumera translatedSource = GetCheckPointObjectFromJuniperNatPoolAddress(pool.Addresses[0]); if (translatedSource != null) { - translatedSource.Name = pool.Name; + translatedSource.Name = pool.Name; CheckObjectNameValidity(translatedSource, pool, false, true); AddCheckPointObject(translatedSource); @@ -2538,20 +2767,20 @@ private CheckPointObject GetCheckPointObjectFromJuniperNatAddress(Subnet address ((CheckPoint_Host)cpObject).IpAddress = address.IpAddress; } else - { - // This is very important, as SRX seems to have such Subnet usages... - if (address.Netmask == "0.0.0.0") - { - cpObject = new CheckPoint_Range(); - cpObject.Tag = "ANY_NETWORK"; // !!! - ((CheckPoint_Range)cpObject).RangeFrom = "0.0.0.0"; - ((CheckPoint_Range)cpObject).RangeTo = "255.255.255.255"; - } - else - { - cpObject = new CheckPoint_Network(); - ((CheckPoint_Network)cpObject).Subnet = address.IpAddress; - ((CheckPoint_Network)cpObject).Netmask = address.Netmask; + { + // This is very important, as SRX seems to have such Subnet usages... + if (address.Netmask == "0.0.0.0") + { + cpObject = new CheckPoint_Range(); + cpObject.Tag = "ANY_NETWORK"; // !!! + ((CheckPoint_Range)cpObject).RangeFrom = "0.0.0.0"; + ((CheckPoint_Range)cpObject).RangeTo = "255.255.255.255"; + } + else + { + cpObject = new CheckPoint_Network(); + ((CheckPoint_Network)cpObject).Subnet = address.IpAddress; + ((CheckPoint_Network)cpObject).Netmask = address.Netmask; } } @@ -3064,7 +3293,7 @@ private bool DoesJuniperApplicationMatchCheckpointPredefinedService(Juniper_Appl } private bool IsNetworkObjectReachableFromInterface(CheckPointObject cpObject, Juniper_Interface juniperInterface) - { + { if (cpObject.Name == CheckPointObject.Any || cpObject.Tag == "ANY_NETWORK") // !!! { return true; @@ -3202,11 +3431,11 @@ private void CheckObjectNameValidity(CheckPointObject cpObject, JuniperObject ju { string unsafeName = inMultipleZones ? (originalName + "_" + cpObject.Tag) : originalName; // this is important!!! _cpUnsafeNames.Add(unsafeName); - } - - if (safeNameOnly) - { - return; + } + + if (safeNameOnly) + { + return; } if (cpObject.GetType().ToString().EndsWith("_TcpService") || cpObject.GetType().ToString().EndsWith("_UdpService")) @@ -3225,61 +3454,61 @@ private void CheckObjectNameValidity(CheckPointObject cpObject, JuniperObject ju errorDescription, juniperObject.ConversionIncidentType)); } - } - + } + DuplicateNameInfo duplicateNameInfo; - if (_duplicateNamesLookup.TryGetValue(originalName, out duplicateNameInfo)) - { - if (inMultipleZones) - { - if (!duplicateNameInfo.Zones.Contains(cpObject.Tag)) - { - duplicateNameInfo.Zones.Add(cpObject.Tag); - _duplicateNamesLookup[originalName] = duplicateNameInfo; - return; - } - } - - if (duplicateNameInfo.IsJuniperApplicationFromTerm && juniperObject.GetType().ToString().EndsWith("_Application")) - { - var juniperApplication = (Juniper_Application)juniperObject; - if (juniperApplication.IsFromTerm) - { - // This is not a real duplicate... - return; - } - } - - juniperObject.ConversionIncidentType = ConversionIncidentType.ManualActionRequired; - - string errorTitle = duplicateNameInfo.IsCPPredefinedName - ? "Detected an object with a same name in Check Point's predefined service objects repository." - : "Detected an object with a non unique name. Check Point names should be case insensitive."; - errorTitle += " Please review for further possible modifications to object configuration before the final migration."; - - string errorDescription = string.Format("Object details: {0} [{1}].", originalName, juniperObject.GetType().ToString().Split('_')[1]); - - _conversionIncidents.Add(new ConversionIncident(juniperObject.LineNumber, errorTitle, errorDescription, juniperObject.ConversionIncidentType)); - } - else - { - duplicateNameInfo = new DuplicateNameInfo(false); - if (inMultipleZones) - { - duplicateNameInfo.Zones.Add(cpObject.Tag); - } - if (juniperObject.GetType().ToString().EndsWith("_Application")) - { - var juniperApplication = (Juniper_Application)juniperObject; - if (juniperApplication.IsFromTerm) - { - // In this case there may be several applications with the same name... - duplicateNameInfo.IsJuniperApplicationFromTerm = true; - } - } - - _duplicateNamesLookup.Add(originalName, duplicateNameInfo); - } + if (_duplicateNamesLookup.TryGetValue(originalName, out duplicateNameInfo)) + { + if (inMultipleZones) + { + if (!duplicateNameInfo.Zones.Contains(cpObject.Tag)) + { + duplicateNameInfo.Zones.Add(cpObject.Tag); + _duplicateNamesLookup[originalName] = duplicateNameInfo; + return; + } + } + + if (duplicateNameInfo.IsJuniperApplicationFromTerm && juniperObject.GetType().ToString().EndsWith("_Application")) + { + var juniperApplication = (Juniper_Application)juniperObject; + if (juniperApplication.IsFromTerm) + { + // This is not a real duplicate... + return; + } + } + + juniperObject.ConversionIncidentType = ConversionIncidentType.ManualActionRequired; + + string errorTitle = duplicateNameInfo.IsCPPredefinedName + ? "Detected an object with a same name in Check Point's predefined service objects repository." + : "Detected an object with a non unique name. Check Point names should be case insensitive."; + errorTitle += " Please review for further possible modifications to object configuration before the final migration."; + + string errorDescription = string.Format("Object details: {0} [{1}].", originalName, juniperObject.GetType().ToString().Split('_')[1]); + + _conversionIncidents.Add(new ConversionIncident(juniperObject.LineNumber, errorTitle, errorDescription, juniperObject.ConversionIncidentType)); + } + else + { + duplicateNameInfo = new DuplicateNameInfo(false); + if (inMultipleZones) + { + duplicateNameInfo.Zones.Add(cpObject.Tag); + } + if (juniperObject.GetType().ToString().EndsWith("_Application")) + { + var juniperApplication = (Juniper_Application)juniperObject; + if (juniperApplication.IsFromTerm) + { + // In this case there may be several applications with the same name... + duplicateNameInfo.IsJuniperApplicationFromTerm = true; + } + } + + _duplicateNamesLookup.Add(originalName, duplicateNameInfo); + } } private void AlertOnDomainNameModification(Juniper_Fqdn fqdn, bool inMultipleZones) @@ -3475,6 +3704,9 @@ private CheckPointObject GetCheckPointObjectOrCreateDummy(string cpObjectName, s cpDummyObject = new CheckPoint_ServiceGroup { Name = "_Err_in_service-line_" + juniperObject.LineNumber }; break; + case "Time": + cpDummyObject = new CheckPoint_Time { Name = cpObjectName}; + break; } if (cpDummyObject != null) @@ -3517,10 +3749,10 @@ public override void Convert(bool convertNat) _cpObjects.Initialize(); // must be first!!! foreach (var cpObject in _cpObjects.GetPredefinedObjects()) - { + { _duplicateNamesLookup.Add(cpObject.Name, new DuplicateNameInfo(true)); } - + Add_Schedulers(); Add_NetworkObjects(); Add_InterfacesAndRoutes(); Add_or_Modify_InterfaceNetworkGroups(); @@ -3560,6 +3792,8 @@ public override void Convert(bool convertNat) // Resolve the conversion categories/lines count to report to the user. ConversionIncidentCategoriesCount = _conversionIncidents.GroupBy(error => error.Title).Count(); ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); + + CreateSmartConnector(); } public override int RulesInConvertedPackage() @@ -3867,7 +4101,7 @@ public override void ExportPolicyPackagesAsHtml() file.WriteLine(" " + subRule.Comments + ""); file.WriteLine(" " + subRule.ConversionComments + ""); file.WriteLine(" "); - + if(isSubSubPolicy) { foreach (CheckPoint_Layer subSubPolicy in package.SubPolicies) diff --git a/JuniperMigration/JuniperMigration.csproj b/JuniperMigration/JuniperMigration.csproj index 496350fe..8618d860 100644 --- a/JuniperMigration/JuniperMigration.csproj +++ b/JuniperMigration/JuniperMigration.csproj @@ -31,7 +31,7 @@ - ..\..\..\CP_HUGO_1_CONV_TOOL\CPConversionTool_V_HUGO1\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/JuniperMigration/JuniperNameToNumber.csv b/JuniperMigration/JuniperNameToNumber.csv index f656c4bd..f84b985e 100644 --- a/JuniperMigration/JuniperNameToNumber.csv +++ b/JuniperMigration/JuniperNameToNumber.csv @@ -79,3 +79,5 @@ who,513 xdmcp,177 zephyr-clt,2103 zephyr-hm,2104 +junos-tcp-any,1-65535 +junos-udp-any,1-65535 diff --git a/JuniperMigration/JuniperObjects.cs b/JuniperMigration/JuniperObjects.cs index 17be58a9..baeab1f1 100644 --- a/JuniperMigration/JuniperObjects.cs +++ b/JuniperMigration/JuniperObjects.cs @@ -18,6 +18,7 @@ limitations under the License. using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; @@ -712,6 +713,62 @@ public override void Parse(XElement objectNode, string zoneName) } } } + + public class Juniper_Scheduler : JuniperObject + { + public List StartStopDates = new List(); + + public Dictionary> patternDictionary = new Dictionary>(); + + public override void Parse(XElement objectNode, string zoneName) + { + base.Parse(objectNode, zoneName); + + var startDates = objectNode.Elements("start-date").ToList(); + + if (startDates.Count > 0) + { + List startStop = new List(); + string startStopDateString; + foreach (var startDate in startDates) + { + startStopDateString = startDate.Element("start-date").Value + ";" + startDate.Element("stop-date").Value; + StartStopDates.Add(startStopDateString); + } + } + + List days = new List { "daily", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" }; + + foreach (string dayKey in days) + { + List daysValue = new List(); + var day = objectNode.Element(dayKey); + if (day != null) + { + if (day.Element("all-day") != null) + { + daysValue.Add("all-day"); + } + else if (day.Element("exclude") != null) + { + daysValue.Add("exclude"); + } + else if (day.Elements("start-time").ToList() != null) + { + List startStopTime = new List(); + string startStopTimeString; + foreach (var startTime in day.Elements("start-time").ToList()) + { + startStopTimeString = startTime.Element("start-time-value").Value + ";" + startTime.Element("stop-time").Value; + startStopTime.Add(startStopTimeString); + } + daysValue.AddRange(startStopTime); + } + patternDictionary.Add(dayKey, daysValue); + } + } + } + } public class Juniper_PolicyRule : JuniperObject { @@ -725,6 +782,8 @@ public enum ActionType { NA, Deny, Reject, Permit }; public bool DestinationNegate { get; set; } public bool Log { get; set; } public ActionType Action { get; set; } + public List Scheduler = new List(); + public override void Parse(XElement objectNode, string zoneName) { @@ -747,6 +806,16 @@ public override void Parse(XElement objectNode, string zoneName) Console.WriteLine(ConversionIncidentMessage); return; } + + //add scheduler + var schedulerNode = objectNode.Elements("scheduler-name"); + + if (schedulerNode != null) + { + foreach (var scheduler in schedulerNode) { + Scheduler.Add(scheduler.Value); + } + } var inactiveAttribute = objectNode.Attribute("inactive"); if (inactiveAttribute != null && inactiveAttribute.Value == "inactive") diff --git a/JuniperMigration/JuniperParser.cs b/JuniperMigration/JuniperParser.cs index 2c910d25..7170ac09 100644 --- a/JuniperMigration/JuniperParser.cs +++ b/JuniperMigration/JuniperParser.cs @@ -56,6 +56,7 @@ public override void Parse(string filename) ParseInterfaces(configNode); ParseRoutes(configNode); ParseApplicationsAndGroups(configNode); + parseSchedulers(configNode); ParsePolicy(configNode); ParseNat(configNode); AttachRoutesToInterfacesTopology(); @@ -384,6 +385,18 @@ private void ParseApplication(XElement application) _juniperObjects.Add(juniperObject); } } + + private void parseSchedulers(XElement configNode) + { + var schedulers = configNode.XPathSelectElements("./schedulers/scheduler"); + foreach (var scheduler in schedulers) + { + JuniperObject juniperScheduler = new Juniper_Scheduler(); + + juniperScheduler.Parse(scheduler, null); + _juniperObjects.Add(juniperScheduler); + } + } private void ParsePolicy(XElement configNode) { diff --git a/JuniperMigration/junos-defaults.xml b/JuniperMigration/junos-defaults.xml index 2845a1ac..3bdfa8ba 100644 --- a/JuniperMigration/junos-defaults.xml +++ b/JuniperMigration/junos-defaults.xml @@ -1509,7 +1509,7 @@ t1 tcp - 0 + 1-65535 # @@ -1520,7 +1520,7 @@ t1 udp - 0 + 1-65535 # diff --git a/MigrationBase/MigrationBase.csproj b/MigrationBase/MigrationBase.csproj index 73d585ae..6ddd4a87 100644 --- a/MigrationBase/MigrationBase.csproj +++ b/MigrationBase/MigrationBase.csproj @@ -30,6 +30,9 @@ 4 + + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + diff --git a/MigrationBase/SupportedVendors.cs b/MigrationBase/SupportedVendors.cs index 173b457a..c4af4a64 100644 --- a/MigrationBase/SupportedVendors.cs +++ b/MigrationBase/SupportedVendors.cs @@ -39,6 +39,9 @@ public class SupportedVendors public const string PaloAltoConfigurationFileLabel = "PaloAlto configuration file:"; public const string PaloAltoProduct = "PaloAlto PAN-OS to Check Point Migration Tool"; public const string PaloAltoProductDescription = "This tool supports migration of PaloAlto PAN-OS 7.x \nand above configuration files."; + public const string PaloAltoPanoramaConfigurationFileLabel = "PaloAlto Panorama configuration files archive:"; + public const string PaloAltoPanoramaProduct = "PaloAlto Panorama to Check Point Migration Tool"; + public const string PaloAltoPanoramaProductDescription = "This tool supports migration of PaloAlto Panorama 7.x \nand above configuration files."; #endregion @@ -72,6 +75,8 @@ public enum Vendor [Description("Fortinet FortiGate")] FortiGate, [Description("PaloAlto PAN-OS")] - PaloAlto + PaloAlto, + [Description("PaloAlto Panorama")] + PaloAltoPanorama } } diff --git a/MigrationBase/VendorConverter.cs b/MigrationBase/VendorConverter.cs index 4dd29563..27224b13 100644 --- a/MigrationBase/VendorConverter.cs +++ b/MigrationBase/VendorConverter.cs @@ -17,6 +17,7 @@ limitations under the License. using System; using System.Collections.Generic; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; @@ -24,6 +25,7 @@ limitations under the License. using System.Text.RegularExpressions; using CheckPointObjects; using CommonUtils; +using Newtonsoft.Json; namespace MigrationBase { @@ -38,6 +40,7 @@ public abstract class VendorConverter protected const string AllInternalNetwotkGroupName = "all_internal"; protected const string AutoGeneratedNameWithError = "_Err_"; protected const string InvalidServiceNamePrefix = "service_"; + protected const string GlobalRulesSubpolicyName = "Global Rules"; protected const string HtmlErrorImageTagFormat = ""; protected const string HtmlAlertImageTagFormat = ""; @@ -122,7 +125,7 @@ protected void RaiseConversionProgress(int progress, string title) ConversionProgress(progress, title); } } - + #endregion #region Methods @@ -216,7 +219,7 @@ public void CleanCheckPointObjectsLists() public abstract void ExportConfigurationAsHtml(); public abstract void ExportPolicyPackagesAsHtml(); protected abstract string GetVendorName(); - + #endregion public void ExportNatLayerAsHtml() @@ -305,7 +308,7 @@ public void ExportNatLayerAsHtml() // Generate the report body file.WriteLine(""); file.WriteLine(" "); - file.WriteLine(" "); + file.WriteLine(" "); file.WriteLine(" "); int ruleNumber = 1; @@ -458,6 +461,11 @@ public void ExportNatLayerAsHtml() file.WriteLine(curRuleHtmlPart); curRuleHtmlFull.Add(curRuleHtmlPart); + var dummy = ConversionIncidentType.None; + curRuleHtmlPart = " "; + file.WriteLine(curRuleHtmlPart); + curRuleHtmlFull.Add(curRuleHtmlPart); + curRuleHtmlPart = " "; file.WriteLine(curRuleHtmlPart); curRuleHtmlFull.Add(curRuleHtmlPart); @@ -499,7 +507,7 @@ public void ExportNatLayerAsHtml() file.WriteLine("

Conversion Errors

"); file.WriteLine("
No. Source Destination Service Translated-Source Translated-Destination Translated-Service CommentsNo. Source Destination Service Translated-Source Translated-Destination Translated-Service Install On Comments
" + RuleStringList2Html(rule.Target, false, CheckPointObject.All, ref dummy) + "" + rule.Comments + "
"); file.WriteLine(" "); - file.WriteLine(" "); + file.WriteLine(" "); file.WriteLine(" "); foreach (var ruleHtml in rulesWithConversionErrors) @@ -520,7 +528,7 @@ public void ExportNatLayerAsHtml() file.WriteLine("

Conversion Notifications

"); file.WriteLine("
No. Source Destination Service Translated-Source Translated-Destination Translated-Service CommentsNo. Source Destination Service Translated-Source Translated-Destination Translated-Service Install On Comments
"); file.WriteLine(" "); - file.WriteLine(" "); + file.WriteLine(" "); file.WriteLine(" "); foreach (var ruleHtml in rulesWithConversionInfos) @@ -534,7 +542,7 @@ public void ExportNatLayerAsHtml() file.WriteLine(""); file.WriteLine(""); } - + } protected virtual bool AddCheckPointObject(CheckPointObject cpObject) @@ -689,7 +697,7 @@ protected virtual bool AddCheckPointObject(CheckPointObject cpObject) { _cpObjects.AddObject(cpObject); - if (cpObject.Name.Contains(AutoGeneratedNameWithError)) + if (cpObject.Name != null && cpObject.Name.Contains(AutoGeneratedNameWithError)) { cpObject.ConversionIncidentType = ConversionIncidentType.ManualActionRequired; } @@ -733,7 +741,7 @@ protected List Add_or_Modify_InterfaceNetworkGroups(List= range1[0]) && (range2[0] <= range1[1])) || + if (((range2[0] >= range1[0]) && (range2[0] <= range1[1])) || ((range1[0] >= range2[0]) && (range1[0] <= range2[1]))) { if (range1[1] - range1[0] > range2[1] - range2[0]) @@ -1260,12 +1268,12 @@ protected void CreateObjectsScript() for (int i = 0; i < obj.Users.Count; i++) { var sb_set = new StringBuilder(); - + sb_set.Append("cmd='mgmt_cli ") .Append("set access-role ") .Append("name " + "\"" + obj.SafeName() + "\" "); - if(obj.Networks.Count == 0) + if (obj.Networks.Count == 0) { sb_set.Append("networks \"any\" "); } @@ -1279,7 +1287,7 @@ protected void CreateObjectsScript() .Append("users.add.selection." + i + " \"" + obj.Users[i].Name + "\" ") .Append(!(string.IsNullOrWhiteSpace(obj.Users[i].BaseDn)) ? "users.add.base-dn \"" + obj.Users[i].BaseDn + "\"" : "") .Append(" ignore-warnings true -s id.txt --user-agent mgmt_cli_smartmove'"); - + file.WriteLine(" " + sb_set.ToString()); file.WriteLine(" " + "run_command"); } @@ -1349,15 +1357,15 @@ protected void CreatePackagesScript() file.WriteLine(CLIScriptBuilder.GeneratePublishScript()); // Enabling Applications and URL Filtering in parent layer - if(package.ParentLayer.ApplicationsAndUrlFiltering) + if (package.ParentLayer.ApplicationsAndUrlFiltering) { file.WriteLine("echo 'Enabling Applications and URL Filtering in parent layer vsys1_policy Network'"); - file.WriteLine("cmd='mgmt_cli set access-layer " + - "name \"" + package.ParentLayer.Name + "\" " + - "applications-and-url-filtering \"true\" " + + file.WriteLine("cmd='mgmt_cli set access-layer " + + "name \"" + package.ParentLayer.Name + "\" " + + "applications-and-url-filtering \"true\" " + "ignore-warnings true -s id.txt --user-agent mgmt_cli_smartmove'"); file.WriteLine("run_command"); - file.WriteLine(CLIScriptBuilder.GeneratePublishScript()); + file.WriteLine(CLIScriptBuilder.GeneratePublishScript()); } file.WriteLine(CLIScriptBuilder.GenerateInstructionScript(string.Format("Add rules to parent layer {0}", package.NameOfAccessLayer))); // !!! Attention !!! -- the rules are created in the reverse order but will be inserted at the TOP (!!!) position, @@ -1580,7 +1588,7 @@ protected void CreateObjectsHtml() var sb_add = new StringBuilder(); sb_add.Append("add access-role ") .Append("name " + "\"" + obj.SafeName() + "\" "); - + if (obj.Networks.Count == 0) { sb_add.Append("networks \"any\" "); @@ -1600,7 +1608,7 @@ protected void CreateObjectsHtml() for (int i = 0; i < obj.Users.Count; i++) { file.WriteLine("
"); - + var sb_set = new StringBuilder(); sb_set.Append("set access-role ") .Append("name " + "\"" + obj.SafeName() + "\" "); @@ -1619,9 +1627,9 @@ protected void CreateObjectsHtml() .Append("users.add.selection." + i + " \"" + obj.Users[i].Name + "\" ") .Append(!(string.IsNullOrWhiteSpace(obj.Users[i].BaseDn)) ? "users.add.base-dn \"" + obj.Users[i].BaseDn + "\"" : ""); - + file.WriteLine(sb_set.ToString()); - + file.WriteLine("
"); } } @@ -1715,6 +1723,39 @@ protected string RuleItemsList2Html(List ruleItems, bool isCel return res; } + protected string RuleStringList2Html(List ruleString, bool isCellNegated, string defaultValue, ref ConversionIncidentType ruleConversionIncidentType) + { + if (ruleString.Count == 0) + { + return defaultValue; + } + + string res = ""; + + if (isCellNegated) + { + res += "
"; + res += "
Negated
"; + res += "
"; + } + + foreach (string item in ruleString) + { + if (_cpObjects.IsKnownService(item)) + { + res += "
" + item + "
"; + } + else + { + + res += ""; + + } + } + + return res; + } + protected string NatRuleItem2Html(string itemName) { return string.Format("", Path.GetFileName(ObjectsHtmlFile), itemName); @@ -1795,7 +1836,21 @@ protected void GeneratePackageHtmlReportHeaders(StreamWriter reportFile, string reportFile.WriteLine(" while (document.getElementById(parrent_rule + '.' + i)) {"); reportFile.WriteLine(" var sub_rule = document.getElementById(parrent_rule + '.' + i);"); reportFile.WriteLine(" sub_rule.style.display = sub_rule.style.display == 'none' ? 'table-row' : 'none';"); - reportFile.WriteLine(" i++;"); + reportFile.WriteLine(" var j=1;"); + reportFile.WriteLine(" while (document.getElementById(parrent_rule + '.' + i + '.' + j)) {"); + reportFile.WriteLine(" var sub_sub_rule = document.getElementById(parrent_rule + '.' + i + '.' + j);"); + reportFile.WriteLine(" // check arrow image to know whether to show sub-sub rules"); + reportFile.WriteLine(" var sub_img = document.getElementById(parrent_rule + '.' + i + '_img');"); + reportFile.WriteLine(" sub_current_icon = sub_img.getAttribute('src');"); + reportFile.WriteLine(" if (sub_current_icon == right_icon) {"); + reportFile.WriteLine(" sub_sub_rule.style.display = 'none'"); + reportFile.WriteLine(" }"); + reportFile.WriteLine(" else {"); + reportFile.WriteLine(" sub_sub_rule.style.display = sub_rule.style.display == 'none' ? 'none' : 'table-row';"); + reportFile.WriteLine(" }"); + reportFile.WriteLine(" j++;"); + reportFile.WriteLine(" }"); + reportFile.WriteLine(" i++;"); reportFile.WriteLine(" }"); reportFile.WriteLine(" }"); reportFile.WriteLine(""); @@ -1831,5 +1886,183 @@ protected void GeneratePackageHtmlReportHeaders(StreamWriter reportFile, string } #endregion + /* + * This method generates cp_objects.json file containing CheckPoint objects. + * Further it creates archive containing cp_objects.json file and SmartConnector.py script. + */ + public void CreateSmartConnector() + { + const string dirLibName = "cpapi"; + + string[] pySmartConnectorFNs = new string[] { + dirLibName + Path.DirectorySeparatorChar + "__init__.py", + dirLibName + Path.DirectorySeparatorChar + "api_exceptions.py", + dirLibName + Path.DirectorySeparatorChar + "api_response.py", + dirLibName + Path.DirectorySeparatorChar + "mgmt_api.py", + dirLibName + Path.DirectorySeparatorChar + "utils.py", + "smartconnector.py" + }; + + bool isGeneratingSC = true; + foreach (var pySmartConnectorFN in pySmartConnectorFNs) + { + if (!File.Exists(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "SmartConnector" + Path.DirectorySeparatorChar + pySmartConnectorFN)) + { + isGeneratingSC = false; + break; + } + } + + string compressorsDirPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "compressors"; + string compressorZip = Path.Combine(compressorsDirPath, "zip.exe"); + string compressorGtar = Path.Combine(compressorsDirPath, "gtar.exe"); + string compressorGzip = Path.Combine(compressorsDirPath, "gzip.exe"); + if (!File.Exists(compressorZip) || !File.Exists(compressorGtar) || !File.Exists(compressorGzip)) + isGeneratingSC = false; + + if (isGeneratingSC) + { + RaiseConversionProgress(90, "Generating Smart Connector ..."); + string cpObjectsJsonFN = "cp_objects.json"; + string cpObjectsJsonFP = _targetFolder + Path.DirectorySeparatorChar + cpObjectsJsonFN; + + #region adding objects and rules to list for generating JSON + + List cpJsonObjects = new List(); + cpJsonObjects.AddRange(_cpDomains); + cpJsonObjects.AddRange(_cpHosts); + cpJsonObjects.AddRange(_cpNetworks); + cpJsonObjects.AddRange(_cpRanges); + // adding NetworkGroups and NetworkGroups with Exclusions + CheckPoint_NetworkGroup allInternal = null; + bool splitNetworkGroupsCreation = (_cpNetworkGroups.Count > 0 && _cpGroupsWithExclusion.Count > 0); + if (_cpNetworkGroups.Count > 0) + { + foreach (CheckPoint_NetworkGroup obj in _cpNetworkGroups) + { + if (obj.Name == AllInternalNetwotkGroupName) + { + allInternal = obj; + continue; + } + if (splitNetworkGroupsCreation && obj.CreateAfterGroupsWithExclusion) + { + continue; + } + + cpJsonObjects.Add(obj); + } + } + if (_cpGroupsWithExclusion.Count > 0) + { + foreach (CheckPoint_GroupWithExclusion obj in _cpGroupsWithExclusion) + { + cpJsonObjects.Add(obj); + } + } + if (splitNetworkGroupsCreation) + { + foreach (CheckPoint_NetworkGroup obj in _cpNetworkGroups) + { + if (!obj.CreateAfterGroupsWithExclusion) + { + continue; + } + cpJsonObjects.Add(obj); + } + } + if (allInternal != null) + { + cpJsonObjects.Add(allInternal); + } + // NetworkGroups and NetworkGroups with Exclusion are added + cpJsonObjects.Add(_cpSimpleGateway); + cpJsonObjects.AddRange(_cpZones); + cpJsonObjects.AddRange(_cpTcpServices); + cpJsonObjects.AddRange(_cpUdpServices); + cpJsonObjects.AddRange(_cpOtherServices); + cpJsonObjects.AddRange(_cpServiceGroups); + cpJsonObjects.AddRange(_cpTimeGroups); + cpJsonObjects.AddRange(_cpTimes); + // objects are added + // adding Security rules + cpJsonObjects.Add(_cpPackages.FirstOrDefault()); + // adding NAT rules + _cpNatRules.ForEach(x => x.Package = _cpPackages[0].Name); + cpJsonObjects.AddRange(_cpNatRules); + + //remove all NULL elements + cpJsonObjects.RemoveAll(x => x == null); + #endregion + + File.WriteAllText(cpObjectsJsonFP, JsonConvert.SerializeObject(cpJsonObjects, Formatting.Indented)); + + string smartConnectorArchiveName = "smartconnector_" + _vendorFileName; + string smartConnectorArchivePath = _targetFolder + Path.DirectorySeparatorChar + smartConnectorArchiveName; + + #region preparing smarctconnector to archiving + if (Directory.Exists(smartConnectorArchivePath)) + Directory.Delete(smartConnectorArchivePath, true); + + Directory.CreateDirectory(smartConnectorArchivePath); + foreach (var pySmartConnectorFN in pySmartConnectorFNs) + { + Directory.CreateDirectory(Directory.GetParent(smartConnectorArchivePath + Path.DirectorySeparatorChar + pySmartConnectorFN).FullName); + File.Copy(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "SmartConnector" + Path.DirectorySeparatorChar + pySmartConnectorFN, + smartConnectorArchivePath + Path.DirectorySeparatorChar + pySmartConnectorFN); + } + if (!string.IsNullOrWhiteSpace(this._domainName)) // update by Domain + { + Encoding utf8Enc = new UTF8Encoding(false); + string smartConnectorSFP = smartConnectorArchivePath + Path.DirectorySeparatorChar + "smartconnector.py"; + string smartConnectorFC = File.ReadAllText(smartConnectorSFP, utf8Enc); + smartConnectorFC = smartConnectorFC.Replace( + "parser.add_argument('-d', '--domain', default=None,", + "parser.add_argument('-d', '--domain', default='" + this._domainName + "',"); + File.WriteAllText(smartConnectorSFP, smartConnectorFC, utf8Enc); + } + File.Copy(cpObjectsJsonFP, smartConnectorArchivePath + Path.DirectorySeparatorChar + cpObjectsJsonFN); + #endregion + + ProcessStartInfo startInfo = new ProcessStartInfo(); + startInfo.UseShellExecute = false; + startInfo.CreateNoWindow = true; + Process compressProc = null; + + #region createing ZIP archive + if (File.Exists(smartConnectorArchivePath + ".zip")) + File.Delete(smartConnectorArchivePath + ".zip"); + + startInfo.FileName = compressorZip; + startInfo.WorkingDirectory = _targetFolder + Path.DirectorySeparatorChar + smartConnectorArchiveName; + startInfo.Arguments = "-r" + " ..\\" + smartConnectorArchiveName + ".zip" + " *"; + compressProc = Process.Start(startInfo); + compressProc.WaitForExit(); + #endregion + + #region createing TAR.GZ archive + if (File.Exists(smartConnectorArchivePath + ".tar.gz")) + File.Delete(smartConnectorArchivePath + ".tar.gz"); + + startInfo.FileName = compressorGtar; + startInfo.WorkingDirectory = _targetFolder + Path.DirectorySeparatorChar + smartConnectorArchiveName; + startInfo.Arguments = "cf" + " ..\\" + smartConnectorArchiveName + ".tar" + " *"; + compressProc = Process.Start(startInfo); + compressProc.WaitForExit(); + + startInfo.FileName = compressorGzip; + startInfo.WorkingDirectory = _targetFolder; + startInfo.Arguments = smartConnectorArchiveName + ".tar"; + compressProc = Process.Start(startInfo); + compressProc.WaitForExit(); + #endregion + + if (File.Exists(cpObjectsJsonFP)) + File.Delete(cpObjectsJsonFP); + + if (Directory.Exists(smartConnectorArchivePath)) + Directory.Delete(smartConnectorArchivePath, true); + } + } } } diff --git a/NetScreenMigration/ScreenOSConverter.cs b/NetScreenMigration/ScreenOSConverter.cs index 5b158a74..d3068804 100644 --- a/NetScreenMigration/ScreenOSConverter.cs +++ b/NetScreenMigration/ScreenOSConverter.cs @@ -3577,6 +3577,8 @@ public override void Convert(bool convertNat = false) // Resolve the conversion categories/lines count to report to the user. ConversionIncidentCategoriesCount = _conversionIncidents.GroupBy(error => error.Title).Count(); ConversionIncidentsCommandsCount = _conversionIncidents.GroupBy(error => error.LineNumber).Count(); + + CreateSmartConnector(); } public override int RulesInConvertedPackage() @@ -3630,7 +3632,7 @@ public override void ExportConfigurationAsHtml() file.WriteLine(" " + HtmlAlertImageTag); file.WriteLine(" Valid Check Point object name consists of the following characters only - \"A-Za-z0-9_.-\". Any invalid character will be replaced with a \"_\" character."); file.WriteLine(" "); - file.WriteLine(""); + file.WriteLine(""); if (_conversionIncidents.Count > 0) { diff --git a/PaloAltoMigration/PA_Apps_CP.csv b/PaloAltoMigration/PA_Apps_CP.csv index 99f8fe6a..8ab1e3c0 100644 --- a/PaloAltoMigration/PA_Apps_CP.csv +++ b/PaloAltoMigration/PA_Apps_CP.csv @@ -819,7 +819,7 @@ genesys-interaction-server;; genesys-desktop-sharing;InterCall Unified Meeting - desktop sharing; genesys-base;InterCall Unified Meeting; ggp;;ggp -ghostsurf;ghostsurf; +ghostsurf;; gifboom;GifBoom; gigaup;Gigaup; git;git; @@ -2026,7 +2026,7 @@ rockwell-factorytalk;; rohc;; roundcube;Roundcube; rover;Rover; -rpc;;DCE-RPC Protocol +rpc;DCE-RPC Protocol; rpc-over-http;RPC over HTTP; rping;; rsa-securid-mfa-api;; @@ -2251,7 +2251,7 @@ snmpv3;;snmp snmp-base;;snmp snmpv1;;snmp snmpv2;;snmp -snmp-trap;SNMP Trap; +snmp-trap;;snmp-trap snp;; snpp;SNPP Protocol; soap;; diff --git a/PaloAltoMigration/PaloAltoConverter.cs b/PaloAltoMigration/PaloAltoConverter.cs index 241c3ab2..5a7ffd34 100644 --- a/PaloAltoMigration/PaloAltoConverter.cs +++ b/PaloAltoMigration/PaloAltoConverter.cs @@ -799,7 +799,7 @@ public override void Convert(bool convertNat) s_paAppFiltersList = GetPAApplicationsFilters(paConfig.Shared, null); - s_cpAppGroupsDict = ConvertApplicationsGroups(new List(paConfig.Shared.ApplicationGroupsEntries), s_appsMatchList, null, s_paAppFiltersList); + s_cpAppGroupsDict = ConvertApplicationsGroups(new List(paConfig.Shared.ApplicationGroupsEntries), s_appsMatchList, null, s_paAppFiltersList, s_cpServicesGroupsDict); s_cpSchedulesDict = new Dictionary>(); ConvertSchedules(paConfig.Shared).ForEach(x => @@ -927,7 +927,7 @@ public void ConvertPaVsysEntry(string targetFolderNew, string targetFileNameNew, List paAppFiltersList = GetPAApplicationsFilters(paVsysEntry, s_paAppFiltersList); Dictionary cpAppGroupsDict = - ConvertApplicationsGroups(new List(paVsysEntry.ApplicationGroupsEntries), appsMatchList, s_cpAppGroupsDict, paAppFiltersList); + ConvertApplicationsGroups(new List(paVsysEntry.ApplicationGroupsEntries), appsMatchList, s_cpAppGroupsDict, paAppFiltersList, cpServicesGroupsDict); Dictionary> cpSchedulesDict = null; if (s_cpSchedulesDict != null) @@ -961,7 +961,7 @@ public void ConvertPaVsysEntry(string targetFolderNew, string targetFileNameNew, if (_isNatConverted) { - ConvertNatPolicy(paVsysEntry, cpAddressesDict, cpNetGroupsDict, cpServicesDict, paServicesTypesDict, cpServicesGroupsDict); + ConvertNatPolicy(paVsysEntry, cpAddressesDict, cpNetGroupsDict, cpServicesDict, paServicesTypesDict, cpServicesGroupsDict, cpServicesGroupsDict); } //if non-optimized convert method is used then all objects are added @@ -997,6 +997,8 @@ public void ConvertPaVsysEntry(string targetFolderNew, string targetFileNameNew, _warningsConvertedPackage = _warningsList.Count; _errorsConvertedPackage = _errorsList.Count; + CreateSmartConnector(); + // to clean; must be the last!!! _cpObjects.ClearRepository(); CleanSavedData(); @@ -1072,7 +1074,7 @@ public string InspectObjectName(string objName, string objType) _warningsList.Add(objName + " " + objType.Trim() + " was renamed to " + objNameNew); objName = objNameNew; } - + objNameNew = GetSafeName(objName); if(!objNameNew.Equals(objName)) { @@ -2022,10 +2024,11 @@ public List GetApplicationsMatchList() return new List(File.ReadAllLines(PA_APPLICATIONS_FILE_NAME)); } - public Dictionary ConvertApplicationsGroups(List paAppsGroupsListCheck, + public Dictionary ConvertApplicationsGroups(List paAppsGroupsListCheck, List appsMatchList, Dictionary s_cpAppGroupDict, - List paAppFiltersList) + List paAppFiltersList, + Dictionary cpServicesGroupsDict) { Dictionary cpAppGroupDict = null; if (s_cpAppGroupDict != null) @@ -2043,7 +2046,10 @@ public Dictionary ConvertApplicationsGroups CheckPoint_ApplicationGroup cpAppGroup = new CheckPoint_ApplicationGroup(); cpAppGroup.Name = InspectObjectName(GetSafeName(paAppsGroupCheck.Name), CP_OBJECT_TYPE_NAME_APPLICATION_GROUP); - foreach(string appMember in paAppsGroupCheck.ApplicationGroupMembers) + CheckPoint_ServiceGroup cpServiceGroup = new CheckPoint_ServiceGroup(); + cpServiceGroup.Name = InspectObjectName(GetSafeName(paAppsGroupCheck.Name + "-svc"), CP_OBJECT_TYPE_NAME_APPLICATION_GROUP); + + foreach (string appMember in paAppsGroupCheck.ApplicationGroupMembers) { string matchedLine = appsMatchList.Find(x => x.StartsWith(appMember + ";")); if (!string.IsNullOrEmpty(matchedLine)) @@ -2052,9 +2058,9 @@ public Dictionary ConvertApplicationsGroups if (!string.IsNullOrWhiteSpace(matchedArray[1])) { string[] matchedValues = matchedArray[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - foreach(string matchedValue in matchedValues) + foreach (string matchedValue in matchedValues) { - if(!matchedValue.Trim().Equals("")) + if (!matchedValue.Trim().Equals("")) { cpAppGroup.Members.Add(matchedValue.Trim()); } @@ -2066,10 +2072,11 @@ public Dictionary ConvertApplicationsGroups foreach (string matchedValue in matchedValues) { if (!matchedValue.Trim().Equals("")) - { - cpAppGroup.Members.Add(matchedValue.Trim()); + { + cpServiceGroup.Members.Add(matchedValue.Trim()); } } + cpServicesGroupsDict[paAppsGroupCheck.Name + "-svc"] = cpServiceGroup; } else { @@ -2084,9 +2091,9 @@ public Dictionary ConvertApplicationsGroups { _warningsList.Add(paAppsGroupCheck.Name + " application group contains application filter: " + appMember); } - else if(paAppsGroupsListCheck.FindIndex(x => x.Name.Equals(appMember)) != -1) + else if (paAppsGroupsListCheck.FindIndex(x => x.Name.Equals(appMember)) != -1) { - cpAppGroupDict = ConvertApplicationsGroups(paAppsGroupsListCheck, appsMatchList, cpAppGroupDict, paAppFiltersList); + cpAppGroupDict = ConvertApplicationsGroups(paAppsGroupsListCheck, appsMatchList, cpAppGroupDict, paAppFiltersList, cpServicesGroupsDict); if (cpAppGroupDict.ContainsKey(appMember)) { cpAppGroup.Members.Add(cpAppGroupDict[appMember].Name); @@ -2359,6 +2366,10 @@ public void ConvertSecurityPolicy(PA_VsysEntry paVsysEntry, applicationsFiltering = true; foreach (string paAppName in paSecurityRuleEntry.ApplicationList) { + if (cpServicesGroupsDict.ContainsKey(paAppName + "-svc"))//to add mapped PA services from CP application group entry + { + cpRuleServiceList.Add(cpServicesGroupsDict[paAppName + "-svc"]); + } if (cpAppGroupsDict.ContainsKey(paAppName)) { cpRuleApplilcationList.Add(cpAppGroupsDict[paAppName]); @@ -2624,9 +2635,20 @@ public void ConvertSecurityPolicy(PA_VsysEntry paVsysEntry, cpLayer.Rules.Add(cpRuleCU); }; - var cpRuleFake = new CheckPoint_Rule(); - cpRuleFake.Name = "Cleanup rule"; //the last rule which is created by default by CheckPoint script importer. It is for report only. - cpPackage.ParentLayer.Rules.Add(cpRuleFake); + // Do NOT create a cleanup rule if it already exists + bool createCleanupRule = true; + if (cpPackage.ParentLayer.Rules.Count > 0) + { + var lastRule = cpPackage.ParentLayer.Rules[cpPackage.ParentLayer.Rules.Count - 1]; + createCleanupRule = !lastRule.IsCleanupRule(); + } + + if (createCleanupRule) + { + var cpRuleFake = new CheckPoint_Rule(); + cpRuleFake.Name = "Cleanup rule"; //the last rule which is created by default by CheckPoint script importer. It is for report only. + cpPackage.ParentLayer.Rules.Add(cpRuleFake); + } AddCheckPointObject(cpPackage); } @@ -2726,11 +2748,12 @@ private CheckPoint_RuleWithApplication CreateCpRule(PA_SecurityRuleEntry paSecur #region Convert Nat Policy public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, - Dictionary cpAddressesDict, + Dictionary cpAddressesDict, Dictionary cpNetGroupsDict, - Dictionary cpServicesDict, + Dictionary cpServicesDict, Dictionary paServicesTypesDict, - Dictionary cpServicesGroupsDict) + Dictionary cpServicesGroupsDict, + Dictionary cpServicesFromAppsGroupDict) { int counterNatRules = -1; @@ -2795,6 +2818,42 @@ public void ConvertNatPolicy(PA_VsysEntry paVsysEntry, { cpSourceTranslationList.Add(cpNetGroupsDict[translatedAddress]); } + else if (Regex.IsMatch(translatedAddress, RE_NET_ADDRESS)) //create address or network object for translated address if they were not created before + { + if (!translatedAddress.Contains("/") || translatedAddress.Contains(NETWORK_NETMASK_WS)) + { + string ipAddress; + + if (translatedAddress.Contains("/")) + ipAddress = translatedAddress.Substring(0, translatedAddress.IndexOf("/")); + else + ipAddress = translatedAddress.Substring(0); + + CheckPoint_Host cpHostNew = new CheckPoint_Host(); + cpHostNew.Name = "Host_" + ipAddress; + cpHostNew.IpAddress = ipAddress; + + cpAddressesDict[translatedAddress] = cpHostNew; + cpSourceTranslationList.Add(cpHostNew); + _warningsList.Add(cpHostNew.Name + " host object is created for NAT rule."); + } + else + { + IPNetwork ipNetwork; + if (IPNetwork.TryParse(translatedAddress, out ipNetwork)) + { + string ipAddress = translatedAddress.Substring(0, translatedAddress.IndexOf("/")); + + CheckPoint_Network cpNetworkNew = new CheckPoint_Network(); + cpNetworkNew.Name = "Net_" + ipAddress; + cpNetworkNew.Subnet = ipAddress; + cpNetworkNew.Netmask = ipNetwork.Netmask.ToString(); + cpAddressesDict[translatedAddress] = cpNetworkNew; + cpSourceTranslationList.Add(cpNetworkNew); + _warningsList.Add(cpNetworkNew.Name + " network object is created for NAT rule."); + } + } + } } } else if(paNatRuleEntry.SourceTranslation.DynamicIpAndPort.InterfaceAddress != null) diff --git a/PaloAltoMigration/PaloAltoMigration.csproj b/PaloAltoMigration/PaloAltoMigration.csproj index 41bb3824..f2e0b797 100644 --- a/PaloAltoMigration/PaloAltoMigration.csproj +++ b/PaloAltoMigration/PaloAltoMigration.csproj @@ -48,6 +48,9 @@ + + + diff --git a/PaloAltoMigration/PanoramaConverter.cs b/PaloAltoMigration/PanoramaConverter.cs new file mode 100644 index 00000000..36016eb4 --- /dev/null +++ b/PaloAltoMigration/PanoramaConverter.cs @@ -0,0 +1,4019 @@ +using CheckPointObjects; +using CommonUtils; +using MigrationBase; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using PaloAltoMigration; +using System.Security.Cryptography.X509Certificates; + +namespace PanoramaPaloAltoMigration +{ + public class PanoramaConverter : VendorConverter + { + #region GUI params + + 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 + + #endregion + + #region Private Members + + private PanoramaParser _paParser; + private bool _isNatConverted; + + private HashSet _vsysNames = new HashSet(); + private HashSet _deviceGroupNames = new HashSet();//Panorama + //private Dictionary _devicesUIDDict = new Dictionary(); + + private List _errorsList = new List(); //storing conversion errors for config or each device group + private List _warningsList = new List(); //storing conversion warnings for config or each device group + + private int _rulesInConvertedPackage = 0; //counter + private int _rulesInNatLayer = 0; //counter + + private int _warningsConvertedPackage = 0; //counter + private int _errorsConvertedPackage = 0; //counter + + private HashSet _timesNamesSet = new HashSet(); + private int _timeCutterCounter = 0; //postfix for Time objects + + private HashSet _objectsNamesSet = new HashSet(); + private int _numPostfix = 0; + + private Dictionary cpPredefServicesTypes = new Dictionary(); + + #endregion + + #region Constants + + private const string LOCAL_DEVICE_ENTRY_NAME = "localhost.localdomain"; + + private const string PA_ANY_VALUE = "any"; + + private const string CP_OBJECT_TYPE_NAME_ZONE = "zone"; + private const string CP_OBJECT_TYPE_NAME_ADDRESS_HOST = "address host"; + private const string CP_OBJECT_TYPE_NAME_ADDRESS_NETWORK = "address network"; + private const string CP_OBJECT_TYPE_NAME_ADDRESS_RANGE = "address range"; + private const string CP_OBJECT_TYPE_NAME_ADDRESS_GROUP = "addresses group"; + private const string CP_OBJECT_TYPE_NAME_SERVICE_TCP = "tcp service"; + private const string CP_OBJECt_TYPE_NAME_SERVICE_UDP = "udp service"; + private const string CP_OBJECT_TYPE_NAME_SERVICE_GROUP = "services group"; + private const string CP_OBJECT_TYPE_NAME_APPLICATION_GROUP = "application group"; + private const string CP_OBJECT_TYPE_NAME_ACCESS_ROLE = "access-role"; + + private const string NETWORK_NETMASK = "32"; + private const string NETWORK_NETMASK_WS = "/32"; + + private const string SERVICE_TYPE_TCP = "TCP"; + private const string SERVICE_TYPE_UDP = "UDP"; + + private const string PA_APPLICATIONS_FILE_NAME = "PA_Apps_CP.csv"; + private const string PA_APP_FILTERS_FILE_NAME = "PA_AppFilters_CP.csv"; + + private const string PA_APPLICATION_DEFAULT = "application-default"; + + private const string PA_INTRAZONE_NAME = "interzone"; + + private const string RE_NET_ADDRESS = "^(\\d+\\.){3}\\d+(/\\d{0,2})?"; // 192.168.1.12/24 or 192.168.1.0/32 or 192.168.1.55 + private const string RE_NAME_UNSAFE = @"[^A-Za-z0-9_.-]"; + + #endregion + + #region Methods are used for reports + + //count of converted rules. + // -1 is VSYSs + public override int RulesInConvertedPackage() + { + return _rulesInConvertedPackage; + } + + //count of warnings of conversion + // -1 if VSYSs + public int WarningsInConvertedPackage() + { + return _warningsConvertedPackage; + } + + //count of errors of conversion + // -1 if VSYSs + public int ErrorsInConvertedPackage() + { + return _errorsConvertedPackage; + } + + public override int RulesInConvertedOptimizedPackage() + { + return 0; + } + + //count of NAT rules + // -1 if VSYSs + public override int RulesInNatLayer() + { + return _rulesInNatLayer; + } + + public override void ExportConfigurationAsHtml() + { + //not used as we have VSYSs + } + + public override void ExportPolicyPackagesAsHtml() + { + //not used as we have VSYSs + } + + protected string RuleItemsList2Html_pa(List ruleItems, List appsItems, bool isCellNegated, string defaultValue, ref ConversionIncidentType ruleConversionIncidentType) + { + if (ruleItems.Count == 0 && (appsItems == null || appsItems.Count == 0)) + { + return defaultValue; + } + + string res = ""; + + if (isCellNegated) + { + res += "
"; + res += "
Negated
"; + res += "
"; + } + + foreach (CheckPointObject item in ruleItems) + { + if (_cpObjects.IsKnownService(item.Name)) + { + res += "
" + item.Name + "
"; + } + else if (item.GetType() == typeof(CheckPoint_PredifinedObject)) + { + res += "
" + item.Name + "
"; + } + else + { + if (item.ConversionIncidentType != ConversionIncidentType.None) + { + if (item.ConversionIncidentType > ruleConversionIncidentType) // Error type overrides information type!!! + { + ruleConversionIncidentType = item.ConversionIncidentType; + } + res += "
" + BuildConversionIncidentLinkTag(item.ConvertedCommandId) + "" + item.Name + "
"; + } + else + { + res += ""; + } + } + } + + if (appsItems != null) + { + foreach (CheckPointObject item in appsItems) + { + res += "
" + item.Name + "
"; + } + } + + return res; + } + + public void ExportPolicyPackagesAsHtmlConfig() + { + const string ruleIdPrefix = "rule_"; + + foreach (CheckPoint_Package package in _cpPackages) + { + string filename = _targetFolder + "\\" + package.Name + ".html"; + + using (var file = new StreamWriter(filename, false)) + { + var rulesWithConversionErrors = new Dictionary(); + var rulesWithConversionInfos = new Dictionary(); + var rulesWithInspection = new Dictionary>(); + + GeneratePackageHtmlReportHeaders(file, package.Name, package.ConversionIncidentType != ConversionIncidentType.None); + + // Generate the report body + file.WriteLine("
No. Source Destination Service Translated-Source Translated-Destination Translated-Service CommentsNo. Source Destination Service Translated-Source Translated-Destination Translated-Service Install On Comments
"); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + + int ruleNumber = 1; + + foreach (CheckPoint_Rule rule in package.ParentLayer.Rules) + { + List ruleAppsList = new List(); + if (rule.GetType() == typeof(CheckPoint_RuleWithApplication)) + { + CheckPoint_RuleWithApplication ruleApp = (CheckPoint_RuleWithApplication)rule; + ruleAppsList.AddRange(ruleApp.Application); + } + + bool isSubPolicy = false; + string action = ""; + string actionStyle = ""; + var dummy = ConversionIncidentType.None; + + switch (rule.Action) + { + case CheckPoint_Rule.ActionType.Accept: + case CheckPoint_Rule.ActionType.Drop: + action = rule.Action.ToString(); + actionStyle = rule.Action.ToString().ToLower(); + break; + + case CheckPoint_Rule.ActionType.SubPolicy: + isSubPolicy = true; + action = "Sub-policy: " + rule.SubPolicyName; + actionStyle = ""; + break; + } + + string curParentRuleId = string.Format("{0}{1}", ruleIdPrefix, ruleNumber); + + if (rule.Enabled) + { + file.WriteLine(" "); + if (isSubPolicy) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + } + else + { + file.WriteLine(" "); + if (isSubPolicy) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + } + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + //file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + + if (isSubPolicy) + { + foreach (CheckPoint_Layer subPolicy in package.SubPolicies) + { + int subRuleNumber = 1; + + foreach (CheckPoint_Rule subRule in subPolicy.Rules) + { + List subRuleAppsList = new List(); + if (subRule.GetType() == typeof(CheckPoint_RuleWithApplication)) + { + CheckPoint_RuleWithApplication subRuleApp = (CheckPoint_RuleWithApplication)subRule; + subRuleAppsList.AddRange(subRuleApp.Application); + } + + if (subRule.Layer == rule.SubPolicyName) + { + var ruleConversionIncidentType = ConversionIncidentType.None; + bool isInspectedRule = !string.IsNullOrEmpty(subRule.Tag); + string curRuleNumber = ruleNumber + "." + subRuleNumber; + string curRuleId = ruleIdPrefix + curRuleNumber; + + if (subRule.Enabled) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + + var sbCurRuleNumberColumnTag = new StringBuilder(); + sbCurRuleNumberColumnTag.Append(" "); + file.WriteLine(sbCurRuleNumberColumnTag.ToString()); + + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + /* */ + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + + subRuleNumber++; + + if (package.ConversionIncidentType != ConversionIncidentType.None && ruleConversionIncidentType != ConversionIncidentType.None) + { + if (ruleConversionIncidentType == ConversionIncidentType.ManualActionRequired) + { + rulesWithConversionErrors.Add(curRuleId, subRule); + } + else + { + rulesWithConversionInfos.Add(curRuleId, subRule); + } + } + + if (isInspectedRule) + { + string[] fortiClassMapNames = subRule.Tag.Split(','); // there may be several class-maps matching the same fw rule... + subRule.Tag = curRuleId; // replace class-map name (it is now the key of this dic) by curRuleId... + + foreach (var classMapName in fortiClassMapNames) + { + if (!rulesWithInspection.ContainsKey(classMapName)) + { + var inspectedRules = new List(); + rulesWithInspection.Add(classMapName, inspectedRules); + } + rulesWithInspection[classMapName].Add(subRule); + } + } + } + } + } + } + + ruleNumber++; + } + + file.WriteLine("
No. Name Source Destination Service Action Time Track Install On Comments Conversion Comments
" + + string.Format(HtmlSubPolicyArrowImageTagFormat, curParentRuleId + "_img", HtmlDownArrowImageSourceData) + ruleNumber + "" + ruleNumber + "
" + + string.Format(HtmlSubPolicyArrowImageTagFormat, curParentRuleId + "_img", HtmlDownArrowImageSourceData) + ruleNumber + HtmlDisabledImageTag + "" + ruleNumber + HtmlDisabledImageTag + "" + rule.Name + "" + RuleItemsList2Html(rule.Source, rule.SourceNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(rule.Destination, rule.DestinationNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html_pa(rule.Service, ruleAppsList, false, CheckPointObject.Any, ref dummy) + "" + action + "" + RuleItemsList2Html(rule.Time, false, CheckPointObject.Any, ref dummy) + "" + rule.Track.ToString() + "" + RuleStringList2Html(rule.Target, rule.TargetNegated, CheckPointObject.All, ref dummy) + "" + rule.Target.ToString() + "" + rule.Comments + "" + rule.ConversionComments + "
"); + sbCurRuleNumberColumnTag.Append(" "); + sbCurRuleNumberColumnTag.Append(curRuleNumber); + if (isInspectedRule) + { + sbCurRuleNumberColumnTag.Append(BuildInspectedRuleInfo(subRule.Tag)); + } + if (subRule.ConversionIncidentType != ConversionIncidentType.None) + { + sbCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(subRule.ConvertedCommandId)); + ruleConversionIncidentType = subRule.ConversionIncidentType; + } + if (!subRule.Enabled) + { + sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); + } + sbCurRuleNumberColumnTag.Append("" + subRule.Name + "" + RuleItemsList2Html(subRule.Source, subRule.SourceNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + RuleItemsList2Html(subRule.Destination, subRule.DestinationNegated, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + RuleItemsList2Html_pa(subRule.Service, subRuleAppsList, false, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + subRule.Action.ToString() + "" + RuleItemsList2Html(subRule.Time, false, CheckPointObject.Any, ref ruleConversionIncidentType) + "" + subRule.Track.ToString() + "" + subRule.Target.ToString() + "" + subRule.Comments + "" + subRule.ConversionComments + "
"); + + if (rulesWithConversionErrors.Count > 0 || rulesWithConversionInfos.Count > 0 || rulesWithInspection.Count > 0) + { + file.WriteLine("

Policy Conversion Issues

"); + } + + // Generate the errors report + if (rulesWithConversionErrors.Count > 0) + { + file.WriteLine(""); + + file.WriteLine("

Conversion Errors

"); + file.WriteLine(""); + file.WriteLine(" "); + file.WriteLine(" " + + " " + + ""); + file.WriteLine(" "); + + foreach (var ruleEntry in rulesWithConversionErrors) + { + var dummy = ConversionIncidentType.None; + + if (ruleEntry.Value.Enabled) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + + var sbCurRuleNumberColumnTag = new StringBuilder(); + sbCurRuleNumberColumnTag.Append(" "); + file.WriteLine(sbCurRuleNumberColumnTag.ToString()); + + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + } + + file.WriteLine("
No. Name Source DestinationService Action Time TrackInstall On Comments Conversion Comments
"); + sbCurRuleNumberColumnTag.Append(""); + sbCurRuleNumberColumnTag.Append(ruleEntry.Key.Replace(ruleIdPrefix, "")); + sbCurRuleNumberColumnTag.Append(""); + if (ruleEntry.Value.ConversionIncidentType != ConversionIncidentType.None) + { + sbCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(ruleEntry.Value.ConvertedCommandId)); + } + if (!ruleEntry.Value.Enabled) + { + sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); + } + sbCurRuleNumberColumnTag.Append("" + ruleEntry.Value.Name + "" + RuleItemsList2Html(ruleEntry.Value.Source, ruleEntry.Value.SourceNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Destination, ruleEntry.Value.DestinationNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Service, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Action.ToString() + "" + RuleItemsList2Html(ruleEntry.Value.Time, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Track.ToString() + "" + ruleEntry.Value.Target.ToString() + "" + ruleEntry.Value.Comments + "" + ruleEntry.Value.ConversionComments + "
"); + } + + if (rulesWithConversionInfos.Count > 0 || rulesWithInspection.Count > 0) + { + int counter = (rulesWithInspection.Count > 0) ? 1 : 0; + counter += rulesWithConversionInfos.Count; + + file.WriteLine(""); + file.WriteLine("

Conversion Notifications

"); + } + + // Generate the information report + if (rulesWithConversionInfos.Count > 0) + { + file.WriteLine(""); + file.WriteLine(" "); + file.WriteLine(" " + + " " + + ""); + file.WriteLine(" "); + + foreach (var ruleEntry in rulesWithConversionInfos) + { + var dummy = ConversionIncidentType.None; + + if (ruleEntry.Value.Enabled) + { + file.WriteLine(" "); + } + else + { + file.WriteLine(" "); + } + + var sbCurRuleNumberColumnTag = new StringBuilder(); + sbCurRuleNumberColumnTag.Append(" "); + file.WriteLine(sbCurRuleNumberColumnTag.ToString()); + + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + file.WriteLine(" "); + } + + file.WriteLine("
No. Name Source DestinationService Action Time TrackInstall On Comments Conversion Comments
"); + sbCurRuleNumberColumnTag.Append(""); + sbCurRuleNumberColumnTag.Append(ruleEntry.Key.Replace(ruleIdPrefix, "")); + sbCurRuleNumberColumnTag.Append(""); + if (ruleEntry.Value.ConversionIncidentType != ConversionIncidentType.None) + { + sbCurRuleNumberColumnTag.Append(BuildConversionIncidentLinkTag(ruleEntry.Value.ConvertedCommandId)); + } + if (!ruleEntry.Value.Enabled) + { + sbCurRuleNumberColumnTag.Append(HtmlDisabledImageTag); + } + sbCurRuleNumberColumnTag.Append("" + ruleEntry.Value.Name + "" + RuleItemsList2Html(ruleEntry.Value.Source, ruleEntry.Value.SourceNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Destination, ruleEntry.Value.DestinationNegated, CheckPointObject.Any, ref dummy) + "" + RuleItemsList2Html(ruleEntry.Value.Service, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Action.ToString() + "" + RuleItemsList2Html(ruleEntry.Value.Time, false, CheckPointObject.Any, ref dummy) + "" + ruleEntry.Value.Track.ToString() + "" + ruleEntry.Value.Target.ToString() + "" + ruleEntry.Value.Comments + "" + ruleEntry.Value.ConversionComments + "
"); + } + + file.WriteLine(""); + file.WriteLine(""); + } + } + } + + public string BuildInspectedRuleInfo(string fortiClassMapName) + { + string inspectTooltip = "Rule traffic is affected by FortiGate inspect policy. [class-map objects: " + fortiClassMapName + "]"; + string htmlInspectedImageTag = string.Format(HtmlAlertImageTagFormat, inspectTooltip); + return htmlInspectedImageTag; + } + + //Catalog is Root file if several device groups exist + public void CreateCatalogObjects() + { + string filename = this.ObjectsHtmlFile; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of Device Group Objects for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string deviceGroupName in _deviceGroupNames) + { + if (File.Exists(this._targetFolder + deviceGroupName + "\\" + deviceGroupName + "_objects.html")) + { + file.WriteLine("
  • " + "" + "

    " + deviceGroupName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + deviceGroupName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //Catalog is Root file if several device groups exist + public void CreateCatalogPolicies() + { + string filename = this.PolicyHtmlFile; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of Device Group Policies for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string deviceGroupName in _deviceGroupNames) + { + if (File.Exists(this._targetFolder + deviceGroupName + "\\" + deviceGroupName + "_policy.html")) + { + file.WriteLine("
  • " + "" + "

    " + deviceGroupName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + deviceGroupName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //Catalog is Root file if several device groups exist + public void CreateCatalogNATs() + { + string filename = this.NatHtmlFile; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of Device Group NATs for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string deviceGroupName in _deviceGroupNames) + { + if (File.Exists(this._targetFolder + deviceGroupName + "\\" + deviceGroupName + "_NAT.html")) + { + file.WriteLine("
  • " + "" + "

    " + deviceGroupName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + deviceGroupName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //Catalog is Root file if several device groups exist + public void CreateCatalogErrors() + { + string filename = this._targetFolder + "\\" + _vendorFileName + "_errors.html"; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of Device Group Errors for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string deviceGroupName in _deviceGroupNames) + { + if (File.Exists(this._targetFolder + deviceGroupName + "\\" + deviceGroupName + "_errors.html")) + { + file.WriteLine("
  • " + "" + "

    " + deviceGroupName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + deviceGroupName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //Catalog is Root file if several device groups exist + public void CreateCatalogWarnings() + { + string filename = this._targetFolder + "\\" + _vendorFileName + "_warnings.html"; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of Device Group Warnings for " + this._vendorFileName + "

"); + file.WriteLine("
    "); + foreach (string deviceGroupName in _deviceGroupNames) + { + if (File.Exists(this._targetFolder + deviceGroupName + "\\" + deviceGroupName + "_warnings.html")) + { + file.WriteLine("
  • " + "" + "

    " + deviceGroupName + "

    " + "
    " + "
  • "); + } + else + { + file.WriteLine("
  • " + "

    " + deviceGroupName + "

    " + "
  • "); + } + } + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //report about Errors + public void CreateErrorsHtml(string deviceGroupName) + { + string filename = _targetFolder + "//" + deviceGroupName + "_errors.html"; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of " + deviceGroupName + " Errors

"); + file.WriteLine(""); + for (int i = 0; i < _errorsList.Count; i++) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + } + file.WriteLine("
"); + file.WriteLine(i); + file.WriteLine(""); + file.WriteLine(_errorsList[i]); + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + //report about Warnings + public void CreateWarningsHtml(string deviceGroupName) + { + string filename = _targetFolder + "//" + deviceGroupName + "_warnings.html"; + + using (var file = new StreamWriter(filename, false)) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine("

List of " + deviceGroupName + " Warnings

"); + file.WriteLine(""); + for (int i = 0; i < _warningsList.Count; i++) + { + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + file.WriteLine(""); + } + file.WriteLine("
"); + file.WriteLine(i); + file.WriteLine(""); + file.WriteLine(_warningsList[i]); + file.WriteLine("
"); + file.WriteLine(""); + file.WriteLine(""); + } + } + + #endregion + + #region Converter + + public override void Initialize(VendorParser vendorParser, string vendorFilePath, string toolVersion, string targetFolder, string domainName) + { + _paParser = (PanoramaParser)vendorParser; + if (_paParser == null) + { + throw new InvalidDataException("Unexpected!!!"); + } + base.Initialize(vendorParser, vendorFilePath, toolVersion, targetFolder, domainName); + } + + protected override bool AddCheckPointObject(CheckPointObject cpObject) + { + if (cpObject != null) + { + cpObject.Comments = string.IsNullOrWhiteSpace(cpObject.Comments) ? "" : (" " + cpObject.Comments); + if (base.AddCheckPointObject(cpObject)) + { + string vendor = Vendor.PaloAlto.ToString(); + if (!cpObject.Tags.Contains(vendor)) + { + cpObject.Tags.Add(vendor); + } + } + } + + return false; + } + + // + // + //method to get correlation between divice groups and zones + // + public Dictionary> getZones(Panorama_Config paConfig) + { + Dictionary> deviceTemplateDictionary = new Dictionary>(); + Dictionary> deviceDevgroupDictionary = new Dictionary>(); + Dictionary> templateZoneDictionary = new Dictionary>(); + Dictionary> devgroupZoneDictionary = new Dictionary>(); + Dictionary> deviceZoneDictionary = new Dictionary>(); + + + foreach (PA_TemplateStackEntry paTemplateStackEntry in paConfig.Devices.DevicesEntry.TemplateStackEntries) + { + List templatesList = new List(); + foreach (string template in paTemplateStackEntry.StackTemplatesMembers) + { + templatesList.Add(template); + } + foreach (PA_DevicesTemplateStackEntry device in paTemplateStackEntry.DevicesEntries) + { + deviceTemplateDictionary.Add(device.Name, templatesList); + } + } + + foreach (PA_TemplateEntry paTemplateEntry in paConfig.Devices.DevicesEntry.TemplateEntries) + { + foreach (PA_VsysEntry vsys in paTemplateEntry.Config.TemplateDevices.TemplateDevicesEntry.VsysEntries) + { + if (!templateZoneDictionary.ContainsKey(paTemplateEntry.Name)) + templateZoneDictionary.Add(paTemplateEntry.Name, vsys.ZoneEntries); + } + + } + + foreach (PA_DeviceGroupEntry deviceGroup in paConfig.Devices.DevicesEntry.DeviceGroupEntries) + { + List deviceNamesList = new List(); + foreach (PA_DevicesGroupDevicesEntry deviceEntry in deviceGroup.DevicesGroupDevicesEntries) + { + deviceNamesList.Add(deviceEntry.Name); + } + deviceDevgroupDictionary.Add(deviceGroup.Name, deviceNamesList); + } + + foreach (string device in deviceTemplateDictionary.Keys) + { + foreach (string template in deviceTemplateDictionary[device]) + { + if (templateZoneDictionary.ContainsKey(template)) + { + if (!deviceZoneDictionary.ContainsKey(device)) + deviceZoneDictionary.Add(device, templateZoneDictionary[template]); + } + } + + } + + foreach (string devGroup in deviceDevgroupDictionary.Keys) + { + foreach (string device in deviceDevgroupDictionary[devGroup]) + { + if (deviceZoneDictionary.ContainsKey(device)) + { + if (!devgroupZoneDictionary.ContainsKey(devGroup)) + devgroupZoneDictionary.Add(devGroup, deviceZoneDictionary[device]); + } + } + + } + + return devgroupZoneDictionary; + } + + public override void Convert(bool convertNat) + { + string targetFileNameMain = _vendorFileName; + string targetFolderMain = _targetFolder; + + Panorama_Config paConfig = _paParser.Config; + + //call method to get divice-group and zones correlation + Dictionary> devgroupZoneDictionary = getZones(paConfig); + + _isNatConverted = convertNat; + if (LDAPAccoutUnit != null) + LDAP_Account_Unit = LDAPAccoutUnit.Trim(); + + Dictionary _devicesUIDDict = GetDevicesUIDdict(_paParser._ArchiveName); + + if (paConfig != null) + { + List s_TagEntries = new List(); + Dictionary s_cpAddressesDict = null; + Dictionary s_cpNetGroupsDict = null; + Dictionary s_cpServicesDict = null; + Dictionary s_paServicesTypesDict = null; + Dictionary s_cpServicesGroupsDict = null; + List s_paAppFiltersList = null; + Dictionary s_cpAppGroupsDict = null; + Dictionary> s_cpSchedulesDict = null; + PA_PreRulebase s_preRulebase = null; + PA_PostRulebase s_postRulebase = null; + + if (paConfig.Shared != null) + { + s_cpAddressesDict = ConvertAddresses(paConfig.Shared, null); + + s_cpNetGroupsDict = ConvertAddressesGroupsWithInspection(paConfig.Shared, s_cpAddressesDict, null, null); + + s_cpServicesDict = ConvertServices(paConfig.Shared, null); + + s_paServicesTypesDict = GetServicesTypes(paConfig.Shared, null); + + s_cpServicesGroupsDict = ConvertServicesGroupsWithInspection(paConfig.Shared, s_cpServicesDict, null); + + List s_appsMatchList = GetApplicationsMatchList(); + + s_paAppFiltersList = GetPAApplicationsFilters(paConfig.Shared, null); + + s_cpAppGroupsDict = ConvertApplicationsGroups(new List(paConfig.Shared.ApplicationGroupsEntries), s_appsMatchList, null, s_paAppFiltersList, s_cpServicesGroupsDict); + + s_cpSchedulesDict = new Dictionary>(); + s_cpSchedulesDict = new Dictionary>(); + ConvertSchedules(paConfig.Shared).ForEach(x => + { + string key = x.Name; + x = InspectCpScheduleName(x); + List cpTimesList = null; + if (s_cpSchedulesDict.ContainsKey(key)) + cpTimesList = s_cpSchedulesDict[key]; + else + cpTimesList = new List(); + cpTimesList.Add(x); + s_cpSchedulesDict[key] = cpTimesList; + }); + + s_preRulebase = paConfig.Shared.PreRulebase; + s_postRulebase = paConfig.Shared.PostRulebase; + } + if (paConfig.Devices != null) + { + if (paConfig.Devices.DevicesEntry != null && paConfig.Devices.DevicesEntry.Name.Equals(LOCAL_DEVICE_ENTRY_NAME)) //we parse PA config from PA + { + if (paConfig.Devices.DevicesEntry.DeviceGroupEntries != null && + paConfig.Devices.DevicesEntry.DeviceGroupEntries != null && + paConfig.Devices.DevicesEntry.DeviceGroupEntries.Count > 0) + { + if (paConfig.Devices.DevicesEntry.DeviceGroupEntries.Count == 1) + { + List FWGroup_List = getPanoramaDeviceGroup(paConfig.Devices.DevicesEntry.DeviceGroupEntries[0], _devicesUIDDict); + + List devicesGroupList = new List(); + devicesGroupList.AddRange(FWGroup_List); + + foreach (CheckPoint_NetworkGroup FWGroup in FWGroup_List) + { + if (s_cpNetGroupsDict != null) + s_cpNetGroupsDict.Add(FWGroup.Name, FWGroup); + else + s_cpNetGroupsDict = new Dictionary + { + { FWGroup.Name, FWGroup} + }; + } + + ConvertPaDeviceGroupEntry(targetFolderMain, targetFileNameMain, paConfig.Devices.DevicesEntry.DeviceGroupEntries[0], devgroupZoneDictionary, + s_TagEntries, + s_cpAddressesDict, + s_cpNetGroupsDict, + s_cpServicesDict, + s_paServicesTypesDict, + s_cpServicesGroupsDict, + s_paAppFiltersList, + s_cpAppGroupsDict, + s_cpSchedulesDict, + s_preRulebase, + s_postRulebase, + devicesGroupList, + _devicesUIDDict + ); + } + else + { + foreach (PA_DeviceGroupEntry paDeviceGroupEntry in paConfig.Devices.DevicesEntry.DeviceGroupEntries) + { + string paDeviceGroupName = paDeviceGroupEntry.Name; + _deviceGroupNames.Add(paDeviceGroupName); + string targetFolderdeviceGroup = targetFolderMain + "\\" + paDeviceGroupName; + System.IO.Directory.CreateDirectory(targetFolderdeviceGroup); + + + List FWGroup_List = getPanoramaDeviceGroup(paDeviceGroupEntry, _devicesUIDDict); + + List devicesGroupList = new List(); + devicesGroupList.AddRange(FWGroup_List); + + Dictionary s_cpNetGroupsDict_Global = new Dictionary();//to avoid duplication of device groups + s_cpNetGroupsDict_Global = s_cpNetGroupsDict_Global.Concat(s_cpNetGroupsDict.Where(x => !s_cpNetGroupsDict_Global.ContainsKey(x.Key))).ToDictionary(x => x.Key, x => x.Value); + + foreach (CheckPoint_NetworkGroup FWGroup in FWGroup_List) + { + if (s_cpNetGroupsDict != null) + { + if (!s_cpNetGroupsDict.ContainsKey(FWGroup.Name)) + s_cpNetGroupsDict.Add(FWGroup.Name, FWGroup); + } + + else + s_cpNetGroupsDict = new Dictionary + { + { FWGroup.Name, FWGroup} + }; + } + + ConvertPaDeviceGroupEntry(targetFolderdeviceGroup, paDeviceGroupName, paDeviceGroupEntry, devgroupZoneDictionary, + s_TagEntries, + s_cpAddressesDict, + s_cpNetGroupsDict, + s_cpServicesDict, + s_paServicesTypesDict, + s_cpServicesGroupsDict, + s_paAppFiltersList, + s_cpAppGroupsDict, + s_cpSchedulesDict, + s_preRulebase, + s_postRulebase, + devicesGroupList, + _devicesUIDDict + ); + s_cpNetGroupsDict.Clear();//to avoid duplication of device groups + 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; + _rulesInConvertedPackage = -1; + _rulesInNatLayer = -1; + CleanCheckPointObjectsLists(); + + // changing target folder path to folder contains config file + ChangeTargetFolder(targetFolderMain, targetFileNameMain); + + // create HTML files which contain links to each report + CreateCatalogObjects(); + CreateCatalogNATs(); + CreateCatalogPolicies(); + CreateCatalogErrors(); + CreateCatalogWarnings(); + } + } + } + } + } + + RaiseConversionProgress(70, "Optimizing Firewall rulebase ..."); + RaiseConversionProgress(80, "Generating CLI scripts ..."); + + VendorHtmlFile = _vendorFilePath; + + ObjectsScriptFile = _targetFolder; + PolicyScriptFile = _targetFolder; + } + + /// + /// Creates network group object for panorama device group + /// + public List getPanoramaDeviceGroup(PA_DeviceGroupEntry deviceGroupEntry, Dictionary _devicesUIDDict) + { + List devices = deviceGroupEntry.DevicesGroupDevicesEntries; + List tags = deviceGroupEntry.TagsEntries; + List tagsList = new List(); + CheckPoint_NetworkGroup FWGroup; + List FWGroup_List = new List(); + + foreach (PA_DevicesGroupDevicesEntry deviceEntry in devices) + { + string deviceName = null; + if (_devicesUIDDict.ContainsKey(deviceEntry.Name)) + { + deviceName = _devicesUIDDict[deviceEntry.Name]; + } + + FWGroup = new CheckPoint_NetworkGroup(); + FWGroup.Name = "FW_" + deviceName; + FWGroup.IsPanoramaDeviceGroup = true; + foreach (PA_TagEntry tagEntry in tags) + { + tagsList.Add(tagEntry.Name); + } + FWGroup.Tags.AddRange(tagsList); + FWGroup_List.Add(FWGroup); + } + + return FWGroup_List; + } + + public void ConvertPaDeviceGroupEntry(string targetFolderNew, string targetFileNameNew, PA_DeviceGroupEntry paDeviceGroupEntry, Dictionary> devgroupZoneDictionary, + List s_TagEntries, + Dictionary s_cpAddressesDict, + Dictionary s_cpNetGroupsDict, + Dictionary s_cpServicesDict, + Dictionary s_paServicesTypesDict, + Dictionary s_cpServicesGroupsDict, + List s_paAppFiltersList, + Dictionary s_cpAppGroupsDict, + Dictionary> s_cpSchedulesDict, + PA_PreRulebase s_preRulebase, + PA_PostRulebase s_postRulebase, + List devicesGroupList, + Dictionary _devicesUIDDict + ) + { + RaiseConversionProgress(35, "Convert configuration..."); + RaiseConversionProgress(40, "Convert objects..."); + + _cpObjects.Initialize(); // must be first!!! + CleanCheckPointObjectsLists(); // must be first!!! + + //change folder path for writing reports + //if there are several device groups then each report will be placed to separate folder + //if only one device group exists then report will be in the same folder as config file + ChangeTargetFolder(targetFolderNew, targetFileNameNew); + + //convert PaloAlto Ojbects to CheckPoint Objects and save them to correspondings List + + Dictionary cpZonesDict = null; + + if (devgroupZoneDictionary.ContainsKey(paDeviceGroupEntry.Name)) + { + cpZonesDict = ConvertZones(devgroupZoneDictionary[paDeviceGroupEntry.Name]); + } + + Dictionary cpAddressesDict = ConvertAddresses(paDeviceGroupEntry, s_cpAddressesDict); + + Dictionary cpNetGroupsDict = ConvertAddressesGroupsWithInspection(paDeviceGroupEntry, cpAddressesDict, s_cpNetGroupsDict, s_TagEntries); + + Dictionary cpServicesDict = ConvertServices(paDeviceGroupEntry, s_cpServicesDict); + + Dictionary paServicesTypesDict = GetServicesTypes(paDeviceGroupEntry, s_paServicesTypesDict); + + Dictionary cpServicesGroupsDict = ConvertServicesGroupsWithInspection(paDeviceGroupEntry, cpServicesDict, s_cpServicesGroupsDict); + + List appsMatchList = GetApplicationsMatchList(); + + List paAppFiltersList = GetPAApplicationsFilters(paDeviceGroupEntry, s_paAppFiltersList); + + Dictionary cpAppGroupsDict = + ConvertApplicationsGroups(new List(paDeviceGroupEntry.ApplicationGroupsEntries), appsMatchList, s_cpAppGroupsDict, paAppFiltersList, cpServicesGroupsDict); + + Dictionary> cpSchedulesDict = null; + if (s_cpSchedulesDict != null) + cpSchedulesDict = new Dictionary>(s_cpSchedulesDict); + else + cpSchedulesDict = new Dictionary>(); + ConvertSchedules(paDeviceGroupEntry).ForEach(x => + { + string key = x.Name; + x = InspectCpScheduleName(x); + List cpTimesList = null; + if (cpSchedulesDict.ContainsKey(key)) + cpTimesList = cpSchedulesDict[key]; + else + cpTimesList = new List(); + cpTimesList.Add(x); + cpSchedulesDict[key] = cpTimesList; + }); + + Dictionary cpAccessRolesDict = new Dictionary(); + + RaiseConversionProgress(60, "Convert policy..."); + + ConvertSecurityPolicy(paDeviceGroupEntry, cpZonesDict, + cpAddressesDict, cpNetGroupsDict, + cpServicesDict, cpServicesGroupsDict, + appsMatchList, cpAppGroupsDict, paAppFiltersList, + cpSchedulesDict, cpAccessRolesDict, s_preRulebase, s_postRulebase, devicesGroupList, _devicesUIDDict); + + (new List(cpAccessRolesDict.Values)).ForEach(x => AddCheckPointObject(x)); + + if (_isNatConverted) + { + ConvertNatPolicy(paDeviceGroupEntry, cpAddressesDict, cpNetGroupsDict, cpServicesDict, paServicesTypesDict, cpServicesGroupsDict, devicesGroupList, _devicesUIDDict); + } + + //if non-optimized convert method is used then all objects are added + + if (!OptimizeConf) + { + if (cpZonesDict != null) + (new List(cpZonesDict.Values)).ForEach(x => AddCheckPointObject(x)); + + (new List(cpAddressesDict.Values)).ForEach(x => AddCheckPointObject(x)); + (new List(cpNetGroupsDict.Values)).ForEach(x => AddCheckPointObject(x)); + (new List(cpServicesDict.Values)).ForEach(x => + { + if (x.GetType() != typeof(CheckPoint_PredifinedObject)) + { + AddCheckPointObject(x); + } + }); + + (new List(cpServicesGroupsDict.Values)).ForEach(x => AddCheckPointObject(x)); + (new List(cpAppGroupsDict.Values)).ForEach(x => AddCheckPointObject(x)); + (new List>(cpSchedulesDict.Values)).ForEach(x => x.ForEach(y => AddCheckPointObject(y))); + } + + //Creating Result Files in Scripting Format and their reports in HTML format + //Console.WriteLine("Create object scripts..."); + CreateObjectsScript(); + CreateObjectsHtml(); + + CreatePackagesScript(); + ExportPolicyPackagesAsHtmlConfig(); + + CreateErrorsHtml(targetFileNameNew); + CreateWarningsHtml(targetFileNameNew); + + ExportNatLayerAsHtml(); + + _warningsConvertedPackage = _warningsList.Count; + _errorsConvertedPackage = _errorsList.Count; + + CreateSmartConnector(); + + // to clean; must be the last!!! + _cpObjects.ClearRepository(); + CleanSavedData(); + } + + public void CleanSavedData() + { + _errorsList.Clear(); + _warningsList.Clear(); + _timeCutterCounter = 0; + _numPostfix = 0; + _objectsNamesSet.Clear(); + } + + public string InspectObjectName(string objName, string objType) + { + string objNameNew = ""; + + string[] reservedWords = new string[] + { + "all", "All", "and", "any", "Any", + "apr", "Apr", "april", "April", "aug", "Aug", "august", "August", + "black", "blackboxs", "blue", "broadcasts", "call", "comment", + "conn", "date", "day", "debug", "dec", "Dec", "december", "December", + "deffunc", "define", "delete", "delstate", "direction", "do", "domains", + "drop", "dst", "dynamic", "else", "expcall", "expires", "export", "fcall", + "feb", "Feb", "february", "February", "firebrick", "foreground", "forest", + "format", "fri", "Fri", "friday", "Friday", "from", "fw1", "FW1", "fwline", + "fwrule", "gateways", "get", "getstate", "gold", "gray", "green", "hashsize", + "hold", "host", "hosts", "if", "ifaddr", "ifid", "implies", "in", "inbound", + "instate", "interface", "interfaces", "ipsecdata", "ipsecmethods", "is", + "jan", "Jan", "january", "January", "jul", "Jul", "july", "July", "jun", + "Jun", "june", "June", "kbuf", "keep", "limit", "local", "localhost", "log", + "LOG", "logics", "magenta", "mar", "Mar", "march", "March", "may", "May", + "mday", "medium", "modify", "mon", "Mon", "monday", "Monday", "month", + "mortrap", "navy", "netof", "nets", "nexpires", "not", "nov", "Nov", + "november", "November", "oct", "Oct", "october", "October", "or", + "orange", "origdport", "origdst", "origsport", "origsrc", "other", + "outbound", "packet", "packetid", "packetlen", "pass", "r_arg", + "r_call_counter", "r_cdir", "r_cflags", "r_chandler", "r_client_community", + "r_client_ifs_grp", "r_community_left", "r_connarg", "r_crule", "r_ctimeout", + "r_ctype", "r_curr_feature_id", "r_data_offset", "r_dtmatch", "r_dtmflags", + "r_entry", "r_g_offset", "r_ipv6", "r_mapped_ip", "r_mflags", "r_mhandler", + "r_mtimeout", "r_oldcdir", "r_pflags", "r_profile_id", "r_ro_client_community", + "r_ro_dst_sr", "r_ro_server_community", "r_ro_src_sr", "r_scvres", + "r_server_community", "r_server_ifs_grp", "r_service_id", "r_simple_hdrlen", + "r_spii_ret", "r_spii_tcpseq", "r_spii_uuid1", "r_spii_uuid2", "r_spii_uuid3", + "r_spii_uuid4", "r_str_dport", "r_str_dst", "r_str_ipp", "r_str_sport", + "r_str_src", "r_user", "record", "red", "refresh", "reject", "routers", + "sat", "Sat", "saturday", "Saturday", "second", "sep", "Sep", "september", + "September", "set", "setstate", "skipme", "skippeer", "sr", "src", "static", + "sun", "Sun", "sunday", "Sunday", "switchs", "sync", "targets", "thu", "Thu", + "thursday", "Thursday", "to", "tod", "tue", "Tue", "tuesday", "Tuesday", "ufp", + "vanish", "vars", "wasskipped", "wed", "Wed", "wednesday", "Wednesday", + "while", "xlatedport", "xlatedst", "xlatemethod", "xlatesport", "xlatesrc", + "xor", "year", "zero", "zero_ip", "mon", "Mon", "monday", "Monday", "tue", + "Tue", "tuesday", "Tuesday", "wed", "Wed", "wednesday", "Wednesday", "thu", + "Thu", "thursday", "Thursday", "fri", "Fri", "friday", "Friday", "sat", "Sat", + "saturday", "Saturday", "sun", "Sun", "sunday", "Sunday", "jan", "Jan", + "january", "January", "feb", "Feb", "february", "February", "mar", "Mar", + "march", "March", "apr", "Apr", "april", "April", "may", "May", "jun", "Jun", + "june", "June", "jul", "Jul", "july", "July", "aug", "Aug", "august", "August", + "sep", "Sep", "september", "September", "oct", "Oct", "october", "October", + "nov", "Nov", "november", "November", "dec", "Dec", "december", "December", + "date", "day", "month", "year", "black", "blue", "cyan", "dark", "firebrick", + "foreground", "forest", "gold", "gray", "green", "magenta", "medium", "navy", + "orange", "red", "sienna", "yellow", "dark", "light", "medium" + }; + + if (reservedWords.Contains(objName)) + { + objNameNew += "_" + objName; + _warningsList.Add(objName + " " + objType.Trim() + " was renamed to " + objNameNew); + objName = objNameNew; + } + + objNameNew = GetSafeName(objName); + if (!objNameNew.Equals(objName)) + { + _warningsList.Add(objName + " " + objType.Trim() + " was renamed to " + objNameNew); + objName = objNameNew; + } + + if (!_objectsNamesSet.Add(objName.ToLower())) + { + objNameNew = objName + "_" + _numPostfix++; + _warningsList.Add(objName + " " + objType.Trim() + " was renamed to " + objNameNew); + objName = objNameNew; + _objectsNamesSet.Add(objName.ToLower()); + } + return objName; + } + + #endregion + + #region Convert Zones + + public Dictionary ConvertZones(List zoneEntries) + { + Dictionary cpZonesDict = new Dictionary(); + + if (zoneEntries != null) + { + foreach (PA_ZoneEntry paZoneEntry in zoneEntries) + { + CheckPoint_Zone cpZone = new CheckPoint_Zone(); + cpZone.Name = InspectObjectName(paZoneEntry.Name, CP_OBJECT_TYPE_NAME_ZONE); + cpZone.Name = cpZone.SafeName(); + cpZone.Comments = paZoneEntry.Description; + cpZone.Tags = paZoneEntry.TagMembers; + cpZonesDict[paZoneEntry.Name] = cpZone; + } + } + + return cpZonesDict; + } + + #endregion + + #region Convert Addresses and Addresses Groups + + public Dictionary ConvertAddresses(PA_Objects paObjects, Dictionary s_cpAddressesDict) + { + Dictionary cpAddressesDict = null; + if (s_cpAddressesDict != null) + cpAddressesDict = new Dictionary(s_cpAddressesDict); + else + cpAddressesDict = new Dictionary(); + + if (paObjects.AddressEntries != null) + { + foreach (PA_AddressEntry paAddressEntry in paObjects.AddressEntries) + { + if (!string.IsNullOrWhiteSpace(paAddressEntry.IpNetmask)) + { + int indexSlash = paAddressEntry.IpNetmask.IndexOf("/"); + + if (indexSlash != -1 && paAddressEntry.IpNetmask.Substring(indexSlash + 1).Trim().Equals(NETWORK_NETMASK)) + { + CheckPoint_Host cpHost = new CheckPoint_Host(); + cpHost.Name = InspectObjectName(paAddressEntry.Name, CP_OBJECT_TYPE_NAME_ADDRESS_HOST); + cpHost.Comments = paAddressEntry.Description; + cpHost.Tags = paAddressEntry.TagMembers; + cpHost.IpAddress = paAddressEntry.IpNetmask.Substring(0, indexSlash); + cpAddressesDict[paAddressEntry.Name] = cpHost; + } + else if (indexSlash != -1 && !paAddressEntry.IpNetmask.Substring(indexSlash + 1).Trim().Equals(NETWORK_NETMASK)) + { + CheckPoint_Network cpNetwork = new CheckPoint_Network(); + cpNetwork.Name = InspectObjectName(paAddressEntry.Name, CP_OBJECT_TYPE_NAME_ADDRESS_NETWORK); + cpNetwork.Comments = paAddressEntry.Description; + cpNetwork.Tags = paAddressEntry.TagMembers; + cpNetwork.Subnet = paAddressEntry.IpNetmask.Substring(0, indexSlash); + cpNetwork.Netmask = IPNetwork.Parse(paAddressEntry.IpNetmask).Netmask.ToString(); + cpAddressesDict[paAddressEntry.Name] = cpNetwork; + } + else if (indexSlash == -1) + { + CheckPoint_Host cpHost = new CheckPoint_Host(); + cpHost.Name = InspectObjectName(paAddressEntry.Name, CP_OBJECT_TYPE_NAME_ADDRESS_HOST); + cpHost.Comments = paAddressEntry.Description; + cpHost.Tags = paAddressEntry.TagMembers; + cpHost.IpAddress = paAddressEntry.IpNetmask; + cpAddressesDict[paAddressEntry.Name] = cpHost; + } + } + + if (!string.IsNullOrWhiteSpace(paAddressEntry.IpRange)) + { + int indexDash = paAddressEntry.IpRange.IndexOf("-"); + + CheckPoint_Range cpRange = new CheckPoint_Range(); + cpRange.Name = InspectObjectName(paAddressEntry.Name, CP_OBJECT_TYPE_NAME_ADDRESS_RANGE); + cpRange.Comments = paAddressEntry.Description; + cpRange.Tags = paAddressEntry.TagMembers; + cpRange.RangeFrom = paAddressEntry.IpRange.Substring(0, indexDash); + cpRange.RangeTo = paAddressEntry.IpRange.Substring(indexDash + 1); + cpAddressesDict[paAddressEntry.Name] = cpRange; + + } + + if (!string.IsNullOrWhiteSpace(paAddressEntry.Fqdn)) + { + int index = (new List(cpAddressesDict.Values)).FindIndex(x => x.GetType() == typeof(CheckPoint_Domain) && x.Name.Equals("." + paAddressEntry.Fqdn)); + CheckPoint_Domain cpDomain = null; + if (index == -1) + { + cpDomain = new CheckPoint_Domain(); + cpDomain.Name = "." + paAddressEntry.Fqdn; + cpDomain.Comments = paAddressEntry.Description; + cpDomain.Tags = paAddressEntry.TagMembers; + } + else + { + cpDomain = (CheckPoint_Domain)(new List(cpAddressesDict.Values))[index]; + } + cpAddressesDict[paAddressEntry.Name] = cpDomain; + } + } + } + + return cpAddressesDict; + } + + public Dictionary ConvertAddressesGroups(PA_Objects paObjects, List s_TagEntries, + List cpAddressesList, + Dictionary s_cpNetGroupsDict + ) + { + Dictionary cpAddressesGroupsDict = null; + if (s_cpNetGroupsDict != null) + cpAddressesGroupsDict = new Dictionary(s_cpNetGroupsDict); + else + cpAddressesGroupsDict = new Dictionary(); + + + List cpNetGrpList = new List(); + if (s_cpNetGroupsDict != null) + cpNetGrpList.AddRange((new List(s_cpNetGroupsDict.Values))); + + if (paObjects.AddressGroupEntries != null) + { + foreach (PA_AddressGroupEntry paAddressGroupEntry in paObjects.AddressGroupEntries) + { + CheckPoint_NetworkGroup cpNetGroup = new CheckPoint_NetworkGroup(); + cpNetGroup.Name = paAddressGroupEntry.Name; + cpNetGroup.Comments = paAddressGroupEntry.Description; + cpNetGroup.Tags = paAddressGroupEntry.TagMembers; + cpNetGrpList.Add(cpNetGroup); + } + } + + Dictionary> tagsToMembersDict = GetDictTagsToNames(paObjects, s_TagEntries, cpAddressesList, cpNetGrpList); + + if (paObjects.AddressGroupEntries != null) + { + foreach (PA_AddressGroupEntry paAddressGroupEntry in paObjects.AddressGroupEntries) + { + CheckPoint_NetworkGroup cpNetGroup = new CheckPoint_NetworkGroup(); + + cpNetGroup.Name = InspectObjectName(GetSafeName(paAddressGroupEntry.Name), CP_OBJECT_TYPE_NAME_ADDRESS_GROUP); + + cpNetGroup.Comments = paAddressGroupEntry.Description; + cpNetGroup.Tags = paAddressGroupEntry.TagMembers; + + if (paAddressGroupEntry.StaticMembers != null && paAddressGroupEntry.StaticMembers.Count > 0) + { + cpNetGroup.Members = paAddressGroupEntry.StaticMembers; + } + + else if (paAddressGroupEntry.Dynamic != null && !string.IsNullOrWhiteSpace(paAddressGroupEntry.Dynamic.Filter)) + { + string adjustedFilter = paAddressGroupEntry.Dynamic.Filter.Trim('\'').Trim('"').Trim(); + + if (tagsToMembersDict.ContainsKey(adjustedFilter)) + { + if (!cpNetGroup.IsPanoramaDeviceGroup) + cpNetGroup.Members = tagsToMembersDict[adjustedFilter]; + } + else + { + _errorsList.Add(cpNetGroup.Name + " dynamic network group is not converted because the filter is too complex"); + cpNetGroup = null; + } + } + + if (cpNetGroup != null) + { + cpAddressesGroupsDict[paAddressGroupEntry.Name] = cpNetGroup; + } + } + } + + return cpAddressesGroupsDict; + } + + public Dictionary> GetDictTagsToNames(PA_Objects paObjects, List s_TagEntries, + List cpAddressesList, List cpNetGrpList) + { + Dictionary> tagsToNamesDict = new Dictionary>(); + + List tagEntriesList = new List(); + if (s_TagEntries != null) + tagEntriesList.AddRange(s_TagEntries); + + tagEntriesList.AddRange(paObjects.TagsEntries); + + foreach (PA_TagEntry paTagEntry in tagEntriesList) + { + if (tagsToNamesDict.ContainsKey(paTagEntry.Name)) + continue; + + List namesList = new List(); + + if (cpAddressesList != null) + { + foreach (CheckPointObject cpAddressEntry in cpAddressesList) + { + if (cpAddressEntry.Tags.Contains(paTagEntry.Name)) + { + namesList.Add(cpAddressEntry.Name); + } + } + } + + if (cpNetGrpList != null) + { + foreach (CheckPoint_NetworkGroup cpAddressGroupEntry in cpNetGrpList) + { + if (cpAddressGroupEntry.Tags.Contains(paTagEntry.Name)) + { + namesList.Add(cpAddressGroupEntry.Name); + } + } + } + + tagsToNamesDict.Add(paTagEntry.Name, namesList); + } + + return tagsToNamesDict; + } + public Dictionary ConvertAddressesGroupsWithInspection(PA_Objects paDeviceGroupEntry, + Dictionary cpAddressesDict, + Dictionary s_cpNetGroupsDict, + List s_TagEntries + ) + { + Dictionary cpNetGroupsDict = + ConvertAddressesGroups(paDeviceGroupEntry, s_TagEntries, (new List(cpAddressesDict.Values)), s_cpNetGroupsDict); + + if (s_cpNetGroupsDict == null) + { + return cpNetGroupsDict;//don't inspect address groups from shared section because they will be inspected further while device-group processing + } + else + { + Dictionary cpNetGroupsResult = InspectAddressGroups(cpAddressesDict, cpNetGroupsDict, null); + + return cpNetGroupsResult; + } + + + } + + public Dictionary InspectAddressGroups(Dictionary cpAddressesNamesDict, + Dictionary cpNetGroupsCheck, + Dictionary cpNetGroupsTemp) + { + Dictionary cpNetGroupsResult = null; + if (cpNetGroupsTemp != null) + { + cpNetGroupsResult = new Dictionary(cpNetGroupsTemp); + } + else + { + cpNetGroupsResult = new Dictionary(); + } + + while (cpNetGroupsCheck.Count > 0) + { + string paNetGroupName = new List(cpNetGroupsCheck.Keys)[0]; + CheckPoint_NetworkGroup cpNetGroupCheck = cpNetGroupsCheck[paNetGroupName]; + cpNetGroupsCheck.Remove(paNetGroupName); + + CheckPoint_NetworkGroup cpNetGroupResult = new CheckPoint_NetworkGroup(); + cpNetGroupResult.Name = cpNetGroupCheck.Name; + cpNetGroupResult.Comments = cpNetGroupCheck.Comments; + cpNetGroupResult.Tags = cpNetGroupCheck.Tags; + cpNetGroupResult.IsPanoramaDeviceGroup = cpNetGroupCheck.IsPanoramaDeviceGroup; + + foreach (string member in cpNetGroupCheck.Members) + { + + if (cpAddressesNamesDict.ContainsKey(member)) //group member is in Addresses + { + cpNetGroupResult.Members.Add(cpAddressesNamesDict[member].Name); + } + else if (cpNetGroupsResult.ContainsKey(member)) //group member is converted and added to Addresses Groups + { + cpNetGroupResult.Members.Add(cpNetGroupsResult[member].Name); + } + else if (cpNetGroupsCheck.ContainsKey(member)) //group member is not converted yet + { + cpNetGroupsResult = InspectAddressGroups(cpAddressesNamesDict, cpNetGroupsCheck, cpNetGroupsResult); + + if (cpNetGroupsResult.ContainsKey(member)) + { + cpNetGroupResult.Members.Add(cpNetGroupsResult[member].Name); + } + else + { + _warningsList.Add(cpNetGroupCheck.Name + " address group contains non-existing member: " + member); + } + } + else + { + _warningsList.Add(cpNetGroupCheck.Name + " address group contains non-existing member: " + member); + } + } + + cpNetGroupsResult.Add(paNetGroupName, cpNetGroupResult); + } + + return cpNetGroupsResult; + } + + #endregion + + #region Convert Schedules + + public List ConvertSchedules(PA_Objects paObjects) + { + List cpTimesList = new List(); + + if (paObjects.ScheduleEntries != null) + { + foreach (PA_ScheduleEntry paScheduleEntry in paObjects.ScheduleEntries) + { + if (paScheduleEntry.Type.Recurring != null) + { + if (paScheduleEntry.Type.Recurring.MembersDaily != null) + { + for (int i = 0; i < paScheduleEntry.Type.Recurring.MembersDaily.Count; i += 3) + { + List timesList = + paScheduleEntry.Type.Recurring.MembersDaily.GetRange(i, Math.Min(3, paScheduleEntry.Type.Recurring.MembersDaily.Count - i)); + + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Name = paScheduleEntry.Name; + cpTime.Comments = paScheduleEntry.Description; + cpTime.Tags = paScheduleEntry.TagMembers; + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Daily; + cpTime.StartNow = true; + cpTime.EndNever = true; + + cpTime = SetHourseRanges(cpTime, timesList); + + cpTimesList.Add(cpTime); + } + } + if (paScheduleEntry.Type.Recurring.Weekly != null) + { + if (paScheduleEntry.Type.Recurring.Weekly.MembersMonday != null) + { + for (int i = 0; i < paScheduleEntry.Type.Recurring.Weekly.MembersMonday.Count; i += 3) + { + List timesList = + paScheduleEntry.Type.Recurring.Weekly.MembersMonday.GetRange(i, Math.Min(3, paScheduleEntry.Type.Recurring.Weekly.MembersMonday.Count - i)); + + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Name = paScheduleEntry.Name; + cpTime.Comments = paScheduleEntry.Description; + cpTime.Tags = paScheduleEntry.TagMembers; + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Weekly; + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Mon); + cpTime.StartNow = true; + cpTime.EndNever = true; + + cpTime = SetHourseRanges(cpTime, timesList); + + cpTimesList.Add(cpTime); + } + } + if (paScheduleEntry.Type.Recurring.Weekly.MembersTuesday != null) + { + for (int i = 0; i < paScheduleEntry.Type.Recurring.Weekly.MembersTuesday.Count; i += 3) + { + List timesList = + paScheduleEntry.Type.Recurring.Weekly.MembersTuesday.GetRange(i, Math.Min(3, paScheduleEntry.Type.Recurring.Weekly.MembersTuesday.Count - i)); + + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Name = paScheduleEntry.Name; + cpTime.Comments = paScheduleEntry.Description; + cpTime.Tags = paScheduleEntry.TagMembers; + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Weekly; + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Tue); + cpTime.StartNow = true; + cpTime.EndNever = true; + + cpTime = SetHourseRanges(cpTime, timesList); + + cpTimesList.Add(cpTime); + } + } + if (paScheduleEntry.Type.Recurring.Weekly.MembersWednesday != null) + { + for (int i = 0; i < paScheduleEntry.Type.Recurring.Weekly.MembersWednesday.Count; i += 3) + { + List timesList = + paScheduleEntry.Type.Recurring.Weekly.MembersWednesday.GetRange(i, Math.Min(3, paScheduleEntry.Type.Recurring.Weekly.MembersWednesday.Count - i)); + + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Name = paScheduleEntry.Name; + cpTime.Comments = paScheduleEntry.Description; + cpTime.Tags = paScheduleEntry.TagMembers; + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Weekly; + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Wed); + cpTime.StartNow = true; + cpTime.EndNever = true; + + cpTime = SetHourseRanges(cpTime, timesList); + + cpTimesList.Add(cpTime); + } + } + if (paScheduleEntry.Type.Recurring.Weekly.MembersThursday != null) + { + for (int i = 0; i < paScheduleEntry.Type.Recurring.Weekly.MembersThursday.Count; i += 3) + { + List timesList = + paScheduleEntry.Type.Recurring.Weekly.MembersThursday.GetRange(i, Math.Min(3, paScheduleEntry.Type.Recurring.Weekly.MembersThursday.Count - i)); + + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Name = paScheduleEntry.Name; + cpTime.Comments = paScheduleEntry.Description; + cpTime.Tags = paScheduleEntry.TagMembers; + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Weekly; + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Thu); + cpTime.StartNow = true; + cpTime.EndNever = true; + + cpTime = SetHourseRanges(cpTime, timesList); + + cpTimesList.Add(cpTime); + } + } + if (paScheduleEntry.Type.Recurring.Weekly.MembersFriday != null) + { + for (int i = 0; i < paScheduleEntry.Type.Recurring.Weekly.MembersFriday.Count; i += 3) + { + List timesList = + paScheduleEntry.Type.Recurring.Weekly.MembersFriday.GetRange(i, Math.Min(3, paScheduleEntry.Type.Recurring.Weekly.MembersFriday.Count - i)); + + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Name = paScheduleEntry.Name; + cpTime.Comments = paScheduleEntry.Description; + cpTime.Tags = paScheduleEntry.TagMembers; + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Weekly; + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Fri); + cpTime.StartNow = true; + cpTime.EndNever = true; + + cpTime = SetHourseRanges(cpTime, timesList); + + cpTimesList.Add(cpTime); + } + } + if (paScheduleEntry.Type.Recurring.Weekly.MembersSaturday != null) + { + for (int i = 0; i < paScheduleEntry.Type.Recurring.Weekly.MembersSaturday.Count; i += 3) + { + List timesList = + paScheduleEntry.Type.Recurring.Weekly.MembersSaturday.GetRange(i, Math.Min(3, paScheduleEntry.Type.Recurring.Weekly.MembersSaturday.Count - i)); + + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Name = paScheduleEntry.Name; + cpTime.Comments = paScheduleEntry.Description; + cpTime.Tags = paScheduleEntry.TagMembers; + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Weekly; + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Sat); + cpTime.StartNow = true; + cpTime.EndNever = true; + + cpTime = SetHourseRanges(cpTime, timesList); + + cpTimesList.Add(cpTime); + } + } + if (paScheduleEntry.Type.Recurring.Weekly.MembersSunday != null) + { + for (int i = 0; i < paScheduleEntry.Type.Recurring.Weekly.MembersSunday.Count; i += 3) + { + List timesList = + paScheduleEntry.Type.Recurring.Weekly.MembersSunday.GetRange(i, Math.Min(3, paScheduleEntry.Type.Recurring.Weekly.MembersSunday.Count - i)); + + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Name = paScheduleEntry.Name; + cpTime.Comments = paScheduleEntry.Description; + cpTime.Tags = paScheduleEntry.TagMembers; + cpTime.RecurrencePattern = CheckPoint_Time.RecurrencePatternEnum.Weekly; + cpTime.RecurrenceWeekdays.Add(CheckPoint_Time.Weekdays.Sun); + cpTime.StartNow = true; + cpTime.EndNever = true; + + cpTime = SetHourseRanges(cpTime, timesList); + + cpTimesList.Add(cpTime); + } + } + } + } + else if (paScheduleEntry.Type.NonRecurring != null) + { + foreach (string member in paScheduleEntry.Type.NonRecurring.Memebers) + { + int indexDash = member.IndexOf("-"); + + if (indexDash == -1) + { + continue; + } + + CheckPoint_Time cpTime = new CheckPoint_Time(); + cpTime.Name = paScheduleEntry.Name; + cpTime.Comments = paScheduleEntry.Description; + cpTime.Tags = paScheduleEntry.TagMembers; + + cpTime.StartNow = false; + cpTime.EndNever = false; + + DateTime dateStart = DateTime.ParseExact(member.Substring(0, indexDash), "yyyy/MM/dd@HH:mm", System.Globalization.CultureInfo.InvariantCulture); + cpTime.StartDate = dateStart.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture); + cpTime.StartTime = dateStart.ToString("HH:mm"); + + DateTime dateEnd = DateTime.ParseExact(member.Substring(indexDash + 1), "yyyy/MM/dd@HH:mm", System.Globalization.CultureInfo.InvariantCulture); + cpTime.EndDate = dateEnd.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture); + cpTime.EndTime = dateEnd.ToString("HH:mm"); + + cpTimesList.Add(cpTime); + } + } + } + } + return cpTimesList; + } + + private CheckPoint_Time SetHourseRanges(CheckPoint_Time cpTime, List timesList) + { + for (int j = 0; j < timesList.Count; j++) + { + int indexDash = timesList[j].IndexOf("-"); + if (indexDash == -1) + { + continue; + } + switch (j) + { + case 0: + cpTime.HoursRangesEnabled_1 = true; + cpTime.HoursRangesFrom_1 = timesList[j].Substring(0, indexDash); + cpTime.HoursRangesTo_1 = timesList[j].Substring(indexDash + 1); + break; + case 1: + cpTime.HoursRangesEnabled_2 = true; + cpTime.HoursRangesFrom_2 = timesList[j].Substring(0, indexDash); + cpTime.HoursRangesTo_2 = timesList[j].Substring(indexDash + 1); + break; + case 2: + cpTime.HoursRangesEnabled_3 = true; + cpTime.HoursRangesFrom_3 = timesList[j].Substring(0, indexDash); + cpTime.HoursRangesTo_3 = timesList[j].Substring(indexDash + 1); + break; + } + } + + return cpTime; + } + + public CheckPoint_Time InspectCpScheduleName(CheckPoint_Time cpTime) + { + string cpTimeName = cpTime.Name; + if (cpTimeName.Length > 11) + { + cpTimeName = cpTimeName.Substring(0, 5) + "_t" + _timeCutterCounter++; + } + + if (!_timesNamesSet.Add(cpTimeName)) + { + cpTimeName = cpTimeName.Substring(0, 5) + "_t" + _timeCutterCounter++; + } + + if (!cpTimeName.Equals(cpTime.Name)) + { + _warningsList.Add(cpTime.Name + " time object was renamed to " + cpTimeName); + cpTime.Name = cpTimeName; + } + return cpTime; + } + + #endregion + + #region Convert Services and Services Groups + + public Dictionary GetServicesTypes(PA_Objects paObjects, Dictionary s_paServicesTypesDict) + { + Dictionary paServicesTypesDict = null; + if (s_paServicesTypesDict != null) + paServicesTypesDict = new Dictionary(s_paServicesTypesDict); + else + paServicesTypesDict = new Dictionary(); + + if (paObjects.ServiceEntries != null) + { + foreach (PA_ServiceEntry paServiceEntry in paObjects.ServiceEntries) + { + if (paServiceEntry.Protocol != null) + { + if (paServiceEntry.Protocol.ServiceTcp != null && paServiceEntry.Protocol.ServiceTcp.Port != null) + { + paServicesTypesDict[paServiceEntry.Name] = SERVICE_TYPE_TCP; + } + + if (paServiceEntry.Protocol.ServiceUdp != null && paServiceEntry.Protocol.ServiceUdp.Port != null) + { + paServicesTypesDict[paServiceEntry.Name] = SERVICE_TYPE_UDP; + } + } + } + } + + return paServicesTypesDict; + } + + public Dictionary ConvertServices(PA_Objects paObjects, Dictionary s_cpServicesDict) + { + Dictionary cpServicesDict = null; + if (s_cpServicesDict != null) + cpServicesDict = new Dictionary(s_cpServicesDict); + else + cpServicesDict = new Dictionary(); + + Dictionary cpInspectedServicesDict = new Dictionary(); + foreach (string service in cpServicesDict.Keys) + { + cpInspectedServicesDict[service] = InspectService(cpServicesDict[service]); + } + cpServicesDict = cpInspectedServicesDict; + + + GetPredefinedServices().ForEach(x => cpServicesDict[x.Name] = InspectService(x)); + + if (paObjects.ServiceEntries != null) + { + foreach (PA_ServiceEntry paServiceEntry in paObjects.ServiceEntries) + { + if (paServiceEntry.Protocol != null) + { + if (paServiceEntry.Protocol.ServiceTcp != null && paServiceEntry.Protocol.ServiceTcp.Port != null) + { + string srvName = paServiceEntry.Name; + + if (!char.IsLetter(paServiceEntry.Name[0])) + { + srvName = SERVICE_TYPE_TCP + "_" + paServiceEntry.Name; + _warningsList.Add(paServiceEntry.Name + " service (TCP) was renamed to " + srvName); + } + + string[] ports = paServiceEntry.Protocol.ServiceTcp.Port.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); + string[] sourcePorts = new string[] { "" }; + if (paServiceEntry.Protocol.ServiceTcp.SourcePort != null) + { + sourcePorts = paServiceEntry.Protocol.ServiceTcp.SourcePort.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); + } + + if (ports.Length > 1 || sourcePorts.Length > 1) + { + //create group + CheckPoint_ServiceGroup cpServicesGrp = new CheckPoint_ServiceGroup(); + cpServicesGrp.Name = InspectObjectName(srvName, CP_OBJECT_TYPE_NAME_SERVICE_GROUP); + cpServicesGrp.Comments = paServiceEntry.Description; + cpServicesGrp.Tags = paServiceEntry.TagMembers; + _warningsList.Add(srvName + " tcp service is replaced by service group: " + cpServicesGrp.Name); + foreach (string port in ports) + { + foreach (string sourcePort in sourcePorts) + { + string srvNameNew = srvName; + srvNameNew += port.Trim().Equals("") ? "" : "_" + port; + srvNameNew += sourcePort.Trim().Equals("") ? "" : "_" + sourcePort; + CheckPoint_TcpService cpTcpService = new CheckPoint_TcpService(); + cpTcpService.Name = InspectObjectName(srvNameNew, CP_OBJECT_TYPE_NAME_SERVICE_TCP); + cpTcpService.Comments = paServiceEntry.Description; + cpTcpService.Tags = paServiceEntry.TagMembers; + cpTcpService.Port = AdjustPorts(port); + cpTcpService.SourcePort = AdjustPorts(sourcePort); + + CheckPointObject cpServiceChecked = InspectService(cpTcpService); + + cpServicesGrp.Members.Add(cpServiceChecked.Name); + cpServicesDict[cpServiceChecked.Name] = cpServiceChecked; + } + } + cpServicesDict[paServiceEntry.Name] = cpServicesGrp; + } + else + { + CheckPoint_TcpService cpTcpService = new CheckPoint_TcpService(); + + cpTcpService.Name = InspectObjectName(srvName, CP_OBJECT_TYPE_NAME_SERVICE_TCP); + + cpTcpService.Comments = paServiceEntry.Description; + cpTcpService.Tags = paServiceEntry.TagMembers; + cpTcpService.Port = AdjustPorts(paServiceEntry.Protocol.ServiceTcp.Port); + cpTcpService.SourcePort = AdjustPorts(paServiceEntry.Protocol.ServiceTcp.SourcePort); + + CheckPointObject cpServiceChecked = InspectService(cpTcpService); + + cpServicesDict[paServiceEntry.Name] = cpServiceChecked; + } + } + + if (paServiceEntry.Protocol.ServiceUdp != null && paServiceEntry.Protocol.ServiceUdp.Port != null) + { + string srvName = paServiceEntry.Name; + if (!char.IsLetter(paServiceEntry.Name[0])) + { + srvName = SERVICE_TYPE_UDP + "_" + paServiceEntry.Name; + _warningsList.Add(paServiceEntry.Name + " service (UDP) was renamed to " + srvName); + } + string[] ports = paServiceEntry.Protocol.ServiceUdp.Port.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); + string[] sourcePorts = new string[] { "" }; + if (paServiceEntry.Protocol.ServiceUdp.SourcePort != null) + { + sourcePorts = paServiceEntry.Protocol.ServiceUdp.SourcePort.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); + } + + if (ports.Length > 1 || sourcePorts.Length > 1) + { + //create group + CheckPoint_ServiceGroup cpServicesGrp = new CheckPoint_ServiceGroup(); + cpServicesGrp.Name = InspectObjectName(srvName, CP_OBJECT_TYPE_NAME_SERVICE_GROUP); + cpServicesGrp.Comments = paServiceEntry.Description; + cpServicesGrp.Tags = paServiceEntry.TagMembers; + _warningsList.Add(srvName + " udp service is replaced by service group: " + cpServicesGrp.Name); + foreach (string port in ports) + { + foreach (string sourcePort in sourcePorts) + { + string srvNameNew = srvName; + srvNameNew += port.Trim().Equals("") ? "" : "_" + port; + srvNameNew += sourcePort.Trim().Equals("") ? "" : "_" + sourcePort; + CheckPoint_UdpService cpUdpService = new CheckPoint_UdpService(); + cpUdpService.Name = InspectObjectName(srvNameNew, CP_OBJECt_TYPE_NAME_SERVICE_UDP); + cpUdpService.Comments = paServiceEntry.Description; + cpUdpService.Tags = paServiceEntry.TagMembers; + cpUdpService.Port = AdjustPorts(port); + cpUdpService.SourcePort = AdjustPorts(sourcePort); + + CheckPointObject cpServiceChecked = InspectService(cpUdpService); + cpServicesGrp.Members.Add(cpServiceChecked.Name); + cpServicesDict[cpServiceChecked.Name] = cpServiceChecked; + } + } + cpServicesDict[paServiceEntry.Name] = cpServicesGrp; + } + else + { + CheckPoint_UdpService cpUdpService = new CheckPoint_UdpService(); + cpUdpService.Name = InspectObjectName(srvName, CP_OBJECt_TYPE_NAME_SERVICE_UDP); + cpUdpService.Comments = paServiceEntry.Description; + cpUdpService.Tags = paServiceEntry.TagMembers; + cpUdpService.Port = AdjustPorts(paServiceEntry.Protocol.ServiceUdp.Port); + cpUdpService.SourcePort = AdjustPorts(paServiceEntry.Protocol.ServiceUdp.SourcePort); + + CheckPointObject cpServiceChecked = InspectService(cpUdpService); + cpServicesDict[paServiceEntry.Name] = cpServiceChecked; + } + } + } + } + } + return cpServicesDict; + } + + public List GetPredefinedServices() + { + List predefinedServices = new List(); + + CheckPoint_ServiceGroup cpServiceGroupHttp = new CheckPoint_ServiceGroup(); + cpServiceGroupHttp.Name = "service-http"; + cpServiceGroupHttp.Members.Add("http"); + cpServiceGroupHttp.Members.Add("HTTP_proxy"); + + predefinedServices.Add(cpServiceGroupHttp); + + CheckPoint_TcpService cpServiceHttps = new CheckPoint_TcpService(); + cpServiceHttps.Name = "service-https"; + cpServiceHttps.Port = "443"; + + predefinedServices.Add(cpServiceHttps); + + return predefinedServices; + } + + private string AdjustPorts(string input) + { + if (!string.IsNullOrWhiteSpace(input) && input.StartsWith("0")) + { + input = "1" + input.Substring(1); + } + return input; + } + + public CheckPointObject InspectService(CheckPointObject cpService) + { + CheckPointObject cpServiceRet = null; + + if (cpService.GetType() == typeof(CheckPoint_TcpService)) + { + CheckPoint_TcpService cpTcpService = (CheckPoint_TcpService)cpService; + bool isFound; + string cpServiceName = _cpObjects.GetKnownServiceName(SERVICE_TYPE_TCP + "_" + cpTcpService.Port, out isFound); + + if (isFound) + { + cpServiceRet = _cpObjects.GetObject(cpServiceName); + cpPredefServicesTypes[cpServiceRet.Name] = SERVICE_TYPE_TCP; + } + else + { + cpServiceRet = cpTcpService; + } + } + else if (cpService.GetType() == typeof(CheckPoint_UdpService)) + { + CheckPoint_UdpService cpUdpService = (CheckPoint_UdpService)cpService; + bool isFound; + string cpServiceName = _cpObjects.GetKnownServiceName(SERVICE_TYPE_UDP + "_" + cpUdpService.Port, out isFound); + + if (isFound) + { + cpServiceRet = _cpObjects.GetObject(cpServiceName); + cpPredefServicesTypes[cpServiceRet.Name] = SERVICE_TYPE_UDP; + } + else + { + cpServiceRet = cpUdpService; + } + } + else if (cpService.GetType() == typeof(CheckPoint_ServiceGroup)) + { + cpServiceRet = cpService; + } + else + { + _errorsList.Add(cpService.Name + " service is not TCP or UDP or service group."); + } + + return cpServiceRet; + } + + public Dictionary ConvertServicesGroups(PA_Objects paObjects, Dictionary s_cpServicesGroupsDict) + { + Dictionary cpServicesGroupsDict = null; + if (s_cpServicesGroupsDict != null) + cpServicesGroupsDict = new Dictionary(s_cpServicesGroupsDict); + else + cpServicesGroupsDict = new Dictionary(); + + if (paObjects.ServiceGroupEntries != null) + { + foreach (PA_ServiceGroupEntry paServiceGroupEntry in paObjects.ServiceGroupEntries) + { + CheckPoint_ServiceGroup cpServiceGroup = new CheckPoint_ServiceGroup(); + cpServiceGroup.Name = InspectObjectName(paServiceGroupEntry.Name, CP_OBJECT_TYPE_NAME_SERVICE_GROUP); + cpServiceGroup.Comments = paServiceGroupEntry.Description; + cpServiceGroup.Tags = paServiceGroupEntry.TagMembers; + cpServiceGroup.Members = paServiceGroupEntry.Members; + cpServicesGroupsDict[paServiceGroupEntry.Name] = cpServiceGroup; + } + } + + return cpServicesGroupsDict; + } + + public Dictionary ConvertServicesGroupsWithInspection(PA_Objects paObjects, Dictionary cpServicesDict, + Dictionary s_cpServicesGroupsDict) + { + Dictionary cpServicesGroupsCheck = ConvertServicesGroups(paObjects, s_cpServicesGroupsDict); + + Dictionary cpServicesGroupsResult = new Dictionary(); + + InspectServicesGroups(cpServicesDict, cpServicesGroupsCheck, cpServicesGroupsResult); + + return cpServicesGroupsResult; + } + + public void InspectServicesGroups(Dictionary cpServicesDict, + Dictionary cpServicesGroupsCheck, + Dictionary cpServicesGroupsResult) + { + while (cpServicesGroupsCheck.Count > 0) + { + string paSrvGroupName = new List(cpServicesGroupsCheck.Keys)[0]; + CheckPoint_ServiceGroup cpSrvGroupCheck = cpServicesGroupsCheck[paSrvGroupName]; + + cpServicesGroupsCheck.Remove(paSrvGroupName); + + InspectServicesGroup(paSrvGroupName, cpSrvGroupCheck, cpServicesDict, cpServicesGroupsCheck, cpServicesGroupsResult); + } + } + + public bool InspectServicesGroup(string paSrvGroupName, + CheckPoint_ServiceGroup cpServicesGroup, + Dictionary cpServicesDict, + Dictionary cpServicesGroupsCheck, + Dictionary cpServicesGroupsResult) + { + bool isOk = true; + + CheckPoint_ServiceGroup cpServicesGroupNew = new CheckPoint_ServiceGroup(); + cpServicesGroupNew.Name = cpServicesGroup.Name; + cpServicesGroupNew.Comments = cpServicesGroup.Comments; + cpServicesGroupNew.Tags = cpServicesGroup.Tags; + + foreach (string member in cpServicesGroup.Members) + { + //group member is in Services List + if (cpServicesDict.ContainsKey(member)) + { + cpServicesGroupNew.Members.Add(cpServicesDict[member].Name); + continue; + } + + //group member is Services Group and converted already + if (cpServicesGroupsResult.ContainsKey(member)) + { + cpServicesGroupNew.Members.Add(cpServicesGroupsResult[member].Name); + continue; + } + + //group member is Services Group and not converted yet + if (cpServicesGroupsCheck.ContainsKey(member)) + { + CheckPoint_ServiceGroup cpSrvGroupNew = cpServicesGroupsCheck[member]; + cpServicesGroupsCheck.Remove(member); + if (InspectServicesGroup(member, cpSrvGroupNew, cpServicesDict, cpServicesGroupsCheck, cpServicesGroupsResult)) + { + cpServicesGroupNew.Members.Add(cpSrvGroupNew.Name); + continue; + } + } + + isOk = false; + _errorsList.Add(cpServicesGroup.Name + " services group can not been converted becuase it contains non-existing member: " + member); + } + + if (isOk) + { + cpServicesGroupsResult[paSrvGroupName] = cpServicesGroupNew; + } + + return isOk; + } + + #endregion + + #region Convert Applications, Applications Groups and Applications Filters + + public List GetApplicationsMatchList() + { + return new List(File.ReadAllLines(PA_APPLICATIONS_FILE_NAME)); + } + + public Dictionary ConvertApplicationsGroups(List paAppsGroupsListCheck, + List appsMatchList, + Dictionary s_cpAppGroupDict, + List paAppFiltersList, + Dictionary cpServicesGroupsDict) + { + Dictionary cpAppGroupDict = null; + if (s_cpAppGroupDict != null) + cpAppGroupDict = new Dictionary(s_cpAppGroupDict); + else + cpAppGroupDict = new Dictionary(); + + if (paAppsGroupsListCheck != null) + { + while (paAppsGroupsListCheck.Count > 0) + { + PA_ApplicationGroupEntry paAppsGroupCheck = paAppsGroupsListCheck[0]; + paAppsGroupsListCheck.RemoveAt(0); + + CheckPoint_ApplicationGroup cpAppGroup = new CheckPoint_ApplicationGroup(); + cpAppGroup.Name = InspectObjectName(GetSafeName(paAppsGroupCheck.Name), CP_OBJECT_TYPE_NAME_APPLICATION_GROUP); + + CheckPoint_ServiceGroup cpServiceGroup = new CheckPoint_ServiceGroup(); + cpServiceGroup.Name = InspectObjectName(GetSafeName(paAppsGroupCheck.Name + "-svc"), CP_OBJECT_TYPE_NAME_APPLICATION_GROUP); + + + foreach (string appMember in paAppsGroupCheck.ApplicationGroupMembers) + { + string matchedLine = appsMatchList.Find(x => x.StartsWith(appMember + ";")); + if (!string.IsNullOrEmpty(matchedLine)) + { + string[] matchedArray = matchedLine.Split(';'); + if (!string.IsNullOrWhiteSpace(matchedArray[1])) + { + string[] matchedValues = matchedArray[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + foreach (string matchedValue in matchedValues) + { + if (!matchedValue.Trim().Equals("")) + { + cpAppGroup.Members.Add(matchedValue.Trim()); + } + } + } + else if (!string.IsNullOrWhiteSpace(matchedArray[2])) + { + string[] matchedValues = matchedArray[2].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + foreach (string matchedValue in matchedValues) + { + if (!matchedValue.Trim().Equals("")) + { + cpServiceGroup.Members.Add(matchedValue.Trim()); + + } + } + cpServicesGroupsDict[paAppsGroupCheck.Name + "-svc"] = cpServiceGroup; + } + else + { + _warningsList.Add(paAppsGroupCheck.Name + " application group contains non-mapped application: " + appMember); + } + } + else if (cpAppGroupDict.ContainsKey(appMember)) + { + cpAppGroup.Members.Add(cpAppGroupDict[appMember].Name); + } + else if (paAppFiltersList.Contains(appMember)) + { + _warningsList.Add(paAppsGroupCheck.Name + " application group contains application filter: " + appMember); + } + else if (paAppsGroupsListCheck.FindIndex(x => x.Name.Equals(appMember)) != -1) + { + cpAppGroupDict = ConvertApplicationsGroups(paAppsGroupsListCheck, appsMatchList, cpAppGroupDict, paAppFiltersList, cpServicesGroupsDict); + if (cpAppGroupDict.ContainsKey(appMember)) + { + cpAppGroup.Members.Add(cpAppGroupDict[appMember].Name); + } + else + { + _warningsList.Add(paAppsGroupCheck.Name + " application group contains unknown application: " + appMember); + } + } + else + { + _warningsList.Add(paAppsGroupCheck.Name + " application group contains unknown application: " + appMember); + } + } + + cpAppGroupDict[paAppsGroupCheck.Name] = cpAppGroup; + } + } + + return cpAppGroupDict; + } + + public List GetPAApplicationsFilters(PA_Objects paObjects, List s_cpAppFiltersDict) + { + List paAppFiltersList = null; + if (s_cpAppFiltersDict != null) + paAppFiltersList = new List(s_cpAppFiltersDict); + else + paAppFiltersList = new List(); + + if (paObjects.ApplicationFiltersEntries != null) + { + foreach (PA_ApplicationFilterEntry paAppFilterEntry in paObjects.ApplicationFiltersEntries) + { + paAppFiltersList.Add(paAppFilterEntry.Name); + } + } + + return paAppFiltersList; + } + + #endregion + + #region Convert Security Policy + + public void ConvertSecurityPolicy(PA_DeviceGroupEntry paDeviceGroupEntry, + Dictionary cpZonesDict, + Dictionary cpAddressesDict, + Dictionary cpNetGroupsDict, + Dictionary cpServicesDict, + Dictionary cpServicesGroupsDict, + List appsMatchList, + Dictionary cpAppGroupsDict, + List paAppFiltersList, + Dictionary> cpSchedulesDict, + Dictionary cpAccessRolesDict, PA_PreRulebase s_preRulebase, + PA_PostRulebase s_postRulebase, + List devicesGroupList, + Dictionary _devicesUIDDict + ) + { + Dictionary cpLayersDict = new Dictionary(); + Dictionary cpGroupRuleAppFiltering = new Dictionary(); + + List paRules = new List(); + bool isPolicyPlain = false; + + //add pre-rules from shared section to the device group rules + if (s_preRulebase != null && s_preRulebase.Security != null && s_preRulebase.Security.RulesList != null) + { + foreach (PA_SecurityRuleEntry paSecurityRuleEntry in s_preRulebase.Security.RulesList) + { + isPolicyPlain = + !isPolicyPlain && (paSecurityRuleEntry.FromList.Contains(PA_ANY_VALUE) || paSecurityRuleEntry.ToList.Contains(PA_ANY_VALUE)) ? true : isPolicyPlain; + paRules.Add(paSecurityRuleEntry); + } + } + + if (paDeviceGroupEntry.PreRulebase != null && paDeviceGroupEntry.PreRulebase.Security != null && paDeviceGroupEntry.PreRulebase.Security.RulesList != null) + { + foreach (PA_SecurityRuleEntry paSecurityRuleEntry in paDeviceGroupEntry.PreRulebase.Security.RulesList) + { + isPolicyPlain = + !isPolicyPlain && (paSecurityRuleEntry.FromList.Contains(PA_ANY_VALUE) || paSecurityRuleEntry.ToList.Contains(PA_ANY_VALUE)) ? true : isPolicyPlain; + paRules.Add(paSecurityRuleEntry); + } + } + + if (paDeviceGroupEntry.PostRulebase != null && paDeviceGroupEntry.PostRulebase.Security != null && paDeviceGroupEntry.PostRulebase.Security.RulesList != null) + { + foreach (PA_SecurityRuleEntry paSecurityRuleEntry in paDeviceGroupEntry.PostRulebase.Security.RulesList) + { + isPolicyPlain = + !isPolicyPlain && (paSecurityRuleEntry.FromList.Contains(PA_ANY_VALUE) || paSecurityRuleEntry.ToList.Contains(PA_ANY_VALUE)) ? true : isPolicyPlain; + paRules.Add(paSecurityRuleEntry); + } + } + + //add post-rules from shared section to the device group rules + if (s_postRulebase != null && s_postRulebase.Security != null && s_postRulebase.Security.RulesList != null) + { + foreach (PA_SecurityRuleEntry paSecurityRuleEntry in s_postRulebase.Security.RulesList) + { + isPolicyPlain = + !isPolicyPlain && (paSecurityRuleEntry.FromList.Contains(PA_ANY_VALUE) || paSecurityRuleEntry.ToList.Contains(PA_ANY_VALUE)) ? true : isPolicyPlain; + paRules.Add(paSecurityRuleEntry); + } + } + + var cpPackage = new CheckPoint_Package(); + cpPackage.Name = _policyPackageName; + cpPackage.ParentLayer.Name = cpPackage.NameOfAccessLayer; + + foreach (PA_SecurityRuleEntry paSecurityRuleEntry in paRules) + { + List messagesE = new List(); + + List cpRuleSourceList = new List(); + #region Processing Source of Rule + if (!paSecurityRuleEntry.SourceList.Contains(PA_ANY_VALUE)) + { + foreach (string srcMember in paSecurityRuleEntry.SourceList) + { + if (cpAddressesDict.ContainsKey(srcMember)) + { + cpRuleSourceList.Add(cpAddressesDict[srcMember]); + } + else if (cpNetGroupsDict.ContainsKey(srcMember)) + { + cpRuleSourceList.Add(cpNetGroupsDict[srcMember]); + } + else if (Regex.IsMatch(srcMember, RE_NET_ADDRESS)) + { + if (!srcMember.Contains("/") || srcMember.Contains(NETWORK_NETMASK_WS)) + { + string ipAddress; + + if (srcMember.Contains("/")) + ipAddress = srcMember.Substring(0, srcMember.IndexOf("/")); + else + ipAddress = srcMember.Substring(0); + + CheckPoint_Host cpHostNew = new CheckPoint_Host(); + cpHostNew.Name = "Host_" + ipAddress; + cpHostNew.IpAddress = ipAddress; + + cpAddressesDict[srcMember] = cpHostNew; + + cpRuleSourceList.Add(cpHostNew); + } + else + { + IPNetwork ipNetwork; + if (IPNetwork.TryParse(srcMember, out ipNetwork)) + { + string ipAddress = srcMember.Substring(0, srcMember.IndexOf("/")); + + CheckPoint_Network cpNetworkNew = new CheckPoint_Network(); + cpNetworkNew.Name = "Net_" + ipAddress; + cpNetworkNew.Subnet = ipAddress; + cpNetworkNew.Netmask = ipNetwork.Netmask.ToString(); + + cpAddressesDict[srcMember] = cpNetworkNew; + + cpRuleSourceList.Add(cpNetworkNew); + } + } + } + else + { + messagesE.Add(paSecurityRuleEntry.Name + + " security rule is not converted because source object is not defined or converted: " + + srcMember); + } + } + } + else + { + if (isPolicyPlain && !paSecurityRuleEntry.FromList.Contains(PA_ANY_VALUE) + && !(ConvertUserConf && paSecurityRuleEntry.SourceUserList != null && !paSecurityRuleEntry.SourceUserList.Contains(PA_ANY_VALUE))) + { + paSecurityRuleEntry.FromList.ForEach(fromObj => + { + if ((cpZonesDict != null) && cpZonesDict.ContainsKey(fromObj)) + { + CheckPoint_Zone cpZone = cpZonesDict[fromObj]; + cpRuleSourceList.Add(cpZone); + AddCheckPointObject(cpZone); + } + }); + } + } + #endregion + + List cpRuleDestinationList = new List(); + #region Processing Destination of Rule + if (!paSecurityRuleEntry.DestinationList.Contains(PA_ANY_VALUE)) + { + foreach (string dstMember in paSecurityRuleEntry.DestinationList) + { + if (cpAddressesDict.ContainsKey(dstMember)) + { + cpRuleDestinationList.Add(cpAddressesDict[dstMember]); + } + else if (cpNetGroupsDict.ContainsKey(dstMember)) + { + cpRuleDestinationList.Add(cpNetGroupsDict[dstMember]); + } + else if (Regex.IsMatch(dstMember, RE_NET_ADDRESS)) + { + if (!dstMember.Contains("/") || dstMember.Contains(NETWORK_NETMASK_WS)) + { + string ipAddress; + + if (dstMember.Contains("/")) + ipAddress = dstMember.Substring(0, dstMember.IndexOf("/")); + else + ipAddress = dstMember.Substring(0); + + CheckPoint_Host cpHostNew = new CheckPoint_Host(); + cpHostNew.Name = "Host_" + ipAddress; + cpHostNew.IpAddress = ipAddress; + + cpAddressesDict[dstMember] = cpHostNew; + + cpRuleDestinationList.Add(cpHostNew); + } + else + { + IPNetwork ipNetwork; + if (IPNetwork.TryParse(dstMember, out ipNetwork)) + { + string ipAddress = dstMember.Substring(0, dstMember.IndexOf("/")); + + CheckPoint_Network cpNetworkNew = new CheckPoint_Network(); + cpNetworkNew.Name = "Net_" + ipAddress; + cpNetworkNew.Subnet = ipAddress; + cpNetworkNew.Netmask = ipNetwork.Netmask.ToString(); + + cpAddressesDict[dstMember] = cpNetworkNew; + + cpRuleDestinationList.Add(cpNetworkNew); + } + } + } + else + { + messagesE.Add(paSecurityRuleEntry.Name + + " security rule is not converted because destination object is not defined or converted: " + + dstMember); + } + } + } + else + { + if (isPolicyPlain && !paSecurityRuleEntry.ToList.Contains(PA_ANY_VALUE)) + { + paSecurityRuleEntry.ToList.ForEach(toObj => + { + if ((cpZonesDict != null) && cpZonesDict.ContainsKey(toObj)) + { + CheckPoint_Zone cpZone = cpZonesDict[toObj]; + cpRuleDestinationList.Add(cpZone); + AddCheckPointObject(cpZone); + } + }); + } + } + #endregion + + List cpRuleServiceList = new List(); + List cpRuleApplilcationList = new List(); + bool applicationsFiltering = false; + #region Processing Services, Groups of Services and Applications of Rule + if ((paSecurityRuleEntry.ApplicationList.Contains(PA_ANY_VALUE))) // services only -> processing services + { + if (!(paSecurityRuleEntry.ServiceList.Contains(PA_APPLICATION_DEFAULT) || paSecurityRuleEntry.ServiceList.Contains(PA_ANY_VALUE))) + { + foreach (string paServiceName in paSecurityRuleEntry.ServiceList) + { + CheckPointObject cpServiceObj = null; + if (cpServicesDict.ContainsKey(paServiceName)) + { + + cpServiceObj = cpServicesDict[paServiceName]; + } + else if (cpServicesGroupsDict.ContainsKey(paServiceName)) + { + cpServiceObj = cpServicesGroupsDict[paServiceName]; + } + + if (cpServiceObj != null) + { + cpRuleServiceList.Add(cpServiceObj); + } + else + { + messagesE.Add(paSecurityRuleEntry.Name + + " security rule is not converted because service object is not defined or converted: " + + paServiceName); + } + } + } + } + else //application and services or applications only -> processing applications + { + applicationsFiltering = true; + foreach (string paAppName in paSecurityRuleEntry.ApplicationList) + { + if (cpServicesGroupsDict.ContainsKey(paAppName + "-svc"))//to add mapped PA services from CP application group entry + { + cpRuleServiceList.Add(cpServicesGroupsDict[paAppName + "-svc"]); + } + + if (cpAppGroupsDict.ContainsKey(paAppName)) + { + cpRuleApplilcationList.Add(cpAppGroupsDict[paAppName]); + } + else if (paAppFiltersList.Contains(paAppName)) + { + _warningsList.Add(paSecurityRuleEntry.Name + " security rule contains application filter: " + paAppName); + } + else + { + string matchedLine = appsMatchList.Find(x => x.StartsWith(paAppName + ";")); + if (!string.IsNullOrEmpty(matchedLine)) + { + string[] matchedArray = matchedLine.Split(';'); + if (!string.IsNullOrWhiteSpace(matchedArray[1])) + { + string[] matchedValues = matchedArray[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + foreach (string matchedValue in matchedValues) + { + if (!matchedValue.Trim().Equals("")) + { + cpRuleApplilcationList.Add(new CheckPoint_PredifinedObject { Name = matchedValue.Trim() }); + } + } + } + else if (!string.IsNullOrWhiteSpace(matchedArray[2])) + { + string[] matchedValues = matchedArray[2].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + foreach (string matchedValue in matchedValues) + { + if (!matchedValue.Trim().Equals("")) + { + cpRuleApplilcationList.Add(new CheckPoint_PredifinedObject { Name = matchedValue.Trim() }); + } + } + } + else + _warningsList.Add(paSecurityRuleEntry.Name + " security rule contains non-mapped application: " + paAppName); + } + else + { + _warningsList.Add(paSecurityRuleEntry.Name + " security rule contains unknown application: " + paAppName); + } + } + } + + if (!(paSecurityRuleEntry.ServiceList.Contains(PA_APPLICATION_DEFAULT) || paSecurityRuleEntry.ServiceList.Contains(PA_ANY_VALUE))) + { + foreach (string paServiceName in paSecurityRuleEntry.ServiceList) + { + _warningsList.Add(paSecurityRuleEntry.Name + " access rule contains service which was not converted: " + paServiceName); + } + } + } + if (!paSecurityRuleEntry.CategoryList.Contains(PA_ANY_VALUE)) + { + foreach (string paCategoryName in paSecurityRuleEntry.CategoryList) + { + _warningsList.Add(paSecurityRuleEntry.Name + " access rule contains URL-category which was not converted: " + paCategoryName); + } + } + #endregion + + List cpAccessRolesList = new List(); + #region Processing Users Roles + if (ConvertUserConf && paSecurityRuleEntry.SourceUserList != null && !paSecurityRuleEntry.SourceUserList.Contains(PA_ANY_VALUE)) + { + CheckPoint_AccessRole cpAccessRole = new CheckPoint_AccessRole(); + cpAccessRole.Name = InspectObjectName("AR_" + paSecurityRuleEntry.Name, CP_OBJECT_TYPE_NAME_ACCESS_ROLE); + + foreach (string sourceUser in paSecurityRuleEntry.SourceUserList) + { + if (sourceUser.Contains(",")) + { + List values = new List(); + sourceUser.Split(new string[] { "," }, StringSplitOptions.None).ToList().ForEach(x => values.Add(x.Trim().Substring(x.IndexOf("=") + 1))); + AccessRoleUser arUser = new AccessRoleUser(); + arUser.Name = values[0]; + arUser.BaseDn = sourceUser; + + cpAccessRole.Users.Add(arUser); + } + else if (sourceUser.Contains("\\")) + { + AccessRoleUser arUser = new AccessRoleUser(); + arUser.Name = sourceUser.Substring(sourceUser.IndexOf("\\") + 1); + + cpAccessRole.Users.Add(arUser); + } + else + { + AccessRoleUser arUser = new AccessRoleUser(); + arUser.Name = sourceUser; + + cpAccessRole.Users.Add(arUser); + } + } + + if (paSecurityRuleEntry.SourceList != null && !paSecurityRuleEntry.SourceList.Contains(PA_ANY_VALUE)) + { + cpRuleSourceList.ForEach(x => cpAccessRole.Networks.Add(x.Name)); + cpRuleSourceList.Clear(); + } + + cpAccessRolesDict.Add(cpAccessRole.Name, cpAccessRole); + cpAccessRolesList.Add(cpAccessRole); + } + #endregion + + CheckPoint_Rule.ActionType cpRuleActionType = (paSecurityRuleEntry.Action.Equals("allow")) ? + CheckPoint_Rule.ActionType.Accept : CheckPoint_Rule.ActionType.Drop; + + List cpRuleTimeList = new List(); + #region Processing Schedule of Rule + if (paSecurityRuleEntry.Schedule != null && cpSchedulesDict.ContainsKey(paSecurityRuleEntry.Schedule)) + { + cpRuleTimeList.AddRange(cpSchedulesDict[paSecurityRuleEntry.Schedule]); + } + #endregion + + CheckPoint_Rule.TrackTypes cpRuleTrack = ("no".Equals(paSecurityRuleEntry.LogStart) && "no".Equals(paSecurityRuleEntry.LogEnd)) ? + CheckPoint_Rule.TrackTypes.None : CheckPoint_Rule.TrackTypes.Log; + + bool cpRuleEnabled = !("yes".Equals(paSecurityRuleEntry.Disabled)); + + bool cpRuleNegateSource = "yes".Equals(paSecurityRuleEntry.NegateSource); + bool cpRuleNegateDestination = "yes".Equals(paSecurityRuleEntry.NegateDestination); + + List cpTargetDeviceUIDList = AddSecurityRuleTarget(devicesGroupList, paSecurityRuleEntry, _devicesUIDDict); + + if (messagesE.Count == 0) + { + if (isPolicyPlain) + { + //Console.WriteLine("Plain policy rule: " + paSecurityRuleEntry.Name); + + CheckPoint_RuleWithApplication cpRule = CreateCpRule(paSecurityRuleEntry, + cpRuleSourceList, + cpRuleDestinationList, + cpRuleServiceList, + cpRuleApplilcationList, + cpRuleActionType, + cpRuleTimeList, + cpRuleTrack, + cpRuleEnabled, + cpRuleNegateSource, + cpRuleNegateDestination, + cpAddressesDict, + cpNetGroupsDict, + cpServicesDict, + cpServicesGroupsDict, + cpAccessRolesList, + cpAppGroupsDict, + //devicesGroupList, + cpTargetDeviceUIDList + ); + if (cpRule.IsCleanupRule()) + { + continue; + } + + if (cpRule.IsAllowAnyRule()) + { + cpRule.Enabled = false; + } + + cpRule.Layer = cpPackage.ParentLayer.Name; + + cpPackage.ParentLayer.Rules.Add(cpRule); + _rulesInConvertedPackage += 1; + + if (applicationsFiltering) + { + cpPackage.ParentLayer.ApplicationsAndUrlFiltering = true; + } + + string ruleCmd = cpRule.ToCLIScript(); + } + else + { + List zonesNamesFromList = paSecurityRuleEntry.FromList; + + List zonesNamesToList = paSecurityRuleEntry.ToList; + + foreach (string zoneNameFrom in zonesNamesFromList) + { + foreach (string zoneNameTo in zonesNamesToList) + { + if (PA_INTRAZONE_NAME.Equals(paSecurityRuleEntry.RuleType) && zoneNameFrom.Equals(zoneNameTo)) + { + continue; + } + if (PA_INTRAZONE_NAME.Equals(paSecurityRuleEntry.RuleType) && !zoneNameFrom.Equals(zoneNameTo)) + { + continue; + } + CheckPoint_RuleWithApplication cpRule = CreateCpRule(paSecurityRuleEntry, + cpRuleSourceList, + cpRuleDestinationList, + cpRuleServiceList, + cpRuleApplilcationList, + cpRuleActionType, + cpRuleTimeList, + cpRuleTrack, + cpRuleEnabled, + cpRuleNegateSource, + cpRuleNegateDestination, + cpAddressesDict, + cpNetGroupsDict, + cpServicesDict, + cpServicesGroupsDict, + cpAccessRolesList, + cpAppGroupsDict, + //devicesGroupList, + cpTargetDeviceUIDList + ); + + string keyLayerName = zoneNameFrom + "_TK_" + zoneNameTo; + string cpGroupRuleName = zoneNameFrom + "__" + zoneNameTo; + + CheckPoint_Layer cpLayer = null; + if (!cpLayersDict.TryGetValue(keyLayerName, out cpLayer)) + { + CheckPoint_Zone cpZoneSrc = cpZonesDict[zoneNameFrom]; + CheckPoint_Zone cpZoneDst = cpZonesDict[zoneNameTo]; + + AddCheckPointObject(cpZoneSrc); + AddCheckPointObject(cpZoneDst); + + cpLayer = new CheckPoint_Layer(); + cpLayer.Name = keyLayerName; + cpLayer.ApplicationsAndUrlFiltering = false; + + cpPackage.SubPolicies.Add(cpLayer); + + CheckPoint_Rule cpGroupRule = new CheckPoint_Rule(); + cpGroupRule.Name = cpGroupRuleName; + cpGroupRule.Source.Add(cpZoneSrc); + cpGroupRule.Destination.Add(cpZoneDst); + cpGroupRule.Layer = cpPackage.NameOfAccessLayer; + cpGroupRule.Action = CheckPoint_Rule.ActionType.SubPolicy; + cpGroupRule.SubPolicyName = cpLayer.Name; + + cpPackage.ParentLayer.Rules.Add(cpGroupRule); + _rulesInConvertedPackage += 1; + + cpGroupRuleAppFiltering[cpGroupRuleName] = false; + } + + cpRule.Layer = cpLayer.Name; + + cpLayer.Rules.Add(cpRule); + _rulesInConvertedPackage += 1; + cpLayersDict[keyLayerName] = cpLayer; + + //--- + if (applicationsFiltering) + { + cpLayer.ApplicationsAndUrlFiltering = true; + cpGroupRuleAppFiltering[cpGroupRuleName] = true; + } + } + } + } + } + else + { + _errorsList.AddRange(messagesE); + } + } + + cpPackage.ParentLayer.Rules.ForEach(x => + { + if (cpGroupRuleAppFiltering.ContainsKey(x.Name) && cpGroupRuleAppFiltering[x.Name]) + x.ConversionComments = "Applications and URL filtering is enabled for layer."; + }); + + foreach (CheckPoint_Layer cpLayer in cpLayersDict.Values) + { + CheckPoint_Rule cpRuleCU = new CheckPoint_Rule(); + cpRuleCU.Name = "Sub-Policy Cleanup"; + cpRuleCU.Layer = cpLayer.Name; + cpLayer.Rules.Add(cpRuleCU); + }; + + // Do NOT create a cleanup rule if it already exists + bool createCleanupRule = true; + if (cpPackage.ParentLayer.Rules.Count > 0) + { + var lastRule = cpPackage.ParentLayer.Rules[cpPackage.ParentLayer.Rules.Count - 1]; + createCleanupRule = !lastRule.IsCleanupRule(); + } + + if (createCleanupRule) + { + var cpRuleFake = new CheckPoint_Rule(); + cpRuleFake.Name = "Cleanup rule"; //the last rule which is created by default by CheckPoint script importer. It is for report only. + cpPackage.ParentLayer.Rules.Add(cpRuleFake); + } + + AddCheckPointObject(cpPackage); + } + + public List AddSecurityRuleTarget(List devicesGroupList, PA_SecurityRuleEntry paSecurityRuleEntry, Dictionary _devicesUIDDict) + { + List cpTargetDeviceEntries = new List(); + List cpTargetDeviceUIDList = new List(); + + ///get List of devices in current device group + List devices = new List(); + foreach (CheckPoint_NetworkGroup group in devicesGroupList) + { + devices.Add(group.Name); + } + + bool cpRuleNegateTarget = false; + if (paSecurityRuleEntry.Target != null) + { + cpRuleNegateTarget = "yes".Equals(paSecurityRuleEntry.Target.Negate); + + cpTargetDeviceEntries = paSecurityRuleEntry.Target.DevicesEntry; + string deviceName = null; + foreach (PA_TargetDeviceEntry entry in cpTargetDeviceEntries) + { + if (!cpRuleNegateTarget) + { + if (_devicesUIDDict.ContainsKey(entry.Name)) + { + deviceName = _devicesUIDDict[entry.Name]; + } + + cpTargetDeviceUIDList.Add("FW_" + deviceName); + } + else + { //negate option set to "yes" + foreach (string device in devices) + { + if (!("FW_" + entry.Name).Equals(device)) + { + if (_devicesUIDDict.ContainsKey(device)) + { + deviceName = _devicesUIDDict[device]; + } + cpTargetDeviceUIDList.Add(deviceName); + } + } + + } + } + } + return cpTargetDeviceUIDList; + } + + public List AddNatRuleTarget(List devicesGroupList, PA_NatRuleEntry paNatRuleEntry, Dictionary _devicesUIDDict) + { + List cpTargetDeviceEntries = new List(); + List cpTargetDeviceUIDList = new List(); + + ///get List of devices in current device group + List devices = new List(); + foreach (CheckPoint_NetworkGroup group in devicesGroupList) + { + devices.Add(group.Name); + } + + bool cpRuleNegateTarget = false; + if (paNatRuleEntry.Target != null) + { + cpRuleNegateTarget = "yes".Equals(paNatRuleEntry.Target.Negate); + + cpTargetDeviceEntries = paNatRuleEntry.Target.DevicesEntry; + string deviceName = null; + foreach (PA_TargetDeviceEntry entry in cpTargetDeviceEntries) + { + if (!cpRuleNegateTarget) + { + if (_devicesUIDDict.ContainsKey(entry.Name)) + { + deviceName = _devicesUIDDict[entry.Name]; + } + cpTargetDeviceUIDList.Add("FW_" + deviceName); + } + else + { //negate option set to "yes" + foreach (string device in devices) + { + if (!("FW_" + entry.Name).Equals(device)) + { + if (_devicesUIDDict.ContainsKey(device)) + { + deviceName = _devicesUIDDict[device]; + } + + cpTargetDeviceUIDList.Add(deviceName); + } + } + + } + } + } + return cpTargetDeviceUIDList; + } + + private CheckPoint_RuleWithApplication CreateCpRule(PA_SecurityRuleEntry paSecurityRuleEntry, + List cpRuleSourceList, + List cpRuleDestinationList, + List cpRuleServiceList, + List cpRuleApplilcationList, + CheckPoint_Rule.ActionType cpRuleActionType, + List cpRuleTimeList, + CheckPoint_Rule.TrackTypes cpRuleTrack, + bool cpRuleEnabled, + bool cpRuleNegateSource, + bool cpRuleNegateDestination, + Dictionary cpAddressesDict, + Dictionary cpNetGroupsDict, + Dictionary cpServicesDict, + Dictionary cpSrvGroupsDict, + List cpAccessRolesList, + Dictionary cpAppGroupsDict, + List cpTargetDeviceUIDList + ) + { + CheckPoint_RuleWithApplication cpRule = new CheckPoint_RuleWithApplication(); + cpRule.Name = paSecurityRuleEntry.Name; + cpRule.Comments = string.IsNullOrWhiteSpace(paSecurityRuleEntry.Description) ? "" : (" " + paSecurityRuleEntry.Description); + cpRule.Tags = paSecurityRuleEntry.TagMembers; + cpRule.Source.AddRange(cpRuleSourceList); + cpRule.Destination.AddRange(cpRuleDestinationList); + cpRule.Service.AddRange(cpRuleServiceList); + cpRule.Application.AddRange(cpRuleApplilcationList); + cpRule.Action = cpRuleActionType; + cpRule.Time.AddRange(cpRuleTimeList); + cpRule.Track = cpRuleTrack; + cpRule.Enabled = cpRuleEnabled; + if (cpTargetDeviceUIDList != null && cpTargetDeviceUIDList.Count() > 0) + { + cpRule.Target.AddRange(cpTargetDeviceUIDList); + } + cpRule.SourceNegated = cpRuleNegateSource; + cpRule.DestinationNegated = cpRuleNegateDestination; + cpRule.ConversionComments = "Matched rule: " + paSecurityRuleEntry.Name; + + + cpRule.Source.ForEach(x => + { + if (x.GetType() == typeof(CheckPoint_NetworkGroup)) + { + AddCpNetworkGroup((CheckPoint_NetworkGroup)x, cpAddressesDict, cpNetGroupsDict); + } + else if (x.GetType() != typeof(CheckPoint_PredifinedObject)) + { + AddCheckPointObject(x); + } + }); + cpRule.Destination.ForEach(x => + { + if (x.GetType() == typeof(CheckPoint_NetworkGroup)) + { + AddCpNetworkGroup((CheckPoint_NetworkGroup)x, cpAddressesDict, cpNetGroupsDict); + } + else if (x.GetType() != typeof(CheckPoint_PredifinedObject)) + { + AddCheckPointObject(x); + } + }); + cpRule.Service.ForEach(x => + { + if (x.GetType() == typeof(CheckPoint_ServiceGroup)) + { + AddCpServiceGroup((CheckPoint_ServiceGroup)x, cpServicesDict, cpSrvGroupsDict); + } + else if (x.GetType() != typeof(CheckPoint_PredifinedObject)) + { + AddCheckPointObject(x); + } + }); + cpRule.Time.ForEach(x => AddCheckPointObject(x)); + + if (ConvertUserConf && cpAccessRolesList.Count > 0) + { + if (cpRule.Source.Contains(_cpObjects.GetObject(CheckPointObject.Any))) + cpRule.Source.Clear(); + cpRule.Source.AddRange(cpAccessRolesList); + } + cpRule.Application.ForEach(x => + { + if (x.GetType() == typeof(CheckPoint_ApplicationGroup)) + { + AddCpApplicationGroup((CheckPoint_ApplicationGroup)x, cpAppGroupsDict); + } + else if (x.GetType() != typeof(CheckPoint_PredifinedObject)) + { + AddCheckPointObject(x); + } + }); + + return cpRule; + } + + #endregion + + #region Convert Nat Policy + + public void ConvertNatPolicy(PA_DeviceGroupEntry paDeviceGroupEntry, + Dictionary cpAddressesDict, + Dictionary cpNetGroupsDict, + Dictionary cpServicesDict, + Dictionary paServicesTypesDict, + Dictionary cpServicesGroupsDict, + List devicesGroupList, + Dictionary _devicesUIDDict) + { + int counterNatRules = -1; + + if (paDeviceGroupEntry.PreRulebase != null && paDeviceGroupEntry.PreRulebase.Nat != null && paDeviceGroupEntry.PreRulebase.Nat.RulesList != null) + { + foreach (PA_NatRuleEntry paNatRuleEntry in paDeviceGroupEntry.PreRulebase.Nat.RulesList) + { + List cpSourceTranslationList = new List(); + bool isSourceTranslationExists = true; + bool isNatRuleStatic = false; + bool isNatRuleBiDirectional = false; + bool isDestinationTranslationNone = false; + + #region converting source translation to list; checking if NAT Rule Method should be Static + if (paNatRuleEntry.SourceTranslation != null) + { + if (paNatRuleEntry.SourceTranslation.StaticIp != null) + { + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.SourceTranslation.StaticIp.TranslatedAddress)) + { + if (cpAddressesDict.ContainsKey(paNatRuleEntry.SourceTranslation.StaticIp.TranslatedAddress)) + { + cpSourceTranslationList.Add(cpAddressesDict[paNatRuleEntry.SourceTranslation.StaticIp.TranslatedAddress]); + isNatRuleStatic = true; + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.SourceTranslation.StaticIp.IsBiDirectional) + && paNatRuleEntry.SourceTranslation.StaticIp.IsBiDirectional.ToLower().Equals("yes")) + { + isNatRuleBiDirectional = true; + } + } + } + } + else if (paNatRuleEntry.SourceTranslation.DynamicIp != null) + { + if (paNatRuleEntry.SourceTranslation.DynamicIp.TranslatedAddresses != null) + { + foreach (string translatedAddress in paNatRuleEntry.SourceTranslation.DynamicIp.TranslatedAddresses) + { + if (cpAddressesDict.ContainsKey(translatedAddress)) + { + cpSourceTranslationList.Add(cpAddressesDict[translatedAddress]); + } + else if (cpNetGroupsDict.ContainsKey(translatedAddress)) + { + cpSourceTranslationList.Add(cpNetGroupsDict[translatedAddress]); + } + } + } + } + else if (paNatRuleEntry.SourceTranslation.DynamicIpAndPort != null) + { + if (paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses != null && + paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses.Count > 0) + { + foreach (string translatedAddress in paNatRuleEntry.SourceTranslation.DynamicIpAndPort.TranslatedAddresses) + { + if (cpAddressesDict.ContainsKey(translatedAddress)) + { + cpSourceTranslationList.Add(cpAddressesDict[translatedAddress]); + } + else if (cpNetGroupsDict.ContainsKey(translatedAddress)) + { + cpSourceTranslationList.Add(cpNetGroupsDict[translatedAddress]); + } + else if (Regex.IsMatch(translatedAddress, RE_NET_ADDRESS)) //create address or network object for translated address if they were not created before + { + if (!translatedAddress.Contains("/") || translatedAddress.Contains(NETWORK_NETMASK_WS)) + { + string ipAddress; + + if (translatedAddress.Contains("/")) + ipAddress = translatedAddress.Substring(0, translatedAddress.IndexOf("/")); + else + ipAddress = translatedAddress.Substring(0); + + CheckPoint_Host cpHostNew = new CheckPoint_Host(); + cpHostNew.Name = "Host_" + ipAddress; + cpHostNew.IpAddress = ipAddress; + cpAddressesDict[translatedAddress] = cpHostNew; + cpSourceTranslationList.Add(cpHostNew); + _warningsList.Add(cpHostNew.Name + " host object is created for NAT rule."); + } + else + { + IPNetwork ipNetwork; + if (IPNetwork.TryParse(translatedAddress, out ipNetwork)) + { + string ipAddress = translatedAddress.Substring(0, translatedAddress.IndexOf("/")); + CheckPoint_Network cpNetworkNew = new CheckPoint_Network(); + cpNetworkNew.Name = "Net_" + ipAddress; + cpNetworkNew.Subnet = ipAddress; + cpNetworkNew.Netmask = ipNetwork.Netmask.ToString(); + cpAddressesDict[translatedAddress] = cpNetworkNew; + cpSourceTranslationList.Add(cpNetworkNew); + _warningsList.Add(cpNetworkNew.Name + " network object is created for NAT rule."); + } + } + } + + } + } + else if (paNatRuleEntry.SourceTranslation.DynamicIpAndPort.InterfaceAddress != null) + { + string intfAddrIP = paNatRuleEntry.SourceTranslation.DynamicIpAndPort.InterfaceAddress.Ip; + if (!string.IsNullOrWhiteSpace(intfAddrIP)) + { + if (cpAddressesDict.ContainsKey(intfAddrIP)) + { + cpSourceTranslationList.Add(cpAddressesDict[intfAddrIP]); + } + else + { + if (intfAddrIP.Contains("/")) + { + intfAddrIP = intfAddrIP.Substring(0, intfAddrIP.IndexOf("/")); + } + + IPAddress ipAddress; + if (IPAddress.TryParse(intfAddrIP, out ipAddress)) + { + CheckPoint_Host cpHost = new CheckPoint_Host(); + cpHost.Name = "NatIntf_" + intfAddrIP; + cpHost.IpAddress = intfAddrIP; + cpSourceTranslationList.Add(cpHost); + + _warningsList.Add(cpHost.Name + " host object is created for NAT rule."); + } + } + } + } + } + } + + if (cpSourceTranslationList.Count == 0) + { + isSourceTranslationExists = false; + // createing Dummy Object because we need to have at least 1 element in cpSourceTranslationList for creating NAT rule + cpSourceTranslationList.Add(new CheckPoint_PredifinedObject { Name = "DUMMY_OBJECT" }); + } + #endregion + + if (paNatRuleEntry.DestinationTranslation == null) + { + isDestinationTranslationNone = true; + } + + foreach (string source in paNatRuleEntry.SourceList) + { + foreach (string destination in paNatRuleEntry.DestinationList) + { + foreach (CheckPointObject cpSourceTranslation in cpSourceTranslationList) + { + CheckPoint_NAT_Rule cpNatRule = new CheckPoint_NAT_Rule(); + + List messagesW = new List(); + List messagesE = new List(); + + CheckPointObject extraNatServiceSourced = null; + CheckPointObject extraNatServiceTranslated = null; + + cpNatRule.Name = GetSafeName(paNatRuleEntry.Name + ((++counterNatRules > 0) ? "_" + counterNatRules : "")); + cpNatRule.Comments = "Matched rule name: " + paNatRuleEntry.Name + ". "; + + cpNatRule.Comments += paNatRuleEntry.Description; + cpNatRule.Tags = paNatRuleEntry.TagMembers; + cpNatRule.Enabled = !("yes".Equals(paNatRuleEntry.Disabled)); + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Hide; + + #region adding original source + if (!PA_ANY_VALUE.Equals(source)) + { + if (cpAddressesDict.ContainsKey(source)) + { + cpNatRule.Source = cpAddressesDict[source]; + } + else if (cpNetGroupsDict.ContainsKey(source)) + { + cpNatRule.Source = cpNetGroupsDict[source]; + } + else if (Regex.IsMatch(source, RE_NET_ADDRESS)) + { + if (!source.Contains("/") || source.Contains(NETWORK_NETMASK_WS)) + { + string ipAddress; + + if (source.Contains("/")) + ipAddress = source.Substring(0, source.IndexOf("/")); + else + ipAddress = source.Substring(0); + + CheckPoint_Host cpHostNew = new CheckPoint_Host(); + cpHostNew.Name = "Host_" + ipAddress; + cpHostNew.IpAddress = ipAddress; + + cpAddressesDict[source] = cpHostNew; + + cpNatRule.Source = cpHostNew; + } + else + { + IPNetwork ipNetwork; + if (IPNetwork.TryParse(source, out ipNetwork)) + { + string ipAddress = source.Substring(0, source.IndexOf("/")); + + CheckPoint_Network cpNetworkNew = new CheckPoint_Network(); + cpNetworkNew.Name = "Net_" + ipAddress; + cpNetworkNew.Subnet = ipAddress; + cpNetworkNew.Netmask = ipNetwork.Netmask.ToString(); + + cpAddressesDict[source] = cpNetworkNew; + + cpNatRule.Source = cpNetworkNew; + } + } + } + else + { + messagesE.Add(paNatRuleEntry.Name + + " NAT rule is not converted because source object is not defined or converted: " + + source); + } + } + #endregion + + #region adding original destination + if (!PA_ANY_VALUE.Equals(destination)) + { + if (cpAddressesDict.ContainsKey(destination)) + { + cpNatRule.Destination = cpAddressesDict[destination]; + } + else if (cpNetGroupsDict.ContainsKey(destination)) + { + cpNatRule.Destination = cpNetGroupsDict[destination]; + } + else if (Regex.IsMatch(destination, RE_NET_ADDRESS)) + { + if (!destination.Contains("/") || destination.Contains(NETWORK_NETMASK_WS)) + { + string ipAddress; + + if (destination.Contains("/")) + ipAddress = destination.Substring(0, destination.IndexOf("/")); + else + ipAddress = destination.Substring(0); + + CheckPoint_Host cpHostNew = new CheckPoint_Host(); + cpHostNew.Name = "Host_" + ipAddress; + cpHostNew.IpAddress = ipAddress; + + cpAddressesDict[destination] = cpHostNew; + + cpNatRule.Destination = cpHostNew; + } + else + { + IPNetwork ipNetwork; + if (IPNetwork.TryParse(destination, out ipNetwork)) + { + string ipAddress = destination.Substring(0, destination.IndexOf("/")); + + CheckPoint_Network cpNetworkNew = new CheckPoint_Network(); + cpNetworkNew.Name = "Net_" + ipAddress; + cpNetworkNew.Subnet = ipAddress; + cpNetworkNew.Netmask = ipNetwork.Netmask.ToString(); + + cpAddressesDict[destination] = cpNetworkNew; + + cpNatRule.Destination = cpNetworkNew; + } + } + } + else + { + messagesE.Add(paNatRuleEntry.Name + + " NAT rule is not converted because destination object is not defined or converted: " + + destination); + } + } + #endregion + + #region adding original service + if (!PA_ANY_VALUE.Equals(paNatRuleEntry.Service)) + { + if (cpServicesDict.ContainsKey(paNatRuleEntry.Service)) + { + cpNatRule.Service = cpServicesDict[paNatRuleEntry.Service]; + } + else if (cpServicesGroupsDict.ContainsKey(paNatRuleEntry.Service)) + { + cpNatRule.Service = cpServicesGroupsDict[paNatRuleEntry.Service]; + } + else + { + messagesE.Add(paNatRuleEntry.Name + + " NAT rule is not converted because service or group of services object is not defined or converted: " + + paNatRuleEntry.Service); + } + } + #endregion + + #region adding source translation and changing NAT rule Method to static if it is required by Source Translation + if (isSourceTranslationExists) + { + cpNatRule.TranslatedSource = cpSourceTranslation; + if (isNatRuleStatic) + { + cpNatRule.Method = CheckPoint_NAT_Rule.NatMethod.Static; + } + } + #endregion + + #region adding destination translation + + if (paNatRuleEntry.DestinationTranslation != null) + { + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.DestinationTranslation.TranslatedAddress)) + { + if (cpAddressesDict.ContainsKey(paNatRuleEntry.DestinationTranslation.TranslatedAddress)) + { + cpNatRule.TranslatedDestination = cpAddressesDict[paNatRuleEntry.DestinationTranslation.TranslatedAddress]; + } + else if (Regex.IsMatch(paNatRuleEntry.DestinationTranslation.TranslatedAddress, RE_NET_ADDRESS)) + { + if (!paNatRuleEntry.DestinationTranslation.TranslatedAddress.Contains("/") || paNatRuleEntry.DestinationTranslation.TranslatedAddress.Contains(NETWORK_NETMASK_WS)) + { + string ipAddress; + + if (paNatRuleEntry.DestinationTranslation.TranslatedAddress.Contains("/")) + ipAddress = paNatRuleEntry.DestinationTranslation.TranslatedAddress.Substring(0, paNatRuleEntry.DestinationTranslation.TranslatedAddress.IndexOf("/")); + else + ipAddress = paNatRuleEntry.DestinationTranslation.TranslatedAddress.Substring(0); + + CheckPoint_Host cpHostNew = new CheckPoint_Host(); + cpHostNew.Name = "Host_" + ipAddress; + cpHostNew.IpAddress = ipAddress; + + cpAddressesDict[paNatRuleEntry.DestinationTranslation.TranslatedAddress] = cpHostNew; + + cpNatRule.TranslatedDestination = cpHostNew; + } + else + { + IPNetwork ipNetwork; + if (IPNetwork.TryParse(paNatRuleEntry.DestinationTranslation.TranslatedAddress, out ipNetwork)) + { + string ipAddress = paNatRuleEntry.DestinationTranslation.TranslatedAddress.Substring(0, paNatRuleEntry.DestinationTranslation.TranslatedAddress.IndexOf("/")); + + CheckPoint_Network cpNetworkNew = new CheckPoint_Network(); + cpNetworkNew.Name = "Net_" + ipAddress; + cpNetworkNew.Subnet = ipAddress; + cpNetworkNew.Netmask = ipNetwork.Netmask.ToString(); + + cpAddressesDict[paNatRuleEntry.DestinationTranslation.TranslatedAddress] = cpNetworkNew; + + cpNatRule.TranslatedDestination = cpNetworkNew; + } + } + } + else + { + messagesE.Add(paNatRuleEntry.Name + + " NAT rule is not converted because destination translation object is not defined or converted: " + + paNatRuleEntry.DestinationTranslation.TranslatedAddress); + } + + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.DestinationTranslation.TranslatedPort)) + { + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.Service)) + { + if (cpServicesDict.ContainsKey(paNatRuleEntry.Service)) + { + CheckPointObject cpService = cpServicesDict[paNatRuleEntry.Service]; + if (cpService.GetType() == typeof(CheckPoint_TcpService)) + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromStatDest(paNatRuleEntry); + } + else if (cpService.GetType() == typeof(CheckPoint_UdpService)) + { + cpNatRule.TranslatedService = CreateNatServiceUdpFromStatDest(paNatRuleEntry); + } + else if (cpService.GetType() == typeof(CheckPoint_PredifinedObject) && paServicesTypesDict.ContainsKey(paNatRuleEntry.Service)) + { + string servicesType = paServicesTypesDict[paNatRuleEntry.Service]; + if (servicesType.Trim().ToUpper().Equals(SERVICE_TYPE_TCP)) + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromStatDest(paNatRuleEntry); + } + else if (servicesType.Trim().ToUpper().Equals(SERVICE_TYPE_UDP)) + { + cpNatRule.TranslatedService = CreateNatServiceUdpFromStatDest(paNatRuleEntry); + } + } + } + else if (cpServicesGroupsDict.ContainsKey(paNatRuleEntry.Service)) + { + bool isTcpSrv = false; + bool isUdpSrv = false; + + GetServicesTypesFromServicesGroup((CheckPoint_ServiceGroup)cpServicesGroupsDict[paNatRuleEntry.Service], + (new List(cpServicesGroupsDict.Values)), + (new List(cpServicesDict.Values)), + out isTcpSrv, out isUdpSrv); + + if (isTcpSrv && !isUdpSrv) + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromStatDest(paNatRuleEntry); + } + else if (!isTcpSrv && isUdpSrv) + { + cpNatRule.TranslatedService = CreateNatServiceUdpFromStatDest(paNatRuleEntry); + } + else + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromStatDest(paNatRuleEntry); + extraNatServiceTranslated = CreateNatServiceUdpFromStatDest(paNatRuleEntry); + + List cpSrvGrpMembersTcp = new List(); + List cpSrvGrpMembersUdp = new List(); + GetServicesGroupsFromServiceGroup( + (CheckPoint_ServiceGroup)cpServicesGroupsDict[paNatRuleEntry.Service], + (new List(cpServicesGroupsDict.Values)), + (new List(cpServicesDict.Values)), + cpSrvGrpMembersTcp, + cpSrvGrpMembersUdp); + + CheckPoint_ServiceGroup cpSrvGrpTcpNat = new CheckPoint_ServiceGroup(); + cpSrvGrpTcpNat.Name = InspectObjectName("Nat_SrcTcpGrp_" + paNatRuleEntry.Name, "services group"); + cpSrvGrpMembersTcp.ForEach(x => cpSrvGrpTcpNat.Members.Add(x.Name)); + + CheckPoint_ServiceGroup cpSrvGrpUdpNat = new CheckPoint_ServiceGroup(); + cpSrvGrpUdpNat.Name = InspectObjectName("Nat_SrcUdpGrp_" + paNatRuleEntry.Name, "services group"); + cpSrvGrpMembersUdp.ForEach(x => cpSrvGrpUdpNat.Members.Add(x.Name)); + + cpNatRule.Service = cpSrvGrpTcpNat; + extraNatServiceSourced = cpSrvGrpUdpNat; + } + } + else // paNatRuleEntry.Service = "any" + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromStatDest(paNatRuleEntry); + extraNatServiceTranslated = CreateNatServiceUdpFromStatDest(paNatRuleEntry); + + CheckPoint_TcpService extraSrcSrvTcp = new CheckPoint_TcpService(); + extraSrcSrvTcp.Name = InspectObjectName("Nat_SrcTcp_" + paNatRuleEntry.Name, "tcp service"); + extraSrcSrvTcp.Port = "1-65535"; + + CheckPoint_UdpService extraSrcSrvUdp = new CheckPoint_UdpService(); + extraSrcSrvUdp.Name = InspectObjectName("Nat_SrcUdp_" + paNatRuleEntry.Name, "udp service"); + extraSrcSrvUdp.Port = "1-65535"; + + cpNatRule.Service = extraSrcSrvTcp; + extraNatServiceSourced = extraSrcSrvUdp; + } + } + } + } + } + + #endregion + + #region adding dynamic destination translation + + if (paNatRuleEntry.DynamicDestinationTranslation != null && !string.IsNullOrWhiteSpace(paNatRuleEntry.DynamicDestinationTranslation.TranslatedAddress) + && !(isNatRuleBiDirectional && isDestinationTranslationNone)) + { + if (cpAddressesDict.ContainsKey(paNatRuleEntry.DynamicDestinationTranslation.TranslatedAddress)) + { + cpNatRule.TranslatedDestination = cpAddressesDict[paNatRuleEntry.DynamicDestinationTranslation.TranslatedAddress]; + } + else if (cpNetGroupsDict.ContainsKey(paNatRuleEntry.DynamicDestinationTranslation.TranslatedAddress)) + { + cpNatRule.TranslatedDestination = cpNetGroupsDict[paNatRuleEntry.DynamicDestinationTranslation.TranslatedAddress]; + } + + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.DynamicDestinationTranslation.TranslatedPort)) + { + if (!string.IsNullOrWhiteSpace(paNatRuleEntry.Service)) + { + if (cpServicesDict.ContainsKey(paNatRuleEntry.Service)) + { + CheckPointObject cpService = cpServicesDict[paNatRuleEntry.Service]; + if (cpService.GetType() == typeof(CheckPoint_TcpService)) + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromDynDest(paNatRuleEntry); + } + else if (cpService.GetType() == typeof(CheckPoint_UdpService)) + { + cpNatRule.TranslatedService = CreateNatServiceUdpFromDynDest(paNatRuleEntry); + } + else if (cpService.GetType() == typeof(CheckPoint_PredifinedObject) && paServicesTypesDict.ContainsKey(paNatRuleEntry.Service)) + { + string servicesType = paServicesTypesDict[paNatRuleEntry.Service]; + if (servicesType.Trim().ToUpper().Equals("TCP")) + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromDynDest(paNatRuleEntry); + } + else if (servicesType.Trim().ToUpper().Equals("UDP")) + { + cpNatRule.TranslatedService = CreateNatServiceUdpFromDynDest(paNatRuleEntry); + } + } + } + else if (cpServicesGroupsDict.ContainsKey(paNatRuleEntry.Service)) + { + bool isTcpSrv = false; + bool isUdpSrv = false; + + GetServicesTypesFromServicesGroup((CheckPoint_ServiceGroup)cpServicesGroupsDict[paNatRuleEntry.Service], + (new List(cpServicesGroupsDict.Values)), + (new List(cpServicesDict.Values)), + out isTcpSrv, out isUdpSrv); + + if (isTcpSrv && !isUdpSrv) + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromDynDest(paNatRuleEntry); + } + else if (!isTcpSrv && isUdpSrv) + { + cpNatRule.TranslatedService = CreateNatServiceUdpFromDynDest(paNatRuleEntry); + } + else + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromDynDest(paNatRuleEntry); + extraNatServiceTranslated = CreateNatServiceUdpFromDynDest(paNatRuleEntry); + + List cpSrvGrpMembersTcp = new List(); + List cpSrvGrpMembersUdp = new List(); + GetServicesGroupsFromServiceGroup( + (CheckPoint_ServiceGroup)cpServicesGroupsDict[paNatRuleEntry.Service], + (new List(cpServicesGroupsDict.Values)), + (new List(cpServicesDict.Values)), + cpSrvGrpMembersTcp, + cpSrvGrpMembersUdp); + + CheckPoint_ServiceGroup cpSrvGrpTcpNat = new CheckPoint_ServiceGroup(); + cpSrvGrpTcpNat.Name = InspectObjectName("Nat_SrcTcpGrp_" + paNatRuleEntry.Name, "services group"); + cpSrvGrpMembersTcp.ForEach(x => cpSrvGrpTcpNat.Members.Add(x.Name)); + + CheckPoint_ServiceGroup cpSrvGrpUdpNat = new CheckPoint_ServiceGroup(); + cpSrvGrpUdpNat.Name = InspectObjectName("Nat_SrcUdpGrp_" + paNatRuleEntry.Name, "services group"); + cpSrvGrpMembersUdp.ForEach(x => cpSrvGrpUdpNat.Members.Add(x.Name)); + + cpNatRule.Service = cpSrvGrpTcpNat; + extraNatServiceSourced = cpSrvGrpUdpNat; + } + } + else // paNatRuleEntry.Service = "any" + { + cpNatRule.TranslatedService = CreateNatServiceTcpFromDynDest(paNatRuleEntry); + extraNatServiceTranslated = CreateNatServiceUdpFromDynDest(paNatRuleEntry); + + CheckPoint_TcpService extraSrcSrvTcp = new CheckPoint_TcpService(); + extraSrcSrvTcp.Name = InspectObjectName("Nat_SrcTcp_" + paNatRuleEntry.Name, "tcp service"); + extraSrcSrvTcp.Port = "1-65535"; + + CheckPoint_UdpService extraSrcSrvUdp = new CheckPoint_UdpService(); + extraSrcSrvUdp.Name = InspectObjectName("Nat_SrcUdp_" + paNatRuleEntry.Name, "udp service"); + extraSrcSrvUdp.Port = "1-65535"; + + cpNatRule.Service = extraSrcSrvTcp; + extraNatServiceSourced = extraSrcSrvUdp; + } + } + } + } + + #endregion + + + List cpTargetDeviceUIDList = AddNatRuleTarget(devicesGroupList, paNatRuleEntry, _devicesUIDDict); + cpNatRule.Target.AddRange(cpTargetDeviceUIDList); + + + if (messagesE.Count == 0) + { + if (!(cpNatRule.Source is CheckPoint_Domain) && + !(cpNatRule.Destination is CheckPoint_Domain) && + !(cpNatRule.TranslatedSource is CheckPoint_Domain) && + !(cpNatRule.TranslatedDestination is CheckPoint_Domain)) + { + if (isNatRuleBiDirectional && isDestinationTranslationNone) + { + //TRANS DEST == NONE + // orig source <- orig destin + // orig destin <- trans source + // trans source <- trans destin + // trans destin <- orig source + + CheckPoint_NAT_Rule cpNatRuleBi = new CheckPoint_NAT_Rule(); + cpNatRuleBi.Comments = cpNatRule.Comments; + cpNatRuleBi.ConversionIncidentType = cpNatRule.ConversionIncidentType; + cpNatRuleBi.ConvertedCommandId = cpNatRule.ConvertedCommandId; + cpNatRuleBi.Enabled = cpNatRule.Enabled; + cpNatRuleBi.Method = cpNatRule.Method; + cpNatRuleBi.Name = cpNatRule.Name + "_BD"; + cpNatRuleBi.Package = cpNatRule.Package; + cpNatRuleBi.Service = cpNatRule.Service; + cpNatRuleBi.Tag = cpNatRule.Tag; + cpNatRuleBi.Tags = cpNatRule.Tags; + cpNatRuleBi.TranslatedService = cpNatRule.TranslatedService; + cpNatRuleBi.VendorCustomData = cpNatRule.VendorCustomData; + cpNatRuleBi.Target = cpNatRule.Target; + cpNatRuleBi.Source = cpNatRule.Destination; + cpNatRuleBi.Destination = cpNatRule.TranslatedSource; + cpNatRuleBi.TranslatedSource = cpNatRule.TranslatedDestination; + cpNatRuleBi.TranslatedDestination = cpNatRule.Source; + + _cpNatRules.Add(cpNatRuleBi); + } + + _cpNatRules.Add(cpNatRule); + AddCheckPointObject(cpNatRule.Source); + AddCheckPointObject(cpNatRule.Destination); + AddCheckPointObject(cpNatRule.Service); + AddCheckPointObject(cpNatRule.TranslatedSource); + AddCheckPointObject(cpNatRule.TranslatedDestination); + AddCheckPointObject(cpNatRule.TranslatedService); + _rulesInNatLayer += 1; + + if (extraNatServiceSourced != null && extraNatServiceTranslated != null) + { + AddCheckPointObject(extraNatServiceSourced); + AddCheckPointObject(extraNatServiceTranslated); + + CheckPoint_NAT_Rule cpNatRuleExtra = cpNatRule.Clone(); + cpNatRuleExtra.Service = extraNatServiceSourced; + cpNatRuleExtra.TranslatedService = extraNatServiceTranslated; + _cpNatRules.Add(cpNatRuleExtra); + _rulesInNatLayer += 1; + } + } + else + { + _errorsList.Add(cpNatRule.Name + " NAT rule contains FQDN object so it can not been converted."); + } + } + else + { + counterNatRules -= 1; + _errorsList.AddRange(messagesE); + } + _warningsList.AddRange(messagesW); + } + } + } + } + } + } + + public CheckPointObject CreateNatServiceTcpFromStatDest(PA_NatRuleEntry paNatRuleEntry) + { + CheckPoint_TcpService natServiceTcp = new CheckPoint_TcpService(); + natServiceTcp.Name = InspectObjectName("Nat_TrTcp_" + paNatRuleEntry.Name, CP_OBJECT_TYPE_NAME_SERVICE_TCP); + natServiceTcp.Port = paNatRuleEntry.DestinationTranslation.TranslatedPort; + + return InspectService(natServiceTcp); + } + + public CheckPointObject CreateNatServiceUdpFromStatDest(PA_NatRuleEntry paNatRuleEntry) + { + CheckPoint_UdpService natServiceUdp = new CheckPoint_UdpService(); + natServiceUdp.Name = InspectObjectName("Nat_TrUdp_" + paNatRuleEntry.Name, CP_OBJECt_TYPE_NAME_SERVICE_UDP); + natServiceUdp.Port = paNatRuleEntry.DestinationTranslation.TranslatedPort; + + return InspectService(natServiceUdp); + } + + public CheckPointObject CreateNatServiceTcpFromDynDest(PA_NatRuleEntry paNatRuleEntry) + { + CheckPoint_TcpService natServiceTcp = new CheckPoint_TcpService(); + natServiceTcp.Name = InspectObjectName("Nat_TrTcp_" + paNatRuleEntry.Name, CP_OBJECT_TYPE_NAME_SERVICE_TCP); + natServiceTcp.Port = paNatRuleEntry.DynamicDestinationTranslation.TranslatedPort; + + return InspectService(natServiceTcp); + } + + public CheckPointObject CreateNatServiceUdpFromDynDest(PA_NatRuleEntry paNatRuleEntry) + { + CheckPoint_UdpService natServiceUdp = new CheckPoint_UdpService(); + natServiceUdp.Name = InspectObjectName("Nat_TrUdp_" + paNatRuleEntry.Name, CP_OBJECt_TYPE_NAME_SERVICE_UDP); + natServiceUdp.Port = paNatRuleEntry.DynamicDestinationTranslation.TranslatedPort; + + return InspectService(natServiceUdp); + } + + public void GetServicesTypesFromServicesGroup( + CheckPoint_ServiceGroup cpSrvGroup, + List cpServicesGroups, + List cpServices, + out bool isTcpSrv, out bool isUdpSrv) + { + isTcpSrv = false; + isUdpSrv = false; + + foreach (string cpSrvMember in cpSrvGroup.Members) + { + CheckPointObject cpSrv = cpServices.Find(x => x.Name.Equals(cpSrvMember)); + if (cpSrv != null) + { + if (cpSrv.GetType() == typeof(CheckPoint_TcpService)) + isTcpSrv = true; + else if (cpSrv.GetType() == typeof(CheckPoint_UdpService)) + isUdpSrv = true; + + continue; + } + + CheckPoint_ServiceGroup cpSrvGrp = cpServicesGroups.Find(x => x.Name.Equals(cpSrvMember)); + if (cpSrvGrp != null) + { + GetServicesTypesFromServicesGroup(cpSrvGrp, cpServicesGroups, cpServices, out isTcpSrv, out isUdpSrv); + } + } + } + + public void GetServicesGroupsFromServiceGroup( + CheckPoint_ServiceGroup cpSrvGroup, + List cpServicesGroups, + List cpServices, + List cpSrvGrpMembersTcp, + List cpSrvGrpMembersUdp) + { + foreach (string cpSrvMember in cpSrvGroup.Members) + { + CheckPointObject cpSrv = cpServices.Find(x => x.Name.Equals(cpSrvMember)); + if (cpSrv != null) + { + if (cpSrv.GetType() == typeof(CheckPoint_TcpService)) + { + cpSrvGrpMembersTcp.Add(cpSrv); + } + else if (cpSrv.GetType() == typeof(CheckPoint_UdpService)) + { + cpSrvGrpMembersUdp.Add(cpSrv); + } + else if (cpSrv.GetType() == typeof(CheckPoint_PredifinedObject) && cpPredefServicesTypes.ContainsKey(cpSrv.Name)) + { + string srvType = cpPredefServicesTypes[cpSrv.Name].ToLower(); + if (srvType.Equals(SERVICE_TYPE_TCP.ToLower())) + { + cpSrvGrpMembersTcp.Add(cpSrv); + } + else if (srvType.Equals(SERVICE_TYPE_UDP.ToLower())) + { + cpSrvGrpMembersUdp.Add(cpSrv); + } + } + continue; + } + + CheckPoint_ServiceGroup cpSrvGrp = cpServicesGroups.Find(x => x.Name.Equals(cpSrvMember)); + if (cpSrvGrp != null) + { + GetServicesGroupsFromServiceGroup(cpSrvGrp, cpServicesGroups, cpServices, cpSrvGrpMembersTcp, cpSrvGrpMembersUdp); + } + } + } + + #endregion + + #region Utility methods + + public void AddCpApplicationGroup(CheckPoint_ApplicationGroup cpAppGrp, + Dictionary cpAppGroupsDict) + { + foreach (string member in cpAppGrp.Members) + { + if (cpAppGroupsDict.ContainsKey(member)) + { + AddCpApplicationGroup(cpAppGroupsDict[member], cpAppGroupsDict); + } + } + AddCheckPointObject(cpAppGrp); + } + + public void AddCpNetworkGroup(CheckPoint_NetworkGroup cpNetGroup, + Dictionary cpAddressesDict, + Dictionary cpNetGroupsDict) + { + foreach (string member in cpNetGroup.Members) + { + if (cpAddressesDict.ContainsKey(member)) + { + AddCheckPointObject(cpAddressesDict[member]); + } + else if (cpNetGroupsDict.ContainsKey(member)) + { + AddCpNetworkGroup(cpNetGroupsDict[member], cpAddressesDict, cpNetGroupsDict); + AddCheckPointObject(cpNetGroupsDict[member]); + } + } + AddCheckPointObject(cpNetGroup); + } + + public void AddCpServiceGroup(CheckPoint_ServiceGroup cpSrvGroup, + Dictionary cpServicesDict, + Dictionary cpSrvGroupsDict) + { + foreach (string member in cpSrvGroup.Members) + { + if (cpServicesDict.ContainsKey(member)) + { + AddCheckPointObject(cpServicesDict[member]); + } + else if (cpSrvGroupsDict.ContainsKey(member)) + { + AddCpServiceGroup(cpSrvGroupsDict[member], cpServicesDict, cpSrvGroupsDict); + AddCheckPointObject(cpSrvGroupsDict[member]); + } + } + AddCheckPointObject(cpSrvGroup); + } + + public static string GetSafeName(string name) + { + if (name != null && !name.Trim().Equals("")) + { + return Regex.Replace(name, RE_NAME_UNSAFE, "_"); + } + else + { + return name; + } + } + + protected override string GetVendorName() + { + return Vendor.PaloAlto.ToString(); + } + #endregion + + public Dictionary GetDevicesUIDdict(string filename) + { + Dictionary devicesUIDDict = new Dictionary(); + + string outConfigsFolder = filename; + string[] configsFolder = Directory.GetDirectories(outConfigsFolder);//get uncompressed folder name + string[] configFilesArray = Directory.GetFiles(configsFolder[0]); + + string configName; + string deviceName; + string deviceUID; + + foreach (string confFile in configFilesArray) + { + + if (confFile.IndexOf("\\") != -1 && confFile.IndexOf(".xml") != -1) + { + configName = confFile.Substring(confFile.LastIndexOf("\\") + 1); + configName = configName.Substring(0, configName.IndexOf(".xml")); + + if (configName.IndexOf("_") != -1) + { + deviceName = configName.Substring(0, configName.LastIndexOf("_")); + deviceUID = configName.Substring(configName.LastIndexOf("_") + 1); + devicesUIDDict.Add(deviceUID, deviceName); + } + } + } + Directory.Delete(outConfigsFolder, true); + return devicesUIDDict; + } + } +} diff --git a/PaloAltoMigration/PanoramaParser.cs b/PaloAltoMigration/PanoramaParser.cs new file mode 100644 index 00000000..9322c51c --- /dev/null +++ b/PaloAltoMigration/PanoramaParser.cs @@ -0,0 +1,164 @@ +using MigrationBase; +using System; +using System.IO; +using System.Diagnostics; +using System.Collections.Generic; +using System.Xml; +using System.Xml.Serialization; + +namespace PanoramaPaloAltoMigration + +{ + public class PanoramaParser : VendorParser + { + private static string _archiveName; + public string _ArchiveName + { + get { return _archiveName; } + set { _archiveName = value; } + } + + public Panorama_Config Config { get; set; } + + public override void Export(string filename) + { + } + + public override void Parse(string filename) + { + + } + + public void ParseWithTargetFolder(string filename, string targetFolder) + { + if (!targetFolder.EndsWith("\\")) + targetFolder += "\\"; + UncompressArchive(filename,targetFolder); + + string outConfigsFolder = targetFolder + "configs"; + _ArchiveName = outConfigsFolder; + string panoramaConfig = GetPanoramaConfFile(outConfigsFolder); + + XmlSerializer serializer = new XmlSerializer(typeof(Panorama_Config)); + + using (FileStream fileStream = new FileStream(panoramaConfig, FileMode.Open)) + { + Config = (Panorama_Config)serializer.Deserialize(fileStream); + + ParseVersion(null); + } + } + + protected override void ParseVersion(object versionProvider) + { + VendorVersion = Config.Version; + } + + public string GetPanoramaConfFile(string outConfigsFolder) + { + string panoramaConfig = null; + + string[] configsFolder = Directory.GetDirectories(outConfigsFolder);//get uncompressed folder name + string[] configFilesArray = Directory.GetFiles(configsFolder[0]);//get list of panorama and firewalls config files + + foreach (string confFile in configFilesArray) + { + if (DetectPanoramaConfFile(confFile)) + { + panoramaConfig = confFile; + break; + } + } + return panoramaConfig; + } + + public bool DetectPanoramaConfFile(string fileName) + { + bool is_panorama = false; + XmlDocument xDoc = new XmlDocument(); + try + { + xDoc.Load(fileName); + XmlElement xRoot = xDoc.DocumentElement; + XmlNode panoramaNode = xRoot.SelectSingleNode("panorama"); + if (panoramaNode != null) + is_panorama = true; + } + catch { } + return is_panorama; + } + + /// + /// //checks if Panorama or standalone PA firewall configuration is converted + /// + public bool CheckPaloAltoConfiguartion(String filename) + { + bool is_panorama = false; + List archiveExt = new List { ".tgz" }; + + string extension = Path.GetExtension(filename); + + if (archiveExt.Contains(extension)) + { + is_panorama = true; + } + else + { + Console.WriteLine("Configs archive must be in .tgz format!"); + } + return is_panorama; + } + + public void UncompressArchive(string archiveName, string targetFolder) + { + string compressorsDirPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "compressors"; + string archiveCopyName = targetFolder + archiveName.Substring(archiveName.LastIndexOf("\\") + 1); + archiveCopyName = archiveCopyName.Substring(0, archiveCopyName.IndexOf(".tgz")) + "_copy" + ".tgz"; + File.Copy(archiveName, archiveCopyName, true); + + #region uncompress .TGZ archive + ProcessStartInfo startInfo = new ProcessStartInfo(); + startInfo.UseShellExecute = false; + startInfo.CreateNoWindow = true; + Process uncompressProc = null; + startInfo.FileName = Path.Combine(compressorsDirPath, "gzip.exe"); + startInfo.WorkingDirectory = archiveCopyName.Substring(0, archiveCopyName.LastIndexOf("\\")); + startInfo.Arguments = "-d" + " \"" + archiveCopyName + "\""; + startInfo.RedirectStandardOutput = true; + uncompressProc = Process.Start(startInfo); + startInfo.RedirectStandardError = true; + + string output = uncompressProc.StandardOutput.ReadToEnd(); + uncompressProc.WaitForExit(); + #endregion + + #region uncompress .TAR archive + startInfo = new ProcessStartInfo(); + startInfo.UseShellExecute = false; + startInfo.CreateNoWindow = true; + Process uncompressTarProc = null; + startInfo = new ProcessStartInfo(); + startInfo.UseShellExecute = false; + startInfo.CreateNoWindow = true; + + string tarArchiveName = archiveCopyName.Substring(0, archiveCopyName.LastIndexOf(".tgz")) + ".tar"; + + startInfo.FileName = Path.Combine(compressorsDirPath, "gtar.exe"); + + string outConfigsFolder = tarArchiveName.Substring(0, tarArchiveName.LastIndexOf("\\")) + "\\configs"; + Directory.CreateDirectory(outConfigsFolder); + startInfo.WorkingDirectory = outConfigsFolder; + startInfo.Arguments = "-xvf \"" + tarArchiveName + "\" --force-local"; + startInfo.RedirectStandardOutput = true; + uncompressTarProc = Process.Start(startInfo); + startInfo.RedirectStandardError = true; + + output = uncompressTarProc.StandardOutput.ReadToEnd(); + uncompressTarProc.WaitForExit(); + + if (File.Exists(tarArchiveName)) + File.Delete(tarArchiveName); + #endregion + } + } +} diff --git a/PaloAltoMigration/Panorama_Config.cs b/PaloAltoMigration/Panorama_Config.cs new file mode 100644 index 00000000..91d211f5 --- /dev/null +++ b/PaloAltoMigration/Panorama_Config.cs @@ -0,0 +1,626 @@ +using System.Collections.Generic; +using System.Xml.Serialization; + +namespace PanoramaPaloAltoMigration +{ + #region Abstract Interfaces + + public abstract class PA_Entry + { + [XmlAttribute("name")] + public string Name { get; set; } + } + + public abstract class PA_EntryExt : PA_Entry + { + private string _description; + + [XmlElement("description")] + public string Description + { + get + { + if (_description == null) + return ""; + else + return _description; + } + set + { + _description = value; + } + } + + [XmlArray("tag")] + [XmlArrayItem("member")] + public List TagMembers { get; set; } + } + + #endregion + + #region Main XML tags binding + + [XmlRoot("config")] + public class Panorama_Config + { + [XmlAttribute("version")] + public string Version { get; set; } + + [XmlElement("shared")] + public PA_Shared Shared { get; set; } + + [XmlElement("devices")] + public PA_Devices Devices { get; set; } + + } + + public class PA_Shared : PA_Objects + { + [XmlElement("pre-rulebase")] + public PA_PreRulebase PreRulebase { get; set; } + [XmlElement("post-rulebase")] + public PA_PostRulebase PostRulebase { get; set; } + } + + #region devices XML tags binding + public class PA_Devices + { + [XmlElement("entry")] + public PA_DevicesEntry DevicesEntry { get; set; } + } + #endregion + + + public class PA_DevicesEntry : PA_Entry + { + [XmlArray("device-group")] + [XmlArrayItem("entry")] + public List DeviceGroupEntries { get; set; } + + [XmlArray("template")] + [XmlArrayItem("entry")] + public List TemplateEntries { get; set; } + + [XmlArray("template-stack")] + [XmlArrayItem("entry")] + public List TemplateStackEntries { get; set; } + } + + public class PA_TemplateStackEntry : PA_Entry + { + [XmlArray("templates")] + [XmlArrayItem("member")] + public List StackTemplatesMembers{ get; set; } + + + [XmlArray("devices")] + [XmlArrayItem("entry")] + public List DevicesEntries { get; set; } + } +/* + public class PA_StackTemplates: PA_Entry + { + [XmlElement("member")] + public List StackTemplateMembers { get; set; } + } +*/ + public class PA_DevicesTemplateStackMemberEntry: PA_Entry + { + + } + public class PA_DevicesTemplateStackEntry : PA_Entry + { + + } + + + public class PA_TemplateEntry : PA_Entry + { + [XmlElement("config")] + public PA_TemplateConfig Config { get; set; } + + } + + public class PA_TemplateConfig : PA_Entry + { + [XmlElement("devices")] + public PA_DevicesTemplateEntry TemplateDevices { get; set; } + + } + + public class PA_DevicesTemplateEntry : PA_Entry + { + [XmlElement("entry")] + public PA_DevicesTemplateDevicesEntry TemplateDevicesEntry { get; set; } + } + + public class PA_DevicesTemplateDevicesEntry : PA_Entry + { + [XmlElement("network")] + public PA_Network Network { get; set; } + + [XmlArray("vsys")] + [XmlArrayItem("entry")] + public List VsysEntries { get; set; } + } + + public class PA_DeviceGroupEntry : PA_Objects + { + [XmlElement("pre-rulebase")] + public PA_PreRulebase PreRulebase { get; set; } + [XmlElement("post-rulebase")] + public PA_PostRulebase PostRulebase { get; set; } + + [XmlArray("devices")] + [XmlArrayItem("entry")] + public List DevicesGroupDevicesEntries { get; set; } + } + + public class PA_PostRulebase + { + [XmlElement("default-security-rules")] + public PA_Security Security { get; set; } + } + + public class PA_DevicesGroupDevicesEntry : PA_Entry // devices serial numbers + { + + } + + public class PA_PreRulebase + { + [XmlElement("security")] + public PA_Security Security { get; set; } + + [XmlElement("nat")] + public PA_Nat Nat { get; set; } + } + #endregion + + #region Network XML tags binding + + public class PA_Network + { + [XmlElement("interface")] + public PA_Interface Interface { get; set; } + } + + public class PA_Interface + { + [XmlArray("ethernet")] + [XmlArrayItem("entry")] + public List EthernetEntries { get; set; } + } + + public class PA_EthernetEntry : PA_Entry + { + [XmlElement("layer3")] + public PA_EthernetLayer3 Layer3 { get; set; } + } + + public class PA_EthernetLayer3 + { + + } + + #endregion + + #region XML tags binding of Content + + public class PA_Objects : PA_Entry + { + [XmlArray("tag")] + [XmlArrayItem("entry")] + public List TagsEntries { get; set; } + + [XmlArray("address")] + [XmlArrayItem("entry")] + public List AddressEntries { get; set; } + + [XmlArray("address-group")] + [XmlArrayItem("entry")] + public List AddressGroupEntries { get; set; } + + [XmlArray("service")] + [XmlArrayItem("entry")] + public List ServiceEntries { get; set; } + + [XmlArray("service-group")] + [XmlArrayItem("entry")] + public List ServiceGroupEntries { get; set; } + + [XmlArray("application-group")] + [XmlArrayItem("entry")] + public List ApplicationGroupsEntries { get; set; } + + [XmlArray("application-filter")] + [XmlArrayItem("entry")] + public List ApplicationFiltersEntries { get; set; } + + [XmlArray("schedule")] + [XmlArrayItem("entry")] + public List ScheduleEntries { get; set; } + } + + public class PA_Vsys + { + [XmlElement("entry")] + public List VsysEntries { get; set; } + } + + public class PA_VsysEntry : PA_Objects + { + [XmlArray("zone")] + [XmlArrayItem("entry")] + public List ZoneEntries { get; set; } +/* + [XmlElement("rulebase")] + public PA_Rulebase Rulebase { get; set; }*/ + } + + public class PA_TagEntry : PA_Entry { /* the class is empty as we need to know only 'name' attribute of Tag entry */ } + + public class PA_Rulebase + { + [XmlElement("security")] + public PA_Security Security { get; set; } + + [XmlElement("nat")] + public PA_Nat Nat { get; set; } + } + + #endregion + + #region Zone XML tags binding + + public class PA_ZoneEntry : PA_EntryExt { /* the class is empty as we need to know Zone's name only */ } + + #endregion + + #region Addresses & Address Groups XML tags binding + + public class PA_AddressEntry : PA_EntryExt + { + //control elements which tells which object we have + + [XmlElement("ip-netmask")] + public string IpNetmask { get; set; } + + [XmlElement("ip-range")] + public string IpRange { get; set; } + + [XmlElement("fqdn")] + public string Fqdn { get; set; } + } + + public class PA_AddressGroupEntry : PA_EntryExt + { + [XmlArray("static")] + [XmlArrayItem("member")] + public List StaticMembers { get; set; } + + [XmlElement("dynamic")] + public PA_AddressGroupEntryDynamic Dynamic { get; set; } + } + + public class PA_AddressGroupEntryDynamic + { + [XmlElement("filter")] + public string Filter { get; set; } + } + + #endregion + + #region Services & Service Groups XML tags binding + + public class PA_ServiceEntry : PA_EntryExt + { + [XmlElement("protocol")] + public PA_ServiceProtocol Protocol { get; set; } + } + + public class PA_ServiceProtocol + { + [XmlElement("tcp")] + public PA_ServiceTcpUdp ServiceTcp { get; set; } + + [XmlElement("udp")] + public PA_ServiceTcpUdp ServiceUdp { get; set; } + } + + public class PA_ServiceTcpUdp + { + [XmlElement("port")] + public string Port { get; set; } + + [XmlElement("source-port")] + public string SourcePort { get; set; } + } + + // Definition for the groups of services + + public class PA_ServiceGroupEntry : PA_EntryExt + { + [XmlArray("members")] + [XmlArrayItem("member")] + public List Members { get; set; } + } + + #endregion + + #region Application Group and Application Filter XML tags binding + + public class PA_ApplicationGroupEntry : PA_Entry + { + [XmlArray("members")] + [XmlArrayItem("member")] + public List ApplicationGroupMembers { get; set; } + } + + public class PA_ApplicationFilterEntry : PA_Entry + { + [XmlArray("category")] + [XmlArrayItem("member")] + public List CategoryMembers { get; set; } + + [XmlArray("subcategory")] + [XmlArrayItem("member")] + public List SubcategoryMembers { get; set; } + } + + #endregion + + #region Schedules XML tags binding + + public class PA_ScheduleEntry : PA_EntryExt + { + [XmlElement("schedule-type")] + public PA_ScheduleType Type { get; set; } + } + + public class PA_ScheduleType + { + [XmlElement("recurring")] + public PA_ScheduleRecurring Recurring { get; set; } + + [XmlElement("non-recurring")] + public PA_ScheduleNonRecurring NonRecurring { get; set; } + } + + public class PA_ScheduleRecurring + { + [XmlArray("daily")] + [XmlArrayItem("member")] + public List MembersDaily { get; set; } + + [XmlElement("weekly")] + public PA_ScheduleRecurringWeekly Weekly { get; set; } + } + + public class PA_ScheduleRecurringWeekly + { + [XmlArray("monday")] + [XmlArrayItem("member")] + public List MembersMonday { get; set; } + + [XmlArray("tuesday")] + [XmlArrayItem("member")] + public List MembersTuesday { get; set; } + + [XmlArray("wednesday")] + [XmlArrayItem("member")] + public List MembersWednesday { get; set; } + + [XmlArray("thursday")] + [XmlArrayItem("member")] + public List MembersThursday { get; set; } + + [XmlArray("friday")] + [XmlArrayItem("member")] + public List MembersFriday { get; set; } + + [XmlArray("saturday")] + [XmlArrayItem("member")] + public List MembersSaturday { get; set; } + + [XmlArray("sunday")] + [XmlArrayItem("member")] + public List MembersSunday { get; set; } + } + + public class PA_ScheduleNonRecurring + { + [XmlElement("member")] + public List Memebers { get; set; } + } + + #endregion + + #region Security XML tags binding (policy rules) + + public class PA_Security + { + [XmlArray("rules")] + [XmlArrayItem("entry")] + public List RulesList { get; set; } + } + + public class PA_SecurityRuleEntry : PA_EntryExt + { + [XmlArray("from")] //Source Zone List + [XmlArrayItem("member")] + public List FromList { get; set; } + + [XmlArray("to")] //Destination Zone List + [XmlArrayItem("member")] + public List ToList { get; set; } + + [XmlArray("source")] + [XmlArrayItem("member")] + public List SourceList { get; set; } + + [XmlArray("destination")] + [XmlArrayItem("member")] + public List DestinationList { get; set; } + + [XmlArray("source-user")] + [XmlArrayItem("member")] + public List SourceUserList { get; set; } + + [XmlArray("application")] + [XmlArrayItem("member")] + public List ApplicationList { get; set; } + + [XmlArray("service")] + [XmlArrayItem("member")] + public List ServiceList { get; set; } + + [XmlElement("action")] + public string Action { get; set; } + + [XmlElement("schedule")] + public string Schedule { get; set; } + + [XmlElement("rule-type")] + public string RuleType { get; set; } + + [XmlElement("log-start")] + public string LogStart { get; set; } + + [XmlElement("log-end")] + public string LogEnd { get; set; } + + [XmlElement("disabled")] + public string Disabled { get; set; } + + [XmlArray("category")] + [XmlArrayItem("member")] + public List CategoryList { get; set; } + + [XmlElement("negate-source")] + public string NegateSource { get; set; } + + [XmlElement("negate-destination")] + public string NegateDestination { get; set; } + + [XmlElement("target")] + public PA_Target Target { get; set; } + } + + + public class PA_Target : PA_Entry + { + [XmlElement("negate")] + public string Negate { get; set; } + + [XmlArray("devices")] + [XmlArrayItem("entry")] + public List DevicesEntry { get; set; } + } + + public class PA_TargetDeviceEntry : PA_Entry{} + +#endregion + + #region NAT XML tags binding (NAT rules) + + public class PA_Nat + { + [XmlArray("rules")] + [XmlArrayItem("entry")] + public List RulesList { get; set; } + } + + public class PA_NatRuleEntry : PA_EntryExt + { + [XmlArray("source")] + [XmlArrayItem("member")] + public List SourceList { get; set; } + + [XmlArray("destination")] + [XmlArrayItem("member")] + public List DestinationList { get; set; } + + [XmlElement("service")] + public string Service { get; set; } + + [XmlElement("source-translation")] + public PA_SourceTranslation SourceTranslation { get; set; } + + [XmlElement("destination-translation")] + public PA_DestinationTranslation DestinationTranslation { get; set; } + + [XmlElement("dynamic-destination-translation")] + public PA_DynamicDestinationTranslation DynamicDestinationTranslation { get;set;} + + [XmlElement("disabled")] + public string Disabled { get; set; } + + [XmlElement("target")] + public PA_Target Target { get; set; } + } + + public class PA_SourceTranslation + { + [XmlElement("static-ip")] + public PA_StaticIp StaticIp { get; set; } + + [XmlElement("dynamic-ip")] + public PA_DynamicIp DynamicIp { get; set; } + + [XmlElement("dynamic-ip-and-port")] + public PA_DynamicIpAndPort DynamicIpAndPort { get; set; } + } + + public class PA_StaticIp + { + [XmlElement("translated-address")] + public string TranslatedAddress { get; set; } + + [XmlElement("bi-directional")] + public string IsBiDirectional { get; set; } + } + + public class PA_DynamicIp + { + [XmlArray("translated-address")] + [XmlArrayItem("member")] + public List TranslatedAddresses { get; set; } + } + + public class PA_DynamicIpAndPort + { + [XmlArray("translated-address")] + [XmlArrayItem("member")] + public List TranslatedAddresses { get; set; } + + [XmlElement("interface-address")] + public PA_InterfaceAddress InterfaceAddress { get; set; } + } + + public class PA_InterfaceAddress + { + [XmlElement("ip")] + public string Ip { get; set; } + } + + public class PA_DestinationTranslation + { + [XmlElement("translated-address")] + public string TranslatedAddress { get; set; } + + [XmlElement("translated-port")] + public string TranslatedPort { get; set; } + } + + public class PA_DynamicDestinationTranslation + { + [XmlElement("translated-address")] + public string TranslatedAddress { get; set; } + + [XmlElement("translated-port")] + public string TranslatedPort { get; set; } + } + + #endregion +} diff --git a/README.md b/README.md index 738fa374..1ef98dad 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,24 @@ # SmartMove Check Point SmartMove tool enables you to convert 3rd party database with firewall security policy and NAT to Check Point database. -At the moment, the tool parses Cisco ASA, Juniper JunosOS/ScreenOS, Fortinet FortiOS and PaloAlto PAN-OS configurations and converts the objects, NAT and firewall policy to a Check Point R80.10 compliant policy. The tool is planned to support additional vendors and security configurations in the future. +At the moment, the tool parses Cisco ASA, Juniper JunosOS/ScreenOS, Fortinet FortiOS, PaloAlto PAN-OS and PaloAlto Panorama configurations and converts the objects, NAT and firewall policy to a Check Point R80.10 compliant policy. The tool is planned to support additional vendors and security configurations in the future. The tool generates bash scripts by utilizing Check Point Management API's command line interface, to migrate the converted policy into a R80.10 Management (or Multi-Domain) server. For SmartMove tool release notes and latest updates, please refer to Check Point sk115416 at: https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk115416 + +## Smart Connector and PaloAlto Panorama Instructions +'Smart Connector' and 'PaloAlto Panorama' are using external reasorces. + +* Dowload the required package from the Check Point Support Center:
+https://supportcenter.checkpoint.com/supportcenter/portal?action=portlets.DCFileAction&eventSubmit_doGetdcdetails=&fileid=110747 +* Extract the downloaded package into this path inside your project:
+```SmartMove\SmartMove\compressors\``` +* Rebuild the solution: + * In Solution Explorer, choose or open the solution. + * On the menu bar, choose Build, and then choose Rebuild Solution. + ## Development Environment The tool is developed using Microsoft C# language and .Net framework version 4.5 (WPF application). The project solution file is configured for Microsoft Visual Studio 2012 and above. diff --git a/SmartMove/App.xaml.cs b/SmartMove/App.xaml.cs index ceb84e5d..f25c263e 100644 --- a/SmartMove/App.xaml.cs +++ b/SmartMove/App.xaml.cs @@ -24,5 +24,10 @@ namespace SmartMove /// public partial class App : Application { + public App() + { + InitializeComponent(); + } + } } diff --git a/SmartMove/CommandLine.cs b/SmartMove/CommandLine.cs new file mode 100644 index 00000000..ed624fca --- /dev/null +++ b/SmartMove/CommandLine.cs @@ -0,0 +1,529 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Linq; +using System.IO; +using CiscoMigration; +using JuniperMigration; +using MigrationBase; +using NetScreenMigration; +using FortiGateMigration; +using PaloAltoMigration; +using PanoramaPaloAltoMigration; +using System.Text.RegularExpressions; + +namespace SmartMove +{ + /// + /// Represents command line logic + /// + class CommandLine + { + private string[] arguments { get; set; } + + public CommandLine(string[] args) + { + this.arguments = args; + } + + #region command line options + //–f “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 + { + get { return vendor; } + set { vendor = value; } + } + + //-t “D:\SmartMove\Content + private string targetFolder { get; set; } + public string TargetFolder + { + get { return targetFolder; } + set { targetFolder = value; } + } + + //-d domain + private string domain { get; set; } + public string Domain + { + get { return domain; } + set { domain = value; } + } + + //-n + private bool convertNat { get; set; } + public bool ConvertNat + { + get { return convertNat; } + set { convertNat = value; } + } + + //-u unit1 + private string ldapAccountUnit { get; set; } + public string LdapAccountUnit + { + get { return ldapAccountUnit; } + set { ldapAccountUnit = value; } + } + + private bool convertUserConfiguration { get; set; } + public bool ConvertUserConfiguration + { + get { return convertUserConfiguration; } + set { convertUserConfiguration = value; } + } + //-i + private bool dontImportUnusedObjects { get; set; } + public bool DontImportUnusedObjects + { + get { return dontImportUnusedObjects; } + set { dontImportUnusedObjects = value; } + } + #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(); + 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(); + Console.WriteLine("Example:"); + Console.WriteLine("\t" + "SmartMove.exe –f \"D:\\SmartMove\\Content\\config.txt\" –v CiscoASA - t \"D:\\SmartMove\\Content\" –n"); + return 0; + } + + /* + * Verifies that mandatory options are specified in command line. + * Also checks options validity for the specific vendor. + */ + public int CheckOptionsValidity(CommandLine commandLine) + { + var fullVendorsList = new List { "CiscoASA", "JuniperSRX", "JuniperSSG", "FortiNet", "PaloAlto", "Panorama" }; + var vendorsList1 = new List { "CiscoASA", "JuniperSRX", "JuniperSSG" }; + var vendorsList2 = new List { "FortiNet", "PaloAlto", "Panorama" }; + 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); + 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); + 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); + 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); + 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); + return 0; + } + + } + if (vendorsList2.Contains(commandLine.Vendor)) + { + 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); + return 0; + } + + } + if ((commandLine.vendor == "JuniperSRX" || commandLine.vendor == "PaloAlto") && !commandLine.configFileName.EndsWith(".xml")) + { + Console.WriteLine("Config file for " + commandLine.vendor + " must be in .xml format!"); + return 0; + } + if (commandLine.vendor == "Panorama" && !commandLine.configFileName.EndsWith(".tgz")) + { + Console.WriteLine("Config files archive for " + commandLine.vendor + " must be in .tgz format!"); + return 0; + } + return 1; + } + + /* + * Workaround method to prevent incorrect interpretation of \" sequense in target directory option while reading command line arguments. + * The reason is that a double quotation mark preceded by a backslash, \", is interpreted as a literal double quotation mark ("). + * This method creates an array of command line arguments from the command line string. + * e.g. + * -t "D:\SmartMove\Content\" + */ + + public string[] regenerateArgs(string commandLineString) + { + String[] args = null; + + var parts = Regex.Matches(commandLineString, @"[\""].+?[\""]|[^ ]+") + .Cast() + .Select(m => m.Value) + .ToList(); + parts.RemoveAt(0); + + string buf; + List finalArgs = new List (); + foreach (var item in parts) + { + if (item.StartsWith("\"") && item.EndsWith("\"")) + { + buf = item.Substring(1, item.Length - 2); + finalArgs.Add(buf); + } + else + { + finalArgs.Add(item); + } + + } + args = finalArgs.ToArray(); + + return args; + } + + /* + * Parses input options and writes its values to ComamndLine class fields + */ + public CommandLine Parse(string[] args) + { + for (int i = 0; i < args.Length; i++) + { + switch (args[i]) + { + case "-f": + { + 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 + { + Console.WriteLine("Value for mandatory option -f is not specified! ", MessageTypes.Error); + } + + break; + } + case "-v": + { + 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); + break; + } + case "-t": + { + if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) + this.targetFolder = args[i + 1]; + else + Console.WriteLine("Value for target folder option -t is not specified. Default value will be set!", MessageTypes.Error); + break; + } + case "-d": + { + if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) + this.domain = args[i + 1]; + else + Console.WriteLine("Value for option -d is not specified! ", MessageTypes.Error); + break; + } + case "-n": + { + this.convertNat = true; + break; + } + case "-u": + { + if (args[i] != args.Last() && !args[i + 1].StartsWith("-")) + { + this.ldapAccountUnit = args[i + 1]; + this.ConvertUserConfiguration = true; + } else + { + this.ConvertUserConfiguration = true; + //Console.WriteLine("Value for option -u is not specified! ", MessageTypes.Error); + } + + break; + } + case "-i": + { + this.dontImportUnusedObjects = true; + break; + } + } + } + return this; + } + + /* + * This is the analog to MainWindow.Go_OnClick() function if application is run as WPF. + * It performs the migration. + */ + public void DoMigration(CommandLine commandLine) + { + + string fileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName); + //Console.WriteLine("File name: " + fileName); + + if (string.IsNullOrEmpty(commandLine.ConfigFileName) || string.IsNullOrEmpty(fileName)) + { + Console.WriteLine("Configuration file is not selected.", MessageTypes.Error); + return; + } + + if (!File.Exists(commandLine.ConfigFileName)) + { + Console.WriteLine("Cannot find configuration file.", MessageTypes.Error); + return; + } + + if (fileName.Length > 20) + { + Console.WriteLine("Configuration file name is restricted to 20 characters at most.", MessageTypes.Error); + return; + } + + if (!Directory.Exists(commandLine.TargetFolder)) + { + Console.WriteLine("Cannot find target folder for conversion output.", MessageTypes.Error); + return; + } + + VendorParser vendorParser; + + switch (commandLine.Vendor) + { + case "CiscoASA": + vendorParser = new CiscoParser(); + break; + case "JuniperSRX": + vendorParser = new JuniperParser(); + break; + case "JuniperSSG": + vendorParser = new ScreenOSParser(); + break; + case "FortiNet": + vendorParser = new FortiGateParser(); + break; + case "PaloAlto": + vendorParser = new PaloAltoParser(); + break; + case "Panorama": + vendorParser = new PanoramaParser(); + break; + default: + throw new InvalidDataException("Unexpected!!!"); + } + + try + { + string ciscoFile = commandLine.ConfigFileName; + Console.WriteLine("Parsing configuration file..."); + + if (commandLine.Vendor.Equals("Panorama")) + { + PanoramaParser panParser = (PanoramaParser)vendorParser; + panParser.ParseWithTargetFolder(ciscoFile, TargetFolder); + } + else + { + vendorParser.Parse(ciscoFile); + } + } + catch (Exception ex) + { + Console.WriteLine(string.Format("Could not parse configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + return; + } + + #region check middleware version + switch (commandLine.Vendor) + { + 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); + 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); + return; + } + break; + + 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); + 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); + return; + } + break; + + case "JuniperSSG": + break; + + 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); + 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); + 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); + 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); + 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); + 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); + return; + } + break; + } + #endregion + + string vendorFileName = Path.GetFileNameWithoutExtension(commandLine.ConfigFileName); + + string toolVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + + string targetFolder = commandLine.TargetFolder + "\\"; + + bool convertNat = commandLine.ConvertNat; + + string ldapAccountUnit = commandLine.LdapAccountUnit; + + vendorParser.Export(targetFolder + vendorFileName + ".json"); + + VendorConverter vendorConverter; + + switch (commandLine.Vendor) + { + case "CiscoASA": + vendorConverter = new CiscoConverter(); + break; + case "JuniperSRX": + vendorConverter = new JuniperConverter(); + break; + case "JuniperSSG": + vendorConverter = new ScreenOSConverter(); + break; + case "FortiNet": + FortiGateConverter fgConverter = new FortiGateConverter(); + fgConverter.OptimizeConf = commandLine.DontImportUnusedObjects; + fgConverter.ConvertUserConf = commandLine.ConvertUserConfiguration; + fgConverter.LDAPAccoutUnit = ldapAccountUnit; + vendorConverter = fgConverter; + break; + case "PaloAlto": + PaloAltoConverter paConverter = new PaloAltoConverter(); + paConverter.OptimizeConf = commandLine.DontImportUnusedObjects; + paConverter.ConvertUserConf = commandLine.ConvertUserConfiguration; + paConverter.LDAPAccoutUnit = ldapAccountUnit; + vendorConverter = paConverter; + break; + case "Panorama": + PanoramaConverter panoramaConverter = new PanoramaConverter(); + panoramaConverter.OptimizeConf = commandLine.DontImportUnusedObjects; + panoramaConverter.ConvertUserConf = commandLine.ConvertUserConfiguration; + panoramaConverter.LDAPAccoutUnit = ldapAccountUnit; + vendorConverter = panoramaConverter; + break; + default: + throw new InvalidDataException("Unexpected!!!"); + } + + vendorConverter.Initialize(vendorParser, commandLine.ConfigFileName, toolVersion, targetFolder, commandLine.Domain); + + try + { + Console.WriteLine("Conversion is in progress..."); + vendorConverter.Convert(convertNat); + Console.WriteLine("Conversion is finished."); + } + catch (Exception ex) + { + + Console.WriteLine(string.Format("Could not convert configuration file.\n\nMessage: {0}\nModule:\t{1}\nClass:\t{2}\nMethod:\t{3}", ex.Message, ex.Source, ex.TargetSite.ReflectedType.Name, ex.TargetSite.Name), MessageTypes.Error); + return; + } + + vendorConverter.ExportConfigurationAsHtml(); + vendorConverter.ExportPolicyPackagesAsHtml(); + if (commandLine.ConvertNat) + { + vendorConverter.ExportNatLayerAsHtml(); + } + } + } +} diff --git a/SmartMove/MainWindow.xaml.cs b/SmartMove/MainWindow.xaml.cs index 8623301f..0365276a 100644 --- a/SmartMove/MainWindow.xaml.cs +++ b/SmartMove/MainWindow.xaml.cs @@ -31,6 +31,7 @@ limitations under the License. using NetScreenMigration; using FortiGateMigration; using PaloAltoMigration; +using PanoramaPaloAltoMigration; namespace SmartMove { @@ -299,6 +300,13 @@ private void VendorSelector_OnSelectionChanged(object sender, SelectionChangedEv SkipUnusedObjects.Visibility = Visibility.Visible; ConvertUserConf.Visibility = Visibility.Visible; break; + case Vendor.PaloAltoPanorama: + ConfigurationFileLabel = SupportedVendors.PaloAltoPanoramaConfigurationFileLabel; + DomainNameTB.Visibility = Visibility.Collapsed; + DomainName.Visibility = Visibility.Collapsed; + SkipUnusedObjects.Visibility = Visibility.Visible; + ConvertUserConf.Visibility = Visibility.Visible; + break; } ConfigFilePath.Text = SourceFolder; @@ -336,7 +344,10 @@ private void BrowseConfigFile_OnClick(object sender, RoutedEventArgs e) filter = "conf files (*.conf)|*.conf"; break; case Vendor.PaloAlto: - filter = "xml files (*.xml)|*.xml"; + filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; + break; + case Vendor.PaloAltoPanorama: + filter = "Gzipped tar files (*.tgz)|*.tgz"; break; } @@ -423,14 +434,6 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) } } - Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; - EnableDisableControls(false); - ProgressPanel.Visibility = Visibility.Visible; - ResultsPanel.Visibility = Visibility.Collapsed; - OutputPanel.Visibility = Visibility.Visible; - - UpdateProgress(10, "Parsing configuration file ..."); - VendorParser vendorParser; switch (_supportedVendors.SelectedVendor) @@ -450,14 +453,51 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) case Vendor.PaloAlto: vendorParser = new PaloAltoParser(); break; + case Vendor.PaloAltoPanorama: + string compressorsDirPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "compressors"; + string compressorZip = Path.Combine(compressorsDirPath, "zip.exe"); + string compressorGtar = Path.Combine(compressorsDirPath, "gtar.exe"); + string compressorGzip = Path.Combine(compressorsDirPath, "gzip.exe"); + if (!File.Exists(compressorZip) || !File.Exists(compressorGtar) || !File.Exists(compressorGzip)) + { + ShowMessage(String.Format("{1}{0}{2}", Environment.NewLine, "The system cannot find the required files. ", + "Please follow"), MessageTypes.Error, "these instructions", "https://github.com/CheckPointSW/SmartMove#smart-connector-and-paloalto-panorama-instructions"); + return; + } + vendorParser = new PanoramaParser(); + break; default: throw new InvalidDataException("Unexpected!!!"); } + + Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; + EnableDisableControls(false); + ProgressPanel.Visibility = Visibility.Visible; + ResultsPanel.Visibility = Visibility.Collapsed; + OutputPanel.Visibility = Visibility.Visible; + + UpdateProgress(10, "Parsing configuration file ..."); + + string vendorFileName = Path.GetFileNameWithoutExtension(ConfigFilePath.Text); + string toolVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + string targetFolder = TargetFolderPath.Text + "\\"; + bool convertNat = ConvertNATConfiguration; + string ldapAccountUnit = LDAPAccountUnit.Text.Trim(); try { string ciscoFile = ConfigFilePath.Text; - await Task.Run(() => vendorParser.Parse(ciscoFile)); + switch (_supportedVendors.SelectedVendor) + { + case Vendor.PaloAltoPanorama: + PanoramaParser panParser = (PanoramaParser)vendorParser; + await Task.Run(() => panParser.ParseWithTargetFolder(ciscoFile,targetFolder)); + break; + default: + await Task.Run(() => vendorParser.Parse(ciscoFile)); + break; + } + } catch (Exception ex) { @@ -515,14 +555,20 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) 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); } break; + case Vendor.PaloAltoPanorama: + if (string.IsNullOrEmpty(vendorParser.Version)) + { + ShowMessage("Unspecified PaloAlto version.\nCannot find PaloAlto Panorama 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 Panorama 7.x and above configuration files.\nThe configuration may not parse correctly.", MessageTypes.Warning); + return; + } + break; } - string vendorFileName = Path.GetFileNameWithoutExtension(ConfigFilePath.Text); - string toolVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); - string targetFolder = TargetFolderPath.Text + "\\"; - bool convertNat = ConvertNATConfiguration; - string ldapAccountUnit = LDAPAccountUnit.Text.Trim(); - vendorParser.Export(targetFolder + vendorFileName + ".json"); VendorConverter vendorConverter; @@ -552,6 +598,13 @@ private async void Go_OnClick(object sender, RoutedEventArgs e) paConverter.LDAPAccoutUnit = ldapAccountUnit.Trim(); vendorConverter = paConverter; break; + case Vendor.PaloAltoPanorama: + PanoramaConverter panoramaConverter = new PanoramaConverter(); + panoramaConverter.OptimizeConf = SkipUnusedObjectsConversion; + panoramaConverter.ConvertUserConf = ConvertUserConfiguration; + panoramaConverter.LDAPAccoutUnit = ldapAccountUnit.Trim(); + vendorConverter = panoramaConverter; + break; default: throw new InvalidDataException("Unexpected!!!"); } @@ -699,6 +752,17 @@ private void ShowResults(VendorConverter vendorConverter, int convertedLinesCoun ConvertingWarningsCount = (paConverter.WarningsInConvertedPackage() != -1) ? string.Format(" ({0} warnings)", paConverter.WarningsInConvertedPackage()) : " Check report."; ConvertingErrorsCount = (paConverter.ErrorsInConvertedPackage() != -1) ? string.Format(" ({0} errors)", paConverter.ErrorsInConvertedPackage()) : " Check report."; break; + case Vendor.PaloAltoPanorama: + CoversionIssuesPreviewPanel.Visibility = Visibility.Visible; + ConvertedOptimizedPolicyPanel.Visibility = Visibility.Collapsed; + RulebaseOptimizedScriptLink.Visibility = Visibility.Collapsed; + + PanoramaConverter panoramaConverter = (PanoramaConverter)vendorConverter; + ConvertedPolicyRulesCount = (panoramaConverter.RulesInConvertedPackage() != -1) ? string.Format(" ({0} rules)", panoramaConverter.RulesInConvertedPackage()) : " Check report."; + ConvertedNATPolicyRulesCount = (panoramaConverter.RulesInNatLayer() != -1) ? string.Format(" ({0} rules)", panoramaConverter.RulesInNatLayer()) : " Check report."; + ConvertingWarningsCount = (panoramaConverter.WarningsInConvertedPackage() != -1) ? string.Format(" ({0} warnings)", panoramaConverter.WarningsInConvertedPackage()) : " Check report."; + ConvertingErrorsCount = (panoramaConverter.ErrorsInConvertedPackage() != -1) ? string.Format(" ({0} errors)", panoramaConverter.ErrorsInConvertedPackage()) : " Check report."; + break; default: CoversionIssuesPreviewPanel.Visibility = Visibility.Collapsed; ConvertedOptimizedPolicyPanel.Visibility = Visibility.Collapsed; @@ -801,10 +865,17 @@ private void HandleCommandLineArgs() } public static void ShowMessage(string message, MessageTypes messageType) + { + ShowMessage(message, messageType, null, null); + } + public static void ShowMessage(string message, MessageTypes messageType, string messageLinkText, string messageLinkValue) { var messageWindow = new MessageWindow { - Message = message, MessageType = messageType + Message = message, + MessageType = messageType, + MessageLinkText = messageLinkText, + MessageLinkValue = messageLinkValue }; messageWindow.ShowDialog(); diff --git a/SmartMove/MessageWindow.xaml b/SmartMove/MessageWindow.xaml index 59d43c87..a47fef74 100644 --- a/SmartMove/MessageWindow.xaml +++ b/SmartMove/MessageWindow.xaml @@ -85,8 +85,12 @@ - + + + + + + diff --git a/SmartMove/MessageWindow.xaml.cs b/SmartMove/MessageWindow.xaml.cs index 349aeffc..01b07604 100644 --- a/SmartMove/MessageWindow.xaml.cs +++ b/SmartMove/MessageWindow.xaml.cs @@ -16,6 +16,8 @@ limitations under the License. ********************************************************************/ using System.Windows; +using System.Diagnostics; +using System.Windows.Documents; using System.Windows.Input; namespace SmartMove @@ -48,7 +50,28 @@ public string Message DependencyProperty.Register("Message", typeof(string), typeof(MessageWindow), new PropertyMetadata(null)); #endregion + + #region MessageLink + public string MessageLinkText + { + get { return (string)GetValue(MessageLinkTextProperty); } + set { SetValue(MessageLinkTextProperty, value); } + } + + public static readonly DependencyProperty MessageLinkTextProperty = + DependencyProperty.Register("MessageLinkText", typeof(string), typeof(MessageWindow), new PropertyMetadata(null)); + + public string MessageLinkValue + { + get { return (string)GetValue(MessageLinkValueProperty); } + set { SetValue(MessageLinkValueProperty, value); } + } + public static readonly DependencyProperty MessageLinkValueProperty = + DependencyProperty.Register("MessageLinkValue", typeof(string), typeof(MessageWindow), new PropertyMetadata(null)); + + #endregion + #region MessageType public MessageTypes MessageType @@ -78,6 +101,15 @@ private void HeaderPanel_OnMouseDown(object sender, MouseButtonEventArgs e) DragMove(); } } + + private void Link_OnClick(object sender, RoutedEventArgs e) + { + var link = (Hyperlink)sender; + if (link.NavigateUri != null) + { + Process.Start(link.NavigateUri.ToString()); + } + } #endregion } diff --git a/SmartMove/Program.cs b/SmartMove/Program.cs new file mode 100644 index 00000000..700823b1 --- /dev/null +++ b/SmartMove/Program.cs @@ -0,0 +1,62 @@ +using System; +using System.Runtime.InteropServices; + +namespace SmartMove +{ + public static class Program + { + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern bool FreeConsole(); + + [STAThread] + /* + * Entry point + */ + public static int Main(string[] args) + { + if (args != null && args.Length > 0) + { + CommandLine commandLine = new CommandLine(args); + + //display command help + if (args[0].Equals("-help") || args[0].Equals("/?")) + { + return commandLine.DisplayHelp(); + } + + args = commandLine.regenerateArgs(Environment.CommandLine); + + commandLine = commandLine.Parse(args); +/* + Console.WriteLine(); + Console.WriteLine(" -> Config file name: " + commandLine.ConfigFileName); + Console.WriteLine(" -> Target folder: " + commandLine.TargetFolder); + Console.WriteLine(" -> Vendor: " + commandLine.Vendor); + Console.WriteLine(" -> Domain: " + commandLine.Domain); + Console.WriteLine(" -> Convert NAT option: " + commandLine.ConvertNat); + Console.WriteLine(" -> LDAP account unit: " + commandLine.LdapAccountUnit); + Console.WriteLine(" -> Convert user configuration option: " + commandLine.ConvertUserConfiguration); + Console.WriteLine(" -> Don't import unused objects option: " + commandLine.DontImportUnusedObjects); + Console.WriteLine();*/ + + int exitCode = commandLine.CheckOptionsValidity(commandLine); + + if (exitCode == 0) + { + return 0; + } else + { + commandLine.DoMigration(commandLine); + return 0; + } + } + else + { + FreeConsole(); + var app = new App(); + return app.Run(); + } + } + + } +} diff --git a/SmartMove/Properties/AssemblyInfo.cs b/SmartMove/Properties/AssemblyInfo.cs index 3ebf9cec..269af37c 100644 --- a/SmartMove/Properties/AssemblyInfo.cs +++ b/SmartMove/Properties/AssemblyInfo.cs @@ -49,5 +49,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("5.1.*")] +[assembly: AssemblyVersion("6.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SmartMove/Properties/Resources.Designer.cs b/SmartMove/Properties/Resources.Designer.cs index f5265615..258a1f07 100644 --- a/SmartMove/Properties/Resources.Designer.cs +++ b/SmartMove/Properties/Resources.Designer.cs @@ -22,16 +22,14 @@ namespace SmartMove.Properties [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { + internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { + internal Resources() { } /// @@ -56,14 +54,11 @@ internal Resources() /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { + internal static global::System.Globalization.CultureInfo Culture { + get { return resourceCulture; } - set - { + set { resourceCulture = value; } } diff --git a/SmartMove/Properties/Settings.Designer.cs b/SmartMove/Properties/Settings.Designer.cs index 2d5cb6f2..6a80f1b7 100644 --- a/SmartMove/Properties/Settings.Designer.cs +++ b/SmartMove/Properties/Settings.Designer.cs @@ -8,21 +8,17 @@ // //------------------------------------------------------------------------------ -namespace SmartMove.Properties -{ +namespace SmartMove.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase{ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - public static Settings Default - { - get - { + public static Settings Default { + get { return defaultInstance; } } diff --git a/SmartMove/SmartConnector/cpapi/__init__.py b/SmartMove/SmartConnector/cpapi/__init__.py new file mode 100644 index 00000000..a8a53c54 --- /dev/null +++ b/SmartMove/SmartConnector/cpapi/__init__.py @@ -0,0 +1,5 @@ +from .mgmt_api import APIClient +from .mgmt_api import APIClientArgs +from .api_exceptions import APIException +from .api_exceptions import APIClientException +from .api_response import APIResponse diff --git a/SmartMove/SmartConnector/cpapi/api_exceptions.py b/SmartMove/SmartConnector/cpapi/api_exceptions.py new file mode 100644 index 00000000..38f37469 --- /dev/null +++ b/SmartMove/SmartConnector/cpapi/api_exceptions.py @@ -0,0 +1,14 @@ +class APIException(Exception): + """An exception subclass for our API exceptions, also includes the response when available.""" + def __init__(self, value, response): + self.value = value + self.response = response + + def __str__(self): + return str(self.value) + + +class APIClientException(APIException): + def __init__(self, value): + APIException.__init__(self, value, None) + diff --git a/SmartMove/SmartConnector/cpapi/api_response.py b/SmartMove/SmartConnector/cpapi/api_response.py new file mode 100644 index 00000000..37ee3f78 --- /dev/null +++ b/SmartMove/SmartConnector/cpapi/api_response.py @@ -0,0 +1,112 @@ +import json +import sys + +from cpapi.utils import compatible_loads + +# compatible import for python 2 and 3 +from .api_exceptions import APIException +if sys.version_info >= (3, 0): + from http.client import HTTPResponse +else: + from httplib import HTTPResponse + + +# compatible iterator for python 2 and 3 +def iteritems(data): + if sys.version_info >= (3, 0): + return data.items() + else: + return data.iteritems() + + +def extract_error_and_warning_messages(data): + error_message = [] + + # get all errors and warnings as key-value pairs + for key, val in iteritems(data): + error_message.append(str(key) + ": ") + # value can be either string or list with dictionaries + if isinstance(val, list): + for error_or_warning in val: + error_message.append("\n- " + "message: " + error_or_warning["message"] + "\n") + else: + error_message.append(str(val) + "\n") + + return ''.join(error_message) + + +class APIResponse: + """ + An object to represent an API Response. + Contains data, status_code, success, and sometimes error_message + """ + def __repr__(self): + return '%s(%s)' % (type(self).__name__, json.dumps(self.as_dict(), indent=4, sort_keys=True)) + + def __init__(self, json_response, success, status_code=None, err_message=""): + self.status_code = status_code + self.data = None + + if err_message: + self.success = False + self.error_message = err_message + self.res_obj = {} + else: + self.success = success + try: + if isinstance(json_response, dict): + data_dict = json_response + else: + data_dict = compatible_loads(json_response) + except ValueError: + raise APIException("APIResponse received a response which is not a valid JSON.", json_response) + else: + self.data = data_dict + self.res_obj = {"status_code": self.status_code, "data": self.data} + if not self.success: + try: + self.error_message = extract_error_and_warning_messages(self.data) + except KeyError: + raise APIException("Unexpected error format.", json_response) + + def as_dict(self): + attribute_dict = { + "res_obj": self.res_obj, + "success": self.success, + "status_code": self.status_code, + "data": self.data + } + + try: + attribute_dict.update({"error_message": str(self.error_message)}) + except AttributeError: + pass + return attribute_dict + + def response(self): + """ + The response we return as an HTTP response. + Use instead of self.res_obj. + """ + return {"status_code": self.status_code, "data": self.data} + + @classmethod + def from_http_response(cls, http_response, err_message=""): + """ + Generate APIResponse from http_response object + + :param http_response: input HTTP response object + :param err_message: if there is an error message included, we include it in the APIResponse + :return: The APIResponse object we generated + """ + assert isinstance(http_response, HTTPResponse) + return cls(http_response.read(), success=(http_response.status == 200), status_code=http_response.status, + err_message=err_message) + + def set_success_status(self, status): + """ + This method sets the response success status + + :param status: input status + """ + self.success = status diff --git a/SmartMove/SmartConnector/cpapi/mgmt_api.py b/SmartMove/SmartConnector/cpapi/mgmt_api.py new file mode 100644 index 00000000..0ac3162d --- /dev/null +++ b/SmartMove/SmartConnector/cpapi/mgmt_api.py @@ -0,0 +1,701 @@ +# +# cp_management_api.py +# version 1.1 +# +# A library for communicating with Check Point's management server using [2.7.9 < python < 3] +# written by: Check Point software technologies inc. +# October 2016 +# tested with Check Point R80 (tested with take hero2 198) +# + +from __future__ import print_function + +import sys + +# compatible import for python 2 and 3 +from .api_exceptions import APIException, APIClientException +from .api_response import APIResponse +if sys.version_info >= (3, 0): + import http.client as http_client +else: + import httplib as http_client + +import hashlib +import json +import os.path +import ssl +import subprocess +import time + +from cpapi.utils import compatible_loads + + +class APIClientArgs: + """ + This class provides arguments for APIClient configuration. + All the arguments are configured with their default values. + """ + + # port is set to None by default, but it gets replaced with 443 if not specified + # context possible values - web_api (default) or gaia_api + def __init__(self, port=None, fingerprint=None, sid=None, server="127.0.0.1", http_debug_level=0, + api_calls=None, debug_file="", proxy_host=None, proxy_port=8080, + api_version=None, unsafe=False, unsafe_auto_accept=False, context="web_api"): + self.port = port + # management server fingerprint + self.fingerprint = fingerprint + # session-id. + self.sid = sid + # management server name or IP-address + self.server = server + # debug level + self.http_debug_level = http_debug_level + # an array with all the api calls (for debug purposes) + self.api_calls = api_calls if api_calls else [] + # name of debug file. If left empty, debug data will not be saved to disk. + self.debug_file = debug_file + # HTTP proxy server address (without "http://") + self.proxy_host = proxy_host + # HTTP proxy port + self.proxy_port = proxy_port + # Management server's API version + self.api_version = api_version + # Indicates that the client should not check the server's certificate + self.unsafe = unsafe + # Indicates that the client should automatically accept and save the server's certificate + self.unsafe_auto_accept = unsafe_auto_accept + # The context of using the client - defaults to web_api + self.context = context + + +class APIClient: + """ + APIClient encapsulates everything that the user needs to do for communicating with a Check Point management server + """ + + def __init__(self, api_client_args=None): + """Constructor + :param api_client_args: APIClientArgs object containing arguments + """ + # if a client_args is not supplied, make a default one + if api_client_args is None: + api_client_args = APIClientArgs() + # port on management server + self.__port, self.__is_port_default = (api_client_args.port, False) if api_client_args.port else (443, True) + # management server fingerprint + self.fingerprint = api_client_args.fingerprint + # session-id. + self.sid = api_client_args.sid + # management server name or IP-address + self.server = api_client_args.server + # domain to log into in an MDS environment + self.domain = None + # debug level + self.http_debug_level = api_client_args.http_debug_level + # an array with all the api calls (for debug purposes) + self.api_calls = api_client_args.api_calls + # name of debug file. If left empty, debug data will not be saved to disk. + self.debug_file = api_client_args.debug_file + # HTTP proxy server address + self.proxy_host = api_client_args.proxy_host + # HTTP proxy port + self.proxy_port = api_client_args.proxy_port + # Management server's API version + self.api_version = api_client_args.api_version + # Indicates that the client should not check the server's certificate + self.unsafe = api_client_args.unsafe + # Indicates that the client should automatically accept and save the server's certificate + self.unsafe_auto_accept = api_client_args.unsafe_auto_accept + # The context of using the client - defaults to web_api + self.context = api_client_args.context + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + """destructor""" + # if sid is not empty (the login api was called), then call logout + if self.sid: + self.api_call("logout") + # save debug data with api calls to disk + self.save_debug_data() + + def get_port(self): + """returns the port of the API client (int)""" + return self.__port + + def is_port_default(self): + """returns whether the user changed the port (bool)""" + return self.__is_port_default + + def set_port(self, port): + self.__port = port + self.__is_port_default = False + + def save_debug_data(self): + """save debug data with api calls to disk""" + if self.debug_file: + print("\nSaving data to debug file {}\n".format(self.debug_file), file=sys.stderr) + out_file = open(self.debug_file, 'w+') + out_file.write(json.dumps(self.api_calls, indent=4, sort_keys=True)) + + def login(self, username, password, continue_last_session=False, domain=None, read_only=False, + payload=None): + """ + performs a 'login' API call to the management server + + :param username: Check Point admin name + :param password: Check Point admin password + :param continue_last_session: [optional] It is possible to continue the last Check Point session + or to create a new one + :param domain: [optional] The name, UID or IP-Address of the domain to login. + :param read_only: [optional] Login with Read Only permissions. This parameter is not considered in case + continue-last-session is true. + :param payload: [optional] More settings for the login command + :returns: APIResponse object + :side-effects: updates the class's uid and server variables + """ + credentials = {"user": username, "password": password} + + if self.context == "web_api": + credentials.update({"continue-last-session": continue_last_session, + "read-only": read_only}) + + if domain: + credentials.update({"domain": domain}) + if isinstance(payload, dict): + credentials.update(payload) + + login_res = self.api_call("login", credentials) + + if login_res.success: + self.sid = login_res.data["sid"] + self.domain = domain + if self.api_version is None: + self.api_version = login_res.data["api-server-version"] + return login_res + + def login_as_root(self, domain=None, payload=None): + """ + This method allows to login into the management server with root permissions. + In order to use this method the application should be run directly on the management server + and to have super-user privileges. + + :param domain: [optional] name/uid/IP address of the domain you want to log into in an MDS environment + :param payload: [optional] dict of additional parameters for the login command + :return: APIResponse object with the relevant details from the login command. + """ + python_absolute_path = os.path.expandvars("$MDS_FWDIR/Python/bin/python") + api_get_port_absolute_path = os.path.expandvars("$MDS_FWDIR/scripts/api_get_port.py") + mgmt_cli_absolute_path = os.path.expandvars("$CPDIR/bin/mgmt_cli") + + # try to get the management server's port by running a script + if not self.is_port_default(): + port = self.get_port() + else: + try: + port = compatible_loads(subprocess.check_output([python_absolute_path, + api_get_port_absolute_path, "-f", "json"]))["external_port"] + # if can't, default back to what the user wrote or the default (443) + except (ValueError, subprocess.CalledProcessError): + port = self.get_port() + + try: + # This simple dict->cli format works only because the login command doesn't require + # any complex parameters like objects and lists + new_payload = [] + if payload: + for key in payload.keys(): + new_payload += [key, payload[key]] + if domain: + new_payload += ["domain", domain] + login_response = compatible_loads(subprocess.check_output( + [mgmt_cli_absolute_path, "login", "-r", "true", "-f", "json", "--port", str(port)] + new_payload)) + self.sid = login_response["sid"] + self.server = "127.0.0.1" + self.domain = domain + if self.api_version is None: + self.api_version = login_response["api-server-version"] + return APIResponse(login_response, success=True) + except ValueError as err: + raise APIClientException( + "Could not load JSON from login as root command, perhaps no root privileges?\n" + str( + type(err)) + " - " + str(err)) + except (WindowsError, subprocess.CalledProcessError) as err: + raise APIClientException("Could not login as root:\n" + str(type(err)) + " - " + str(err)) + + def api_call(self, command, payload=None, sid=None, wait_for_task=True): + """ + performs a web-service API request to the management server + + :param command: the command is placed in the URL field + :param payload: a JSON object (or a string representing a JSON object) with the command arguments + :param sid: [optional]. The Check Point session-id. when omitted use self.sid. + :param wait_for_task: determines the behavior when the API server responds with a "task-id". + by default, the function will periodically check the status of the task + and will not return until the task is completed. + when wait_for_task=False, it is up to the user to call the "show-task" API and check + the status of the command. + :return: APIResponse object + :side-effects: updates the class's uid and server variables + """ + self.check_fingerprint() + if payload is None: + payload = {} + # Convert the json payload to a string if needed + if isinstance(payload, str): + _data = payload + elif isinstance(payload, dict): + _data = json.dumps(payload, sort_keys=False) + else: + raise TypeError('Invalid payload type - must be dict/string') + # update class members if needed. + if sid is None: + sid = self.sid + + # Set headers + _headers = { + "User-Agent": "python-api-wrapper", + "Accept": "*/*", + "Content-Type": "application/json", + "Content-Length": len(_data) + } + + # In all API calls (except for 'login') a header containing the Check Point session-id is required. + if sid is not None: + _headers["X-chkp-sid"] = sid + + # Create ssl context with no ssl verification, we do it by ourselves + context = ssl.create_default_context() + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + + # create https connection + if self.proxy_host and self.proxy_port: + conn = HTTPSConnection(self.proxy_host, self.proxy_port, context=context) + conn.set_tunnel(self.server, self.get_port()) + else: + conn = HTTPSConnection(self.server, self.get_port(), context=context) + + # Set fingerprint + conn.fingerprint = self.fingerprint + + # Set debug level + conn.set_debuglevel(self.http_debug_level) + url = "/" + self.context + "/" + (("v" + str(self.api_version) + "/") if self.api_version else "") + command + response = None + try: + # Send the data to the server + conn.request("POST", url, _data, _headers) + # Get the reply from the server + response = conn.getresponse() + res = APIResponse.from_http_response(response) + except ValueError as err: + if err.args[0] == "Fingerprint value mismatch": + err_message = "Error: Fingerprint value mismatch:\n" + " Expecting : {}\n".format( + err.args[1]) + " Got: {}\n".format( + err.args[2]) + "If you trust the new fingerprint, edit the 'fingerprints.txt' file." + res = APIResponse("", False, err_message=err_message) + else: + res = APIResponse("", False, err_message=err) + except Exception as err: + res = APIResponse("", False, err_message=err) + + if response: + res.status_code = response.status + + # When the command is 'login' we'd like to convert the password to "****" so that it + # would not appear as plaintext in the debug file. + if command == "login": + json_data = compatible_loads(_data) + json_data["password"] = "****" + _data = json.dumps(json_data) + + # Store the request and the reply (for debug purpose). + _api_log = { + "request": { + "url": url, + "payload": compatible_loads(_data), + "headers": _headers + }, + "response": res.response() + } + self.api_calls.append(_api_log) + + # If we want to wait for the task to end, wait for it + if wait_for_task is True and res.success and command != "show-task": + if "task-id" in res.data: + res = self.__wait_for_task(res.data["task-id"]) + elif "tasks" in res.data: + res = self.__wait_for_tasks(res.data["tasks"]) + + return res + + def api_query(self, command, details_level="standard", container_key="objects", include_container_key=False, + payload=None): + """ + The APIs that return a list of objects are limited by the number of objects that they return. + To get the full list of objects, there's a need to make repeated API calls each time using a different offset + until all the objects are returned. + This API makes such repeated API calls and return the full list objects. + note: this function calls gen_api_query and iterates over the generator until it gets all the objects, + then returns. + + :param command: name of API command. This command should be an API that returns an array of + objects (for example: show-hosts, show networks, ...) + :param details_level: query APIs always take a details-level argument. + possible values are "standard", "full", "uid" + :param container_key: name of the key that holds the objects in the JSON response (usually "objects"). + :param include_container_key: If set to False the 'data' field of the APIResponse object + will be a list of the wanted objects. + Otherwise, the date field of the APIResponse will be a dictionary in the following + format: { container_key: [ List of the wanted objects], "total": size of the list} + :param payload: a JSON object (or a string representing a JSON object) with the command arguments + :return: if include-container-key is False: + an APIResponse object whose .data member contains a list of the objects requested: [ , , , ...] + if include-container-key is True: + an APIResponse object whose .data member contains a dict: { container_key: [...], "total": n } + """ + api_res = None + for api_res in self.gen_api_query(command, details_level, [container_key], payload=payload): + pass + if api_res and api_res.success and container_key in api_res.data and include_container_key is False: + api_res.data = api_res.data[container_key] + return api_res + + def gen_api_query(self, command, details_level="standard", container_keys=None, payload=None): + """ + This is a generator function that yields the list of wanted objects received so far from the management server. + This is in contrast to normal API calls that return only a limited number of objects. + This function can be used to show progress when requesting many objects (i.e. "Received x/y objects.") + + :param command: name of API command. This command should be an API that returns an array of objects + (for example: show-hosts, show networks, ...) + :param details_level: query APIs always take a details-level argument. Possible values are "standard", "full", "uid" + :param container_keys: the field in the .data dict that contains the objects + :param payload: a JSON object (or a string representing a JSON object) with the command arguments + :yields: an APIResponse object as detailed above + """ + + finished = False # will become true after getting all the data + all_objects = {} # accumulate all the objects from all the API calls + + # default + if container_keys is None: + container_keys = ["objects"] + + # if given a string, make it a list + if sys.version_info >= (3, 0): + if isinstance(container_keys, (str, str)): + container_keys = [container_keys] + else: + if isinstance(container_keys, (str, unicode)): + container_keys = [container_keys] + + for key in container_keys: + all_objects[key] = [] + iterations = 0 # number of times we've made an API call + limit = 50 # page size to get for each api call + if payload is None: + payload = {} + else: + limit = int(payload.get("limit", limit)) + + payload.update({"limit": limit, "offset": iterations * limit, "details-level": details_level}) + api_res = self.api_call(command, payload) + for container_key in container_keys: + if not api_res.data or container_key not in api_res.data or not isinstance(api_res.data[container_key], list) \ + or "total" not in api_res.data or api_res.data["total"] == 0: + finished = True + yield api_res + break + + # are we done? + while not finished: + # make the API call, offset should be increased by 'limit' with each iteration + if api_res.success is False: + raise APIException(api_res.error_message, api_res.data) + + total_objects = api_res.data["total"] # total number of objects + received_objects = api_res.data["to"] # number of objects we got so far + for container_key in container_keys: + all_objects[container_key] += api_res.data[container_key] + api_res.data[container_key] = all_objects[container_key] + # yield the current result + yield api_res + # did we get all the objects that we're supposed to get + if received_objects == total_objects: + break + + iterations += 1 + payload.update({"limit": limit, "offset": iterations * limit, "details-level": details_level}) + api_res = self.api_call(command, payload) + + def get_server_fingerprint(self): + """ + Initiates an HTTPS connection to the server and extracts the SHA1 fingerprint from the server's certificate. + :return: string with SHA1 fingerprint (all uppercase letters) + """ + context = ssl.create_default_context() + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + + if self.proxy_host and self.proxy_port: + conn = HTTPSConnection(self.proxy_host, self.proxy_port, context=context) + conn.set_tunnel(self.server, self.get_port()) + else: + conn = HTTPSConnection(self.server, self.get_port(), context=context) + + return conn.get_fingerprint_hash() + + def __wait_for_task(self, task_id): + """ + When the server needs to perform an API call that may take a long time (e.g. run-script, install-policy, + publish), the server responds with a 'task-id'. + Using the show-task API it is possible to check on the status of this task until its completion. + Every two seconds, this function will check for the status of the task. + The function will return when the task (and its sub-tasks) are no longer in-progress. + + :param task_id: The task identifier. + :return: APIResponse object (response of show-task command). + :raises APIException + """ + task_complete = False + task_result = None + in_progress = "in progress" + + # As long as there is a task in progress + while not task_complete: + # Check the status of the task + task_result = self.api_call("show-task", {"task-id": task_id, "details-level": "full"}, self.sid, False) + + attempts_counter = 0 + while task_result.success is False: + if attempts_counter < 5: + attempts_counter += 1 + time.sleep(2) + task_result = self.api_call("show-task", {"task-id": task_id, "details-level": "full"}, + self.sid, False) + else: + raise APIException( + "ERROR: Failed to handle asynchronous tasks as synchronous, tasks result is undefined", + task_result) + + # Count the number of tasks that are not in-progress + completed_tasks = sum(1 for task in task_result.data["tasks"] if task["status"] != in_progress) + + # Get the total number of tasks + total_tasks = len(task_result.data["tasks"]) + + # Are we done? + if completed_tasks == total_tasks: + task_complete = True + else: + time.sleep(2) # Wait for two seconds + + self.check_tasks_status(task_result) + return task_result + + def __wait_for_tasks(self, task_objects): + """ + The version of __wait_for_task function for the collection of tasks + + :param task_objects: A list of task objects + :return: APIResponse object (response of show-task command). + """ + + # A list of task ids to be retrieved + tasks = [] + for task_obj in task_objects: + # Retrieve the taskId and wait for the task to be completed + task_id = task_obj["task-id"] + tasks.append(task_id) + self.__wait_for_task(task_id) + + task_result = self.api_call("show-task", {"task-id": tasks, "details-level": "full"}, + self.sid, False) + + APIClient.check_tasks_status(task_result) + return task_result + + @staticmethod + def check_tasks_status(task_result): + """ + This method checks if one of the tasks failed and if so, changes the response status to be False + + :param task_result: api_response returned from "show-task" command + :return: + """ + for task in task_result.data["tasks"]: + if task["status"] == "failed" or task["status"] == "partially succeeded": + task_result.set_success_status(False) + break + + def check_fingerprint(self): + """ + This function checks if the server's certificate is stored in the local fingerprints file. + If the server's fingerprint is not found, an HTTPS connection is made to the server + and the user is asked if he or she accepts the server's fingerprint. + If the fingerprint is trusted, it is stored in the fingerprint file. + + :return: False if the user does not accept the server certificate, True in all other cases. + """ + if self.unsafe: + return True + # Read the fingerprint from the local file + local_fingerprint = self.read_fingerprint_from_file(self.server) + server_fingerprint = self.get_server_fingerprint() + + #Check if fingerprint is passed and matches + if self.fingerprint == server_fingerprint: + return True + + # If the fingerprint is not stored in the local file + if local_fingerprint == "" or \ + local_fingerprint.replace(':', '').upper() != server_fingerprint.replace(':', '').upper(): + # Get the server's fingerprint with a socket. + if server_fingerprint == "": + return False + + if self.unsafe_auto_accept: + self.save_fingerprint_to_file(self.server, server_fingerprint) + return True + + if local_fingerprint == "": + print("You currently do not have a record of this server's fingerprint.", file=sys.stderr) + else: + print( + "The server's fingerprint is different from your local record of this server's fingerprint.\n" + "You maybe a victim to a Man-in-the-Middle attack, please beware.", file=sys.stderr) + print("Server's fingerprint: {}".format(server_fingerprint), file=sys.stderr) + + if self.ask_yes_no_question("Do you accept this fingerprint?"): + if self.save_fingerprint_to_file(self.server, server_fingerprint): + print("Fingerprint saved.", file=sys.stderr) + else: + print("Could not save fingerprint to file. Continuing anyway.", file=sys.stderr) + else: + return False + + self.fingerprint = server_fingerprint # set the actual fingerprint in the class instance + return True + + @staticmethod + def ask_yes_no_question(question): + """ + helper function. Present a question to the user with Y/N options. + + :param question: The question to display to the user + :return: 'True' if the user typed 'Y'. 'False' is the user typed 'N' + """ + if sys.version_info >= (3, 0): + answer = input(question + " [y/n] ") + else: + answer = raw_input(question + " [y/n] ") + if answer.lower() == "y" or answer.lower() == "yes": + return True + else: + return False + + @staticmethod + def save_fingerprint_to_file(server, fingerprint, filename="fingerprints.txt"): + """ + store a server's fingerprint into a local file. + + :param server: the IP address/name of the Check Point management server. + :param fingerprint: A SHA1 fingerprint of the server's certificate. + :param filename: The file in which to store the certificates. The file will hold a JSON structure in which + the key is the server and the value is its fingerprint. + :return: 'True' if everything went well. 'False' if there was some kind of error storing the fingerprint. + """ + if not fingerprint: + return False + + if os.path.isfile(filename): + try: + with open(filename) as f: + json_dict = json.load(f) + except ValueError as e: + if e.message == "No JSON object could be decoded": + print("Corrupt JSON file: " + filename, file=sys.stderr) + else: + print(e.message, file=sys.stderr) + return False + except IOError as e: + print("Couldn't open file: " + filename + "\n" + e.message, file=sys.stderr) + return False + except Exception as e: + print(e, file=sys.stderr) + return False + else: + if server in json_dict and json_dict[server] == fingerprint: + return True + else: + json_dict[server] = fingerprint + else: + json_dict = {server: fingerprint} + + try: + with open(filename, 'w') as filedump: + json.dump(json_dict, filedump, indent=4, sort_keys=True) + filedump.close() + return True + except IOError as e: + print("Couldn't open file: " + filename + " for writing.\n" + e.message, file=sys.stderr) + except Exception as e: + print(e, file=sys.stderr) + return False + + @staticmethod + def read_fingerprint_from_file(server, filename="fingerprints.txt"): + """ + reads a server's fingerprint from a local file. + + :param server: the IP address/name of the Check Point management server. + :param filename: The file in which to store the certificates. The file will hold a JSON structure in which + the key is the server and the value is its fingerprint. + :return: A SHA1 fingerprint of the server's certificate. + """ + if sys.version_info >= (3, 0): + assert isinstance(server, (str, str)) + else: + assert isinstance(server, (str, unicode)) + + if os.path.isfile(filename): + try: + with open(filename) as f: + json_dict = json.load(f) + except ValueError as e: + if e.message == "No JSON object could be decoded": + print("Corrupt JSON file: " + filename, file=sys.stderr) + else: + print(e.message, file=sys.stderr) + except IOError as e: + print("Couldn't open file: " + filename + "\n" + e.message, file=sys.stderr) + except Exception as e: + print(e, file=sys.stderr) + else: + # file is ok and readable. + if server in json_dict: + return json_dict[server] + return "" + + +class HTTPSConnection(http_client.HTTPSConnection): + """ + A class for making HTTPS connections that overrides the default HTTPS checks (e.g. not accepting + self-signed-certificates) and replaces them with a server fingerprint check. + """ + + def connect(self): + http_client.HTTPConnection.connect(self) + self.sock = ssl.wrap_socket(self.sock, self.key_file, self.cert_file, cert_reqs=ssl.CERT_NONE) + + def get_fingerprint_hash(self): + try: + http_client.HTTPConnection.connect(self) + self.sock = ssl.wrap_socket(self.sock, self.key_file, self.cert_file, cert_reqs=ssl.CERT_NONE) + except Exception: + return "" + fingerprint = hashlib.new("SHA1", self.sock.getpeercert(True)).hexdigest() + return fingerprint.upper() diff --git a/SmartMove/SmartConnector/cpapi/utils.py b/SmartMove/SmartConnector/cpapi/utils.py new file mode 100644 index 00000000..640e73bb --- /dev/null +++ b/SmartMove/SmartConnector/cpapi/utils.py @@ -0,0 +1,13 @@ +import json +import sys + + +def compatible_loads(json_data): + """ + Function json.loads in python 3.0 - 3.5 can't handle bytes, so this function handle it. + :param json_data: + :return: unicode (str if it's python 3) + """ + if isinstance(json_data, bytes) and (3, 0) <= sys.version_info < (3, 6): + json_data = json_data.decode("utf-8") + return json.loads(json_data) diff --git a/SmartMove/SmartConnector/smartconnector.py b/SmartMove/SmartConnector/smartconnector.py new file mode 100644 index 00000000..02396be9 --- /dev/null +++ b/SmartMove/SmartConnector/smartconnector.py @@ -0,0 +1,1244 @@ +#!/usr/bin/env python + +import sys +import argparse +import json +import os + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))) +from cpapi import APIClient, APIClientArgs + + +# printing messages to console and log file +# res_action - response from server, used if response is not OK +# message - message to inform user +# error - message with mark to inform user about issue +# --- +# returns: nothing +def printStatus(res_action, message, error=None): + line = "" + if res_action is not None and res_action.success is False: + if 'errors' in res_action.data: + for msg_err in res_action.data['errors']: + line += "WARN:" + "\t" + msg_err['message'] + "\n" + if 'warnings' in res_action.data: + for msg_wrn in res_action.data['warnings']: + line += "WARN:" + "\t" + msg_wrn['message'] + "\n" + if line == "": + line = "WARN:" + "\t" + res_action.data['message'] + "\n" + elif message is not None: + line += "\t" + message + "\n" + elif error is not None: + line += "WARN:" + "\t" + error + "\n" + if line != "": + print(line.rstrip()) + file_log.write(line) + file_log.flush() + + +# printing info message "process..." with delimeters +# objectsType - string of objects type +# --- +# returns: nothing +def printMessageProcessObjects(objectsType): + printStatus(None, "==========") + printStatus(None, "process " + objectsType + " ...") + printStatus(None, "") + + +# publishing to database new updates by condition; increasing counter by 1 +# counter - is number of new updates. if it equals threshold then updates will be published +# isForced - publishing to database anyway +# --- +# returns: updated counter +def publishUpdate(counter, isForced): + if counter < 0: + counter = 0 + counter += 1 + if isForced or counter >= args.threshold: + if not isForced: + printStatus(None, "") + printStatus(None, "----------") + printStatus(None, "publishing to database...") + res_publish = client.api_call("publish", {}) + if res_publish.success: + counter = 0 + printStatus(res_publish, "publish is completed") + printStatus(None, "----------") + if isForced: + printStatus(None, "") + return counter + + +# check if response contains message that name of "new" object exists in database +# res_add_obj - response from server +# --- +# returns: True - if the name is duplicated, False - otherwise +def isNameDuplicated(res_add_obj): + isNameDuplicated = False + if 'errors' in res_add_obj.data: + for msg in res_add_obj.data['errors']: + if msg['message'].startswith("More than one object named") and msg['message'].endswith("exists."): + isNameDuplicated = True + return isNameDuplicated + + +# check if response contains message that IP of "new" object exists in database +# res_add_obj - response from server +# --- +# returns: True - if the IP is duplicated, False - otherwise +def isIpDuplicated(res_add_obj): + isIpDuplicated = False + if 'warnings' in res_add_obj.data: + messagePrefixes = ("Multiple objects have the same IP address",) + messagePrefixes += ("More than one network have the same IP",) + messagePrefixes += ("More than one network has the same IP",) + for msg in res_add_obj.data['warnings']: + if msg['message'].startswith(messagePrefixes): + isIpDuplicated = True + return isIpDuplicated + + +# check if object from server comes from "global" domain +# serverObject - JSON presentation of object +# --- +# returns: True - if object comes from "global" domain, False - otherwise +def isServerObjectGlobal(serverObject): + return serverObject['domain']['domain-type'] == "global domain" + + +# check if object from server comes from "local" domain +# serverObject - JSON presentation of object +# --- +# returns: True - if object comes from "local" domain, False - otherwise +def isServerObjectLocal(serverObject): + return serverObject['domain']['domain-type'] == "domain" + + +# adding "new" object to server +# adjusting the name if object with the name exists at server: _ +# client - client object +# apiCommand - short string which indicates what should be done +# payload - JSON representation of "new" object +# userObjectNamePostfix - postfix as number +# changeName=True - True: to try to add object and adjust the name; False: to try to add object and NOT adjust the name +# --- +# returns: added object from server in JSON format, None - otherwise +def addUserObjectToServer(client, apiCommand, payload, userObjectNamePostfix=1, changeName=True): + isObjectAdded = False + userObjectNameInitial = "" + if changeName: + userObjectNameInitial = payload['name'] + addedObject = None + while not isObjectAdded: + res_add_obj = client.api_call(apiCommand, payload) + printStatus(res_add_obj, None) + if res_add_obj.success is False: + if not changeName: + break + if isNameDuplicated(res_add_obj): + payload['name'] = userObjectNameInitial + '_' + str(userObjectNamePostfix) + userObjectNamePostfix += 1 + else: + break + else: + addedObject = res_add_obj.data + isObjectAdded = True + return addedObject + + +# adding to server the object which contains fields with IP: hosts, networks +# adjusting the name if object with the name exists at server: _ +# using the object from server side if object exsits with the same IP at server +# client - client object +# payload - JSON representation of "new" object +# userObjectType - the type of object: host or network +# userObjectIp - IP which will be used as filter in request to server +# mergedObjectsNamesMap - the map which contains name of user's object (key) and name of resulting object (value) +# --- +# returns: updated mergedObjectsNamesMap +def addCpObjectWithIpToServer(client, payload, userObjectType, userObjectIp, mergedObjectsNamesMap): + printStatus(None, "processing " + userObjectType + ": " + payload['name']) + userObjectNameInitial = payload['name'] + userObjectNamePostfix = 1 + isFinished = False + isIgnoreWarnings = False + while not isFinished: + payload["ignore-warnings"] = isIgnoreWarnings + res_add_obj_with_ip = client.api_call("add-" + userObjectType, payload) + printStatus(res_add_obj_with_ip, "REPORT: " + userObjectNameInitial + " is added as " + payload['name']) + if res_add_obj_with_ip.success is False: + if isIpDuplicated(res_add_obj_with_ip) and not isIgnoreWarnings: + res_get_obj_with_ip = client.api_query("show-objects", payload={"filter": userObjectIp, "ip-only": True, + "type": userObjectType}) + printStatus(res_get_obj_with_ip, None) + if res_get_obj_with_ip.success is True: + if len(res_get_obj_with_ip.data) > 0: + for serverObject in res_get_obj_with_ip.data: + if isServerObjectLocal(serverObject) and not isReplaceFromGlobalFirst: + mergedObjectsNamesMap[userObjectNameInitial] = serverObject['name'] + break + if isServerObjectGlobal(serverObject) and isReplaceFromGlobalFirst: + mergedObjectsNamesMap[userObjectNameInitial] = serverObject['name'] + break + mergedObjectsNamesMap[userObjectNameInitial] = serverObject['name'] + printStatus(None, "REPORT: " + "CP object " + mergedObjectsNamesMap[ + userObjectNameInitial] + " is used instead of " + userObjectNameInitial) + isFinished = True + else: + isIgnoreWarnings = True + else: + isFinished = True + elif isNameDuplicated(res_add_obj_with_ip): + payload['name'] = userObjectNameInitial + '_' + str(userObjectNamePostfix) + userObjectNamePostfix += 1 + else: + isFinished = True + else: + mergedObjectsNamesMap[userObjectNameInitial] = payload['name'] + isFinished = True + return mergedObjectsNamesMap + + +# processing and adding to server the groups which contains list of members +# adjusting the name if group with the name exists at server: _ +# client - client object +# apiCommand - short string which indicates what should be done +# userGroup - group which will be processed and added to server +# mergedObjectsMap - map of objects which will be used for replacing +# mergedGroupsNamesMap - the map which contains name of user's object (key) and name of resulting object (value) +# --- +# returns: updated mergedGroupsNamesMap +def processGroupWithMembers(client, apiCommand, userGroup, mergedObjectsMap, mergedGroupsNamesMap): + for i, userGroupMember in enumerate(userGroup['Members']): + if userGroupMember in mergedObjectsMap: + userGroup['Members'][i] = mergedObjectsMap[userGroupMember] + elif userGroupMember in mergedGroupsNamesMap: + userGroup['Members'][i] = mergedGroupsNamesMap[userGroupMember] + addedGroup = addUserObjectToServer( + client, + apiCommand, + { + "name": userGroup['Name'], + "members": userGroup['Members'], + "comments": userGroup['Comments'], + "tags": userGroup['Tags'] + } + ) + return addedGroup + + +# processing and adding to server the CheckPoint Domains +# adjusting the name if domain with the name exists at server: _ +# client - client object +# userDomains - the list of domains which will be processed and added to server +# --- +# returns: mergedDomainsNamesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processDomains(client, userDomains): + printMessageProcessObjects("domains...") + publishCounter = 0 + mergedDomainsNamesMap = {} + if len(userDomains) == 0: + return mergedDomainsNamesMap + for userDomain in userDomains: + userDomainNameInitial = userDomain['Name'] + printStatus(None, "processing domain: " + userDomain['Name']) + addedDomain = addUserObjectToServer( + client, + "add-dns-domain", + { + "name": userDomain['Name'], + "is-sub-domain": userDomain['IsSubDomain'], + "comments": userDomain['Comments'], + "tags": userDomain['Tags'] + } + ) + if addedDomain is not None: + mergedDomainsNamesMap[userDomainNameInitial] = addedDomain['name'] + printStatus(None, "REPORT: " + userDomainNameInitial + " is added as " + addedDomain['name']) + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: " + userDomainNameInitial + ' is not added.') + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedDomainsNamesMap + + +# processing and adding to server the CheckPoint Hosts +# adjusting the name if host with the name exists at server: _ +# if host contains existing IP address then Host object from server will be used instead +# client - client object +# userHosts - the list of hosts which will be processed and added to server +# --- +# returns: mergedHostsNamesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processHosts(client, userHosts): + printMessageProcessObjects("hosts") + publishCounter = 0 + mergedHostsNamesMap = {} + if len(userHosts) == 0: + return mergedHostsNamesMap + for userHost in userHosts: + payload = { + "name": userHost['Name'], + "ip-address": userHost['IpAddress'], + "comments": userHost['Comments'], + "tags": userHost['Tags'] + } + initialMapLength = len(mergedHostsNamesMap) + mergedHostsNamesMap = addCpObjectWithIpToServer(client, payload, "host", userHost['IpAddress'], + mergedHostsNamesMap) + if initialMapLength == len(mergedHostsNamesMap): + printStatus(None, "REPORT: " + userHost['Name'] + ' is not added.') + else: + publishCounter = publishUpdate(publishCounter, False) + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedHostsNamesMap + + +# processing and adding to server the CheckPoint Networks +# adjusting the name if network with the name exists at server: _ +# if network contains existing IP subnet then Network object from server will be used instead +# client - client object +# userNetworks - the list of networks which will be processed and added to server +# --- +# returns: mergedNetworksNamesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processNetworks(client, userNetworks): + printMessageProcessObjects("networks") + publishCounter = 0 + mergedNetworksNamesMap = {} + if len(userNetworks) == 0: + return mergedNetworksNamesMap + for userNetwork in userNetworks: + payload = { + "name": userNetwork['Name'], + "subnet4": userNetwork['Subnet'], + "subnet-mask": userNetwork['Netmask'], + "comments": userNetwork['Comments'], + "tags": userNetwork['Tags'] + } + initialMapLength = len(mergedNetworksNamesMap) + mergedNetworksNamesMap = addCpObjectWithIpToServer(client, payload, "network", userNetwork['Subnet'], + mergedNetworksNamesMap) + if initialMapLength == len(mergedNetworksNamesMap): + printStatus(None, "REPORT: " + userNetwork['Name'] + ' is not added.') + else: + publishCounter = publishUpdate(publishCounter, False) + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedNetworksNamesMap + + +# processing and adding to server the CheckPoint Ranges +# adjusting the name if range with the name exists at server: _ +# if range contains existing IP start and end then Range object from server will be used instead +# client - client object +# userRanges - the list of ranges which will be processed and added to server +# --- +# returns: mergedRangesNamesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processRanges(client, userRanges): + printMessageProcessObjects("ranges") + publishCounter = 0 + mergedRangesNamesMap = {} + if len(userRanges) == 0: + return mergedRangesNamesMap + serverRangesMap = {} + serverRangesMapGlobal = {} + serverRangesMapLocal = {} + printStatus(None, "reading address ranges from server") + res_get_ranges = client.api_query("show-address-ranges") + printStatus(res_get_ranges, None) + for serverRange in res_get_ranges.data: + key = serverRange['ipv4-address-first'] + '_' + serverRange['ipv4-address-last'] + if isServerObjectGlobal(serverRange) and key not in serverRangesMapGlobal: + serverRangesMapGlobal[key] = serverRange['name'] + elif isServerObjectLocal(serverRange) and key not in serverRangesMapLocal: + serverRangesMapLocal[key] = serverRange['name'] + elif key not in serverRangesMapGlobal and key not in serverRangesMapLocal and key not in serverRangesMap: + serverRangesMap[key] = serverRange['name'] + printStatus(None, "") + if sys.version_info >= (3, 0): + serverRangesMap = serverRangesMap.copy() + if isReplaceFromGlobalFirst: + serverRangesMap.update(serverRangesMapLocal) + serverRangesMap.update(serverRangesMapGlobal) + else: + serverRangesMap.update(serverRangesMapGlobal) + serverRangesMap.update(serverRangesMapLocal) + else: + if isReplaceFromGlobalFirst: + serverRangesMap = dict( + serverRangesMap.items() + serverRangesMapLocal.items() + serverRangesMapGlobal.items()) + else: + serverRangesMap = dict( + serverRangesMap.items() + serverRangesMapGlobal.items() + serverRangesMapLocal.items()) + for userRange in userRanges: + printStatus(None, "processing range: " + userRange['Name']) + userRangeNameInitial = userRange['Name'] + key = userRange['RangeFrom'] + '_' + userRange['RangeTo'] + if key in serverRangesMap: + printStatus(None, None, + "More than one range has the same ip: '" + userRange['RangeFrom'] + "' and '" + userRange[ + 'RangeTo'] + "'") + mergedRangesNamesMap[userRangeNameInitial] = serverRangesMap[key] + printStatus(None, "REPORT: " + "CP object " + mergedRangesNamesMap[ + userRangeNameInitial] + " is used instead of " + userRangeNameInitial) + else: + userRangeNamePostfix = 1 + if userRange['Name'] in serverRangesMap.values(): + printStatus(None, None, "More than one object named '" + userRange['Name'] + "' exists.") + while userRange['Name'] in serverRangesMap.values(): + userRange['Name'] = userRangeNameInitial + '_' + str(userRangeNamePostfix) + userRangeNamePostfix += 1 + payload = { + "name": userRange['Name'], + "ip-address-first": userRange['RangeFrom'], + "ip-address-last": userRange['RangeTo'], + "comments": userRange['Comments'], + "tags": userRange['Tags'], + "ignore-warnings": True + } + addedRange = addUserObjectToServer(client, "add-address-range", payload, userRangeNamePostfix) + if addedRange is not None: + mergedRangesNamesMap[userRangeNameInitial] = addedRange['name'] + key = addedRange['ipv4-address-first'] + '_' + addedRange['ipv4-address-last'] + serverRangesMap[key] = addedRange['name'] + printStatus(None, "REPORT: " + userRangeNameInitial + " is added as " + addedRange['name']) + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: " + userRangeNameInitial + ' is not added.') + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedRangesNamesMap + + +# processing and adding to server the CheckPoint Network Groups +# adjusting the name if network group with the name exists at server: _ +# client - client object +# userNetworkGroups - the list of network groups which will be processed and added to server +# mergedNetworkObjectsMap - map of network objects which will be used for replacing +# --- +# returns: mergedGroupsNamesDict dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processNetGroups(client, userNetworkGroups, mergedNetworkObjectsMap): + printMessageProcessObjects("network groups") + publishCounter = 0 + mergedGroupsNamesDict = {} + if len(userNetworkGroups) == 0: + return mergedGroupsNamesDict + for userNetworkGroup in userNetworkGroups: + userNetworkGroupNameInitial = userNetworkGroup['Name'] + addedNetworkGroup = None + if userNetworkGroup['TypeName'] == 'CheckPoint_GroupWithExclusion': + printStatus(None, "processing network group with exclusion: " + userNetworkGroup['Name']) + if userNetworkGroup['Include'] in mergedGroupsNamesDict: + userNetworkGroup['Include'] = mergedGroupsNamesDict[userNetworkGroup['Include']] + if userNetworkGroup['Except'] in mergedGroupsNamesDict: + userNetworkGroup['Except'] = mergedGroupsNamesDict[userNetworkGroup['Except']] + addedNetworkGroup = addUserObjectToServer( + client, + "add-group-with-exclusion", + { + "name": userNetworkGroup['Name'], + "include": userNetworkGroup['Include'], + "except": userNetworkGroup['Except'], + "comments": userNetworkGroup['Comments'], + "tags": userNetworkGroup['Tags'] + } + ) + else: + printStatus(None, "processing network group: " + userNetworkGroup['Name']) + addedNetworkGroup = processGroupWithMembers(client, "add-group", userNetworkGroup, mergedNetworkObjectsMap, + mergedGroupsNamesDict) + if addedNetworkGroup is not None: + mergedGroupsNamesDict[userNetworkGroupNameInitial] = addedNetworkGroup['name'] + printStatus(None, "REPORT: " + userNetworkGroupNameInitial + " is added as " + addedNetworkGroup['name']) + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: " + userNetworkGroupNameInitial + " is not added.") + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedGroupsNamesDict + + +# processing and adding to server the CheckPoint Simple Gateways +# adjusting the name if simple gateway with the name exists at server: _ +# client - client object +# userSimpleGateways - the list of simple gateways which will be processed and added to server +# --- +# returns: mergedSimpleGatewaysNamesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processSimpleGateways(client, userSimpleGateways): + printMessageProcessObjects("simple gateways") + publishCounter = 0 + mergedSimpleGatewaysNamesMap = {} + if len(userSimpleGateways) == 0: + return mergedSimpleGatewaysNamesMap + for userSimpleGateway in userSimpleGateways: + printStatus(None, "processing simple getway: " + userSimpleGateway['Name']) + userSimpleGatewayNameInitial = userSimpleGateway['Name'] + addedSimpleGateway = addUserObjectToServer( + client, + "add-simple-gateway", + { + "name": userSimpleGateway['Name'], + "ip-address": userSimpleGateway['IpAddress'], + "comments": userSimpleGateway['Comments'], + "tags": userSimpleGateway['Tags'] + } + ) + if addedSimpleGateway is not None: + mergedSimpleGatewaysNamesMap[userSimpleGatewayNameInitial] = addedSimpleGateway['name'] + printStatus(None, "REPORT: " + userSimpleGatewayNameInitial + " is added as " + addedSimpleGateway['name']) + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: " + userSimpleGatewayNameInitial + ' is not added.') + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedSimpleGatewaysNamesMap + + +# processing and adding to server the CheckPoint Zones +# adjusting the name if zone with the name exists at server: _ +# client - client object +# userZones - the list of zones which will be processed and added to server +# --- +# returns: mergedZonesNamesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processZones(client, userZones): + printMessageProcessObjects("zones") + publishCounter = 0 + mergedZonesNamesMap = {} + if len(userZones) == 0: + return mergedZonesNamesMap + for userZone in userZones: + printStatus(None, "processing zone: " + userZone['Name']) + userZoneNameInitial = userZone['Name'] + addedZone = addUserObjectToServer( + client, + "add-security-zone", + { + "name": userZone['Name'], + "comments": userZone['Comments'], + "tags": userZone['Tags'] + } + ) + if addedZone is not None: + mergedZonesNamesMap[userZoneNameInitial] = addedZone['name'] + printStatus(None, "REPORT: " + userZoneNameInitial + " is added as " + addedZone['name']) + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: " + userZoneNameInitial + ' is not added.') + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedZonesNamesMap + + +# generate and provide key for Services dictionary +# serverService - service in JSON format +# --- +# returns: string as key +def provideServerServiceKey(serverService): + key = "" + if 'port' in serverService: # key for TCP or UDP or SCTP + key = serverService['port'] + elif 'icmp-type' in serverService: # key for ICMP + key = str(serverService['icmp-type']) + if 'icmp-code' in serverService and serverService['icmp-code'] != 'null': + key += "_" + str(serverService['icmp-code']) + elif 'ip-protocol' in serverService: # key for Other + key = serverService['ip-protocol'] + return key + + +# processing and adding to server the CheckPoint Services (TCP, UDP, SCTP, ICMP or Other) +# adjusting the name if service with the name exists at server: _ +# if service contains existing port then Service object from server will be used instead +# client - client object +# userServices - the list of services which will be processed and added to server +# userServiceType - the type of service which should be processed +# --- +# returns: mergedServicesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processServices(client, userServices, userServiceType): + printMessageProcessObjects(userServiceType + " services") + publishCounter = 0 + mergedServicesMap = {} + serverServicesMap = {} + serverServicesMapGlobal = {} + serverServicesMapLocal = {} + printStatus(None, "reading " + userServiceType + " services from server") + res_get_services = client.api_query("show-services-" + userServiceType) + printStatus(res_get_services, None) + for serverService in res_get_services.data: + mergedServicesMap[serverService['name']] = serverService['uid'] + key = provideServerServiceKey(serverService) + isServiceReplacing = False + if 'port' in serverService and ('protocol' not in serverService or serverService['protocol'] == 'null'): + isServiceReplacing = True + if isServerObjectGlobal(serverService) and (key not in serverServicesMapGlobal or isServiceReplacing): + serverServicesMapGlobal[key] = (serverService['name'], serverService['uid']) + elif isServerObjectLocal(serverService) and (key not in serverServicesMapLocal or isServiceReplacing): + serverServicesMapLocal[key] = (serverService['name'], serverService['uid']) + elif not isServerObjectGlobal(serverService) and not isServerObjectLocal(serverService) and ( + key not in serverServicesMap or isServiceReplacing): + serverServicesMap[key] = (serverService['name'], serverService['uid']) + printStatus(None, "") + if sys.version_info >= (3, 0): + serverServicesMap = serverServicesMap.copy() + if isReplaceFromGlobalFirst: + serverServicesMap.update(serverServicesMapLocal) + serverServicesMap.update(serverServicesMapGlobal) + else: + serverServicesMap.update(serverServicesMapGlobal) + serverServicesMap.update(serverServicesMapLocal) + else: + if isReplaceFromGlobalFirst: + serverServicesMap = dict( + serverServicesMap.items() + serverServicesMapLocal.items() + serverServicesMapGlobal.items()) + else: + serverServicesMap = dict( + serverServicesMap.items() + serverServicesMapGlobal.items() + serverServicesMapLocal.items()) + if len(userServices) == 0: + return mergedServicesMap + for userService in userServices: + printStatus(None, "processing " + userServiceType + " service: " + userService['Name']) + userServiceNameInitial = userService['Name'] + key = "" + duplicationValueMessagePostfix = "" + if 'Port' in userService: + key = userService['Port'] + duplicationValueMessagePostfix = "port: " + userService['Port'] + elif 'Type' in userService: + key = userService['Type'] + duplicationValueMessagePostfix = "type: " + userService['Type'] + if 'Code' in userService and userService['Code'] != 'null': + key += "_" + userService['Code'] + duplicationValueMessagePostfix = "type / code: " + userService['Type'] + " / " + userService['Code'] + elif 'IpProtocol' in userService: + key = userService['IpProtocol'] + duplicationValueMessagePostfix = "ip-protocol: " + userService['IpProtocol'] + if key in serverServicesMap: + printStatus(None, None, + "More than one " + userServiceType + " service has the same " + duplicationValueMessagePostfix) + mergedServicesMap[userServiceNameInitial] = serverServicesMap[key][1] + printStatus(None, "REPORT: " + "CP object " + serverServicesMap[key][ + 0] + " is used instead of " + userServiceNameInitial) + else: + userServiceNamePostfix = 1 + serverServicesNames = [serverServiceNameUid[0] for serverServiceNameUid in serverServicesMap.values()] + if userService['Name'] in serverServicesNames: + printStatus(None, None, "More than one object named '" + userService['Name'] + "' exists.") + while userService['Name'] in serverServicesNames: + userService['Name'] = userServiceNameInitial + '_' + str(userServiceNamePostfix) + userServiceNamePostfix += 1 + payload = {} + payload["name"] = userService['Name'] + payload["comments"] = userService['Comments'] + payload["tags"] = userService['Tags'] + payload["ignore-warnings"] = True + if 'Port' in userService: + payload["port"] = userService['Port'] + payload["source-port"] = userService['SourcePort'] + payload["session-timeout"] = userService['SessionTimeout'] + elif 'Type' in userService: + payload["icmp-type"] = userService['Type'] + if 'Code' in userService and userService['Code'] != 'null': + payload["icmp-code"] = userService['Code'] + elif 'IpProtocol' in userService: + payload["ip-protocol"] = userService['IpProtocol'] + payload["match-for-any"] = True + addedService = addUserObjectToServer(client, "add-service-" + userServiceType, payload, + userServiceNamePostfix) + if addedService is not None: + mergedServicesMap[userServiceNameInitial] = addedService['uid'] + key = provideServerServiceKey(addedService) + serverServicesMap[key] = (addedService['name'], addedService['uid']) + printStatus(None, "REPORT: " + userServiceNameInitial + " is added as " + addedService['name']) + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: " + userServiceNameInitial + ' is not added.') + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedServicesMap + + +# processing and adding to server the CheckPoint Service Groups +# adjusting the name if service group with the name exists at server: _ +# client - client object +# userServicesGroups - the list of service groups which will be processed and added to server +# mergedServicesMap - map of service objects which will be used for replacing +# --- +# returns: mergedServicesGroupsNamesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processServicesGroups(client, userServicesGroups, mergedServicesMap): + printMessageProcessObjects("services groups") + publishCounter = 0 + mergedServicesGroupsNamesMap = {} + if len(userServicesGroups) == 0: + return mergedServicesGroupsNamesMap + for userServicesGroup in userServicesGroups: + printStatus(None, "processing services group: " + userServicesGroup['Name']) + userServicesGroupNameInitial = userServicesGroup['Name'] + addedServicesGroup = processGroupWithMembers(client, "add-service-group", userServicesGroup, mergedServicesMap, + mergedServicesGroupsNamesMap) + if addedServicesGroup is not None: + mergedServicesGroupsNamesMap[userServicesGroupNameInitial] = addedServicesGroup['name'] + printStatus(None, "REPORT: " + userServicesGroupNameInitial + " is added as " + addedServicesGroup['name']) + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: " + userServicesGroupNameInitial + " is not added.") + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedServicesGroupsNamesMap + + +# processing and adding to server the CheckPoint Time Groups +# adjusting the name if time group with the name exists at server: _ +# client - client object +# userTimesGroups - the list of time groups which will be processed and added to server +# --- +# returns: mergedTimesGroupsNamesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processTimesGroups(client, userTimesGroups): + printMessageProcessObjects("times groups") + publishCounter = 0 + mergedTimesGroupsNamesMap = {} + if len(userTimesGroups) == 0: + return mergedTimesGroupsNamesMap + for userTimesGroup in userTimesGroups: + printStatus(None, "processing times group: " + userTimesGroup['Name']) + userTimesGroupNameInitial = userTimesGroup['Name'] + addedTimesGroup = addUserObjectToServer( + client, + "add-time-group", + { + "name": userTimesGroup['Name'], + "members": userTimesGroup['Members'], + "comments": userTimesGroup['Comments'], + "tags": userTimesGroup['Tags'] + } + ) + if addedTimesGroup is not None: + mergedTimesGroupsNamesMap[userTimesGroupNameInitial] = addedTimesGroup['name'] + printStatus(None, "REPORT: " + userTimesGroupNameInitial + " is added as " + addedTimesGroup['name']) + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: " + userTimesGroupNameInitial + ' is not added.') + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedTimesGroupsNamesMap + + +# processing and adding to server the CheckPoint Time objects +# adjusting the name if time object with the name exists at server: _ +# client - client object +# userTimes - the list of time objects which will be processed and added to server +# --- +# returns: mergedTimesNamesMap dictionary +# the map contains name of user's object (key) and name of resulting object (value) +def processTimes(client, userTimes): + printMessageProcessObjects("times") + publishCounter = 0 + mergedTimesNamesMap = {} + payload = {} + if len(userTimes) == 0: + return mergedTimesNamesMap + weekdays = {0: "Sun", 1: "Mon", 2: "Tue", 3: "Wed", 4: "Thu", 5: "Fri", 6: "Sat"} + for userTime in userTimes: + printStatus(None, "processing time: " + userTime['Name']) + userTimeNameInitial = userTime['Name'] + + payload["name"] = userTime['Name'] + payload["comments"] = userTime['Comments'] + + payload["start-now"] = userTime['StartNow'] + payload["start"] = { + "date": userTime['StartDate'], + "time": userTime['StartTime'] + } + + payload["end-never"] = userTime['EndNever'] + payload["end"] = { + "date": userTime['EndDate'], + "time": userTime['EndTime'] + } + + payload["hours-ranges"] = [ + { + "enabled": userTime['HoursRangesEnabled_1'], + "from": userTime['HoursRangesFrom_1'] if userTime['HoursRangesFrom_1'] is not None else "00:00", + "to": userTime['HoursRangesTo_1'] if userTime['HoursRangesTo_1'] is not None else "00:00", + "index": 1 + }, + { + "enabled": userTime['HoursRangesEnabled_2'], + "from": userTime['HoursRangesFrom_2'] if userTime['HoursRangesFrom_2'] is not None else "00:00", + "to": userTime['HoursRangesTo_2'] if userTime['HoursRangesTo_2'] is not None else "00:00", + "index": 2 + }, + { + "enabled": userTime['HoursRangesEnabled_3'], + "from": userTime['HoursRangesFrom_3'] if userTime['HoursRangesFrom_3'] is not None else "00:00", + "to": userTime['HoursRangesTo_3'] if userTime['HoursRangesTo_3'] is not None else "00:00", + "index": 3 + } + ] + + daysNames = [] # list of weekdays names e.g. "Sun", "Mon"... + # weekdays are presented as [1,2,3.. ] in userTime['RecurrenceWeekdays'] + for day in userTime['RecurrenceWeekdays']: + daysNames.append(weekdays[day]) + + payload["recurrence"] = { + "pattern": "Daily" if userTime['RecurrencePattern'] == 1 else ( + "Weekly" if userTime['RecurrencePattern'] == 2 else ( + "Monthly" if userTime['RecurrencePattern'] == 3 else None)), + "weekdays": daysNames + } + + payload["tags"] = userTime['Tags'] + + addedTime = addUserObjectToServer( + client, + "add-time", + payload + ) + + if addedTime is not None: + mergedTimesNamesMap[userTimeNameInitial] = addedTime['name'] + printStatus(None, "REPORT: " + userTimeNameInitial + " is added as " + addedTime['name']) + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: " + userTimeNameInitial + ' is not added.') + printStatus(None, "") + publishUpdate(publishCounter, True) + return mergedTimesNamesMap + + +# processing and adding to server the CheckPoint Access Rules +# the rules is added in back order: the last item of list goes first and the first item goes last +# client - client object +# userRules - the list of access rules which will be processed and added to server +# userLayerName - the name of layer where access rules will be added +# skipCleanUpRule - the flag which indicates to exclude "Clean up" rule from layer or not; "Clean up" rule is the last rule in the layer always +# mergedNetworkObjectsMap - map of all network objects (groups is included) which will be used for replacing +# mergedServiceObjectsMap - map of all services objects (groups is included) which will be used for replacing +# mergedTimesGroupsNamesMap - map of time groups objects which will be used for replacing +# --- +# returns: nothing +def addAccessRules(client, userRules, userLayerName, skipCleanUpRule, mergedNetworkObjectsMap, mergedServiceObjectsMap, + mergedTimesGroupsNamesMap, mergedTimesNamesMap): + if userRules is not None: + publishCounter = 0 + printStatus(None, "processing access rules to " + userLayerName + " layer") + printStatus(None, "") + userRulesStartPosition = -2 if skipCleanUpRule else -1 + # userRules[userRulesStartPosition::-1]: + # -1 - minus means to iterate backwards, 1 means step + # userRulesStartPosition - start point, length of list "- userRulesStartPosition" because reverse mode is specified + # end point is not specified - all elements + for i, userRule in enumerate(userRules[userRulesStartPosition::-1]): + printStatus(None, "processing access rule: #" + str(len(userRules) - i) + ", " + ( + userRule['Name'] if userRule['Name'] is not None else "")) + # JSON access rules contain "action" as number + # "action" number points to the next list of values from SmartMove: + # 0 = Accept + # 1 = Drop + # 2 = Reject + # 3 = SubPolicy + actions = {0: "accept", 1: "drop", 2: "reject", 3: "apply layer"} + sources = [] + for source in userRule['Source']: + sourceName = source['Name'] + sourceName = mergedNetworkObjectsMap[ + sourceName] if sourceName in mergedNetworkObjectsMap else sourceName + sources.append(sourceName) + destinations = [] + for destination in userRule['Destination']: + destinationName = destination['Name'] + destinationName = mergedNetworkObjectsMap[ + destinationName] if destinationName in mergedNetworkObjectsMap else destinationName + destinations.append(destinationName) + services = [] + for service in userRule['Service']: + serviceName = service['Name'] + serviceName = mergedServiceObjectsMap[ + serviceName] if serviceName in mergedServiceObjectsMap else serviceName + services.append(serviceName) + times = [] + for time in userRule['Time']: + timeName = time['Name'] + + # support of time-ranges along with time-groups is added + if timeName in mergedTimesGroupsNamesMap: + timeName = mergedTimesGroupsNamesMap[timeName] + elif timeName in mergedTimesNamesMap: + timeName = mergedTimesNamesMap[timeName] + else: + timeName = timeName + # timeName = mergedTimesGroupsNamesMap[timeName] if timeName in mergedTimesGroupsNamesMap else timeName + + times.append(timeName) + payload = { + "layer": userRule['Layer'], + "position": "top", + "name": userRule['Name'], + "action": actions[userRule['Action']], + "destination": destinations, + "destination-negate": userRule['DestinationNegated'], + "enabled": userRule['Enabled'], + "service": services, + "source": sources, + "source-negate": userRule['SourceNegated'], + "time": times, + "track": {"type": "None" if userRule['Track'] == 0 else "Log"}, + "comments": userRule['Comments'] + } + if userRule['Action'] == 3: + payload["inline-layer"] = userRule['SubPolicyName'] + if userRule['ConversionComments'].strip() != "": + payload["custom-fields"] = {"field-1": userRule['ConversionComments']} + addedRule = addUserObjectToServer(client, "add-access-rule", payload, changeName=False) + if addedRule is not None: + printStatus(None, "REPORT: access rule is added") + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: access rule is not added") + printStatus(None, "") + publishUpdate(publishCounter, True) + + +# processing and adding to server the CheckPoint Package with Layers and Access Rules +# client - client object +# userPackage - the package which contains layers and access rules +# mergedNetworkObjectsMap - map of all network objects (groups is included) which will be used for replacing +# mergedServiceObjectsMap - map of all services objects (groups is included) which will be used for replacing +# mergedTimesGroupsNamesMap - map of time groups objects which will be used for replacing +# --- +# returns: added package in JSON format +def processPackage(client, userPackage, mergedNetworkObjectsMap, mergedServiceObjectsMap, mergedTimesGroupsNamesMap, + mergedTimesNamesMap): + printMessageProcessObjects("package") + addedPackage = None + if userPackage is not None: + publishCounter = 0 + printStatus(None, "processing package: " + userPackage['Name']) + addedPackage = addUserObjectToServer( + client, + "add-package", + { + "name": userPackage['Name'], + "threat-prevention": False, + "tags": userPackage['Tags'] + }, + changeName=False + ) + if addedPackage is None: + printStatus(None, "REPORT: " + userPackage['Name'] + " package is not added") + return addedPackage + printStatus(None, "REPORT: " + userPackage['Name'] + " package is added") + printStatus(None, "") + publishCounter = publishUpdate(publishCounter, True) + if userPackage['SubPolicies'] is not None: + for userSubLayer in userPackage['SubPolicies']: + printStatus(None, "processing access layer: " + userSubLayer['Name']) + addedSubLayer = addUserObjectToServer( + client, + "add-access-layer", + { + "name": userSubLayer['Name'], + "add-default-rule": False, + "applications-and-url-filtering": userSubLayer['ApplicationsAndUrlFiltering'], + "comments": userSubLayer['Comments'], + "tags": userSubLayer['Tags'] + }, + changeName=False + ) + if addedSubLayer is None: + printStatus(None, "REPORT: " + userSubLayer['Name'] + " layer is not added") + continue + printStatus(None, "REPORT: " + userSubLayer['Name'] + " layer is added") + printStatus(None, "") + publishCounter = publishUpdate(publishCounter, True) + addAccessRules(client, userSubLayer['Rules'], userSubLayer['Name'], False, mergedNetworkObjectsMap, + mergedServiceObjectsMap, mergedTimesGroupsNamesMap, mergedTimesNamesMap) + if userPackage['ParentLayer'] is not None: + addAccessRules(client, userPackage['ParentLayer']['Rules'], "parent", True, mergedNetworkObjectsMap, + mergedServiceObjectsMap, mergedTimesGroupsNamesMap, mergedTimesNamesMap) + return addedPackage + + +# processing and adding to server the CheckPoint NAT rules +# NAT rules are added if package has been added +# client - client object +# addedPackage - added package in JSON format +# userNatRules - the list of NAT rules which will be processed and added to server +# mergedNetworkObjectsMap - map of all network objects (groups is included) which will be used for replacing +# mergedServiceObjectsMap - map of all services objects (groups is included) which will be used for replacing +# --- +# returns: nothing +def processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, mergedServiceObjectsMap): + printMessageProcessObjects("nat rules") + if addedPackage is None: + printStatus(None, "REPORT: nat rules can not been added because package was not added") + return + publishCounter = 0 + for i, userNatRule in enumerate(userNatRules): + printStatus(None, "processing nat rule: #" + str(i)) + sourceOrig = "" + if userNatRule['Source'] is not None: + sourceOrig = userNatRule['Source']['Name'] + sourceOrig = mergedNetworkObjectsMap[sourceOrig] if sourceOrig in mergedNetworkObjectsMap else sourceOrig + destinationOrig = "" + if userNatRule['Destination'] is not None: + destinationOrig = userNatRule['Destination']['Name'] + destinationOrig = mergedNetworkObjectsMap[ + destinationOrig] if destinationOrig in mergedNetworkObjectsMap else destinationOrig + serviceOrig = "" + if userNatRule['Service'] is not None: + serviceOrig = userNatRule['Service']['Name'] + serviceOrig = mergedServiceObjectsMap[ + serviceOrig] if serviceOrig in mergedServiceObjectsMap else serviceOrig + sourceTrans = "" + if userNatRule['TranslatedSource'] is not None: + sourceTrans = userNatRule['TranslatedSource']['Name'] + sourceTrans = mergedNetworkObjectsMap[ + sourceTrans] if sourceTrans in mergedNetworkObjectsMap else sourceTrans + destinationTrans = "" + if userNatRule['TranslatedDestination'] is not None: + destinationTrans = userNatRule['TranslatedDestination']['Name'] + destinationTrans = mergedNetworkObjectsMap[ + destinationTrans] if destinationTrans in mergedNetworkObjectsMap else destinationTrans + serviceTrans = "" + if userNatRule['TranslatedService'] is not None: + serviceTrans = userNatRule['TranslatedService']['Name'] + serviceTrans = mergedServiceObjectsMap[ + serviceTrans] if serviceTrans in mergedServiceObjectsMap else serviceTrans + payload = { + "package": userNatRule['Package'], + "position": "bottom", + "comments": userNatRule['Comments'], + "enabled": userNatRule['Enabled'], + "method": "static" if userNatRule['Method'] == 0 else "hide", + "original-source": sourceOrig, + "original-destination": destinationOrig, + "original-service": serviceOrig, + "translated-source": sourceTrans, + "translated-destination": destinationTrans, + "translated-service": serviceTrans + } + addedNatRule = addUserObjectToServer(client, "add-nat-rule", payload, changeName=False) + if addedNatRule is not None: + printStatus(None, "REPORT: nat rule is added") + publishCounter = publishUpdate(publishCounter, False) + else: + printStatus(None, "REPORT: nat rule is not added") + printStatus(None, "") + publishCounter = publishUpdate(publishCounter, True) + + +# START + +args_parser = argparse.ArgumentParser() + +args_parser._optionals.title = "arguments" + +args_parser.add_argument('-r', '--root', action="store_true", + help="If administrator logged into the management server and wants to receive SuperUser permissions, 'login-as-root' feature might be used. " + + "In this case providing additional login credentials is not required.") +args_parser.add_argument('-m', '--management', default='127.0.0.1', + help="Management server IP address or name. Default: 127.0.0.1") +args_parser.add_argument('--port', type=int, + help="Server port. Default: 443") +args_parser.add_argument('-u', '--user', + help="User name") +args_parser.add_argument('-p', '--password', + help="User password") +args_parser.add_argument('-f', '--file', default='cp_objects.json', + help="JSON file with CheckPoint Objects. Default: cp_objects.json") +args_parser.add_argument('-t', '--threshold', type=int, default=100, + help="Parameter specifies maximum number of Check Point objects/rules to add before starting publish operation. Default: 100") +args_parser.add_argument('-d', '--domain', default=None, + help="The name/uid of the domain you want to log into in an MDS environment.") +args_parser.add_argument('--replace-from-global-first', default="false", + help="The argument indicates that SmartConnector should use 'Global' objects at first, by default it uses 'Local' objects. [true, false]") + +args = args_parser.parse_args() + +file_name_log = "smartconnector" +if args.file != "cp_objects.json": + file_name_log += "_" + os.path.splitext(args.file)[0] +file_name_log += ".log" +if os.path.exists(file_name_log): + os.remove(file_name_log) +file_log = open(file_name_log, "w+") + +if not args.root and args.user is None: + print("") + printStatus(None, None, "No user or root option is specified.") + print("") + args_parser.print_help() +elif args.root and args.user is not None: + print("") + printStatus(None, None, "Command contains ambiguous parameters. User is unexpected when logging in as root.") + print("") + args_parser.print_help() +elif args.root and args.management != '127.0.0.1': + print("") + printStatus(None, None, "Command contains ambiguous parameters. Management is unexpected when logging in as root.") + print("") + args_parser.print_help() +elif not args.root and args.password is None: + print("") + printStatus(None, None, "No password option is specified.") + print("") + args_parser.print_help() +elif not os.path.isfile(args.file): + print("") + printStatus(None, None, "The file does not exists") + print("") + args_parser.print_help() +elif args.replace_from_global_first.lower() != "true" and args.replace_from_global_first.lower() != "false": + print("") + printStatus(None, None, + "smartconnector.py: error: argument --replace-from-global-first: invalid boolean value: '" + args.replace_from_global_first + "'") + print("") + args_parser.print_help() +else: + if args.replace_from_global_first.lower() == "true": + isReplaceFromGlobalFirst = True + elif args.replace_from_global_first.lower() == "false": + isReplaceFromGlobalFirst = False + printStatus(None, "Input arguments:") + printStatus(None, "root flag is set" if args.root else "root flag is not set") + printStatus(None, "management: " + args.management) + printStatus(None, + "port: " + str(args.port) if args.port is not None else "port: is not set, default value will be used") + printStatus(None, "domain: " + args.domain if args.domain is not None else "domain: is not set") + printStatus(None, "user: " + args.user if args.user is not None else "user: is not set") + printStatus(None, "password: ***" if args.password is not None else "password: is not set") + printStatus(None, "file: " + args.file) + printStatus(None, "threshold: " + str(args.threshold)) + printStatus(None, "replace-from-global-first: " + str(isReplaceFromGlobalFirst)) + printStatus(None, "===========================================") + printStatus(None, "reading and parsing processes are started for JSON file: " + args.file) + with open(args.file) as json_file: + json_data = json.load(json_file) + # define lists of CheckPoint Objects + userDomains = [] + userHosts = [] + userNetworks = [] + userRanges = [] + userNetGroups = [] + userSimpleGateways = [] + userZones = [] + userServicesTcp = [] + userServicesUdp = [] + userServicesSctp = [] # is not used in Cisco + userServicesIcmp = [] # is not used in Cisco + userServicesOther = [] + userServicesGroups = [] + userTimesGroups = [] + userTimes = [] + userPackage = None + userNatRules = [] + for jsonObject in json_data: + if jsonObject is None or 'TypeName' not in jsonObject: + continue + if jsonObject['TypeName'] == 'CheckPoint_Domain': + userDomains.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_Host': + userHosts.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_Network': + userNetworks.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_Range': + userRanges.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_NetworkGroup' or jsonObject[ + 'TypeName'] == 'CheckPoint_GroupWithExclusion': + userNetGroups.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_SimpleGateway': + userSimpleGateways.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_Zone': + userZones.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_TcpService': + userServicesTcp.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_UdpService': + userServicesUdp.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_SctpService': + userServicesSctp.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_IcmpService': + userServicesIcmp.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_OtherService': + userServicesOther.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_ServiceGroup': + userServicesGroups.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_TimeGroup': + userTimesGroups.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_Time': + userTimes.append(jsonObject) + if jsonObject['TypeName'] == 'CheckPoint_Package': + userPackage = jsonObject + if jsonObject['TypeName'] == 'CheckPoint_NAT_Rule': + userNatRules.append(jsonObject) + + printStatus(None, "reading and parsing processes are completed for JSON file: " + args.file) + client_args = None + if args.port is not None: + client_args = APIClientArgs(server=args.management, port=args.port) + else: + client_args = APIClientArgs(server=args.management) + with APIClient(client_args) as client: + client.debug_file = "api_calls.json" + printStatus(None, "checking fingerprint") + if client.check_fingerprint() is False: + printStatus(None, "Could not get the server's fingerprint - Check connectivity with the server.") + else: + if args.root: + msg = "login as root to " + if args.domain is not None: + msg += args.domain + " domain of local server" + else: + msg += "local server" + printStatus(None, msg) + login_res = client.login_as_root(domain=args.domain) + else: + msg = "login as " + args.user + " to " + if args.domain is not None: + msg += args.domain + " domain of " + args.management + " server" + else: + msg += args.management + " server" + printStatus(None, msg) + login_res = client.login(args.user, args.password, domain=args.domain) + if login_res.success is False: + printStatus(None, "Login failed: {}".format(login_res.error_message)) + else: + printStatus(None, "") + mergedNetworkObjectsMap = {} + mergedNetworkObjectsMap.update(processDomains(client, userDomains)) + mergedNetworkObjectsMap.update(processHosts(client, userHosts)) + mergedNetworkObjectsMap.update(processNetworks(client, userNetworks)) + mergedNetworkObjectsMap.update(processRanges(client, userRanges)) + mergedNetworkObjectsMap.update(processNetGroups(client, userNetGroups, mergedNetworkObjectsMap)) + mergedNetworkObjectsMap.update(processSimpleGateways(client, userSimpleGateways)) + mergedNetworkObjectsMap.update(processZones(client, userZones)) + mergedServicesObjectsMap = {} + mergedServicesObjectsMap.update(processServices(client, userServicesTcp, "tcp")) + mergedServicesObjectsMap.update(processServices(client, userServicesUdp, "udp")) + mergedServicesObjectsMap.update(processServices(client, userServicesSctp, "sctp")) + mergedServicesObjectsMap.update(processServices(client, userServicesIcmp, "icmp")) + mergedServicesObjectsMap.update(processServices(client, userServicesOther, "other")) + mergedServicesObjectsMap.update( + processServicesGroups(client, userServicesGroups, mergedServicesObjectsMap)) + mergedTimesGroupsMap = processTimesGroups(client, userTimesGroups) + mergedTimesMap = processTimes(client, userTimes) + addedPackage = processPackage(client, userPackage, mergedNetworkObjectsMap, mergedServicesObjectsMap, + mergedTimesGroupsMap, mergedTimesMap) + processNatRules(client, addedPackage, userNatRules, mergedNetworkObjectsMap, mergedServicesObjectsMap) + printStatus(None, "==========") +file_log.close() +# END diff --git a/SmartMove/SmartMove.csproj b/SmartMove/SmartMove.csproj index d3e724dd..8b7dbdf7 100644 --- a/SmartMove/SmartMove.csproj +++ b/SmartMove/SmartMove.csproj @@ -5,7 +5,7 @@ Debug AnyCPU {CF7E7724-6EBF-4A54-B27C-FD56877A8FF4} - WinExe + Exe Properties SmartMove SmartMove @@ -13,6 +13,21 @@ 512 {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 4 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true AnyCPU @@ -36,11 +51,23 @@ Resources\Conversion_Icon.ico + + SmartMove.Program + + + ..\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 + - + @@ -58,6 +85,8 @@ MSBuild:Compile Designer + + Designer @@ -114,7 +143,7 @@ ResXFileCodeGenerator Resources.Designer.cs - + SettingsSingleFileGenerator Settings.Designer.cs @@ -175,6 +204,21 @@ PreserveNewest + + + False + .NET Framework 3.5 SP1 + false + + + + + PreserveNewest + + + PreserveNewest + +