コード例 #1
0
        public FirewallRule Clone()
        {
            FirewallRule rule = new FirewallRule(mID);

            rule.Name        = Name;
            rule.Grouping    = Grouping;
            rule.Description = Description;

            rule.Enabled   = Enabled;
            rule.Action    = Action;
            rule.Direction = Direction;
            rule.Profile   = Profile;

            rule.Protocol          = Protocol;
            rule.Interface         = Interface;
            rule.LocalPorts        = LocalPorts;
            rule.LocalAddresses    = LocalAddresses;
            rule.RemoteAddresses   = RemoteAddresses;
            rule.RemotePorts       = RemotePorts;
            rule.IcmpTypesAndCodes = IcmpTypesAndCodes;

            rule.EdgeTraversal = EdgeTraversal;

            rule.Expiration = Expiration;

            return(rule);
        }
コード例 #2
0
        public bool RemoveRule(FirewallRule rule)
        {
            NetFwRule FwRule;

            if (!Rules.TryGetValue(rule.guid, out FwRule))
            {
                return(true); // tne rule is already gone
            }
            try
            {
                // Note: if this is not set to null renam may fail as well as other sets :/
                FwRule.Entry.EdgeTraversalOptions = (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY;

                // Note: the removal is done byname, howeever multiple rules may have the same name, WTF, so we set a temporary unique name
                FwRule.Entry.Name = "***_to_be_deleted_***"; // todo add rand string

                NetFwPolicy.Rules.Remove(FwRule.Entry.Name);

                Rules.Remove(rule.guid);
            }
            catch (Exception err)
            {
                Priv10Logger.LogError("Failed to Remove rule: " + err.Message);
                return(false);
            }
            return(true);
        }
コード例 #3
0
        public FirewallRule Duplicate()
        {
            FirewallRule rule = new FirewallRule();

            rule.Assign(this);
            return(rule);
        }
コード例 #4
0
        public List <FirewallRule> LoadRules()
        {
            RuleCounter = 0;
            Rules.Clear();

            List <FirewallRule> rules = new List <FirewallRule>();

            try
            {
                int Count = NetFwPolicy.Rules.Count;
                foreach (INetFwRule2 entry in NetFwPolicy.Rules)
                {
                    FirewallRule rule = new FirewallRule();
                    if (LoadRule(rule, entry))
                    {
                        rule.Index = Count - ++RuleCounter;
                        rule.guid  = Guid.NewGuid().ToString("B");
                        Rules.Add(rule.guid, new NetFwRule()
                        {
                            Entry = entry, Rule = rule
                        });
                        rules.Add(rule);
                    }
                }
            }
            catch // firewall service is deisabled :/
            {
                return(null);
            }
            return(rules);
        }
コード例 #5
0
        public void Assign(FirewallRule rule)
        {
            this.guid  = rule.guid;
            this.Index = rule.Index;

            this.BinaryPath = rule.BinaryPath;
            this.ServiceTag = rule.ServiceTag;
            this.AppSID     = rule.AppSID;
            this.ProgID     = rule.ProgID;

            this.Name        = rule.Name;
            this.Grouping    = rule.Grouping;
            this.Description = rule.Description;

            this.Enabled = rule.Enabled;

            this.Action    = rule.Action;
            this.Direction = rule.Direction;
            this.Profile   = rule.Profile;

            this.Protocol          = rule.Protocol;
            this.Interface         = rule.Interface;
            this.LocalPorts        = rule.LocalPorts;
            this.LocalAddresses    = rule.LocalAddresses;
            this.RemoteAddresses   = rule.RemoteAddresses;
            this.RemotePorts       = rule.RemotePorts;
            this.IcmpTypesAndCodes = rule.IcmpTypesAndCodes;

            this.EdgeTraversal = rule.EdgeTraversal;

            // todo: xxx
        }
コード例 #6
0
        public bool RemoveRule(FirewallRule rule, bool silent = false)
        {
            INetFwRule2 entry;

            if (!mAllRules.TryGetValue(rule.guid, out entry))
            {
                return(true); // tne rule is already gone
            }
            if (!RemoveRule(entry))
            {
                return(false);
            }

            var prog = App.engine.programs.GetProgram(rule.mID);

            if (prog != null)
            {
                prog.Rules.Remove(rule.guid);

                if (!silent)
                {
                    App.engine.NotifyChange(prog);
                }
            }

            return(true);
        }
コード例 #7
0
        public FirewallRule.Actions LookupRuleAction(FirewallEvent FwEvent, NetworkMonitor.AdapterInfo NicInfo)
        {
            int BlockRules = 0;
            int AllowRules = 0;

            foreach (FirewallRule rule in Rules.Values)
            {
                if (!rule.Enabled)
                {
                    continue;
                }
                if (rule.Direction != FwEvent.Direction)
                {
                    continue;
                }
                if (rule.Protocol != (int)NetFunc.KnownProtocols.Any && FwEvent.Protocol != rule.Protocol)
                {
                    continue;
                }
                if (((int)NicInfo.Profile & rule.Profile) == 0)
                {
                    continue;
                }
                if (rule.Interface != (int)FirewallRule.Interfaces.All && (int)NicInfo.Type != rule.Interface)
                {
                    continue;
                }
                if (!FirewallRule.MatchEndpoint(rule.RemoteAddresses, rule.RemotePorts, FwEvent.RemoteAddress, FwEvent.RemotePort, NicInfo))
                {
                    continue;
                }
                if (!FirewallRule.MatchEndpoint(rule.LocalAddresses, rule.LocalPorts, FwEvent.RemoteAddress, FwEvent.RemotePort, NicInfo))
                {
                    continue;
                }

                if (rule.Action == FirewallRule.Actions.Allow)
                {
                    AllowRules++;
                }
                else if (rule.Action == FirewallRule.Actions.Block)
                {
                    BlockRules++;
                }
            }

            // Note: block rules take precedence
            if (BlockRules > 0)
            {
                return(FirewallRule.Actions.Block);
            }
            if (AllowRules > 0)
            {
                return(FirewallRule.Actions.Allow);
            }
            return(FirewallRule.Actions.Undefined);
        }
コード例 #8
0
        public bool UpdateRule(FirewallRule rule, UInt64 expiration = 0)
        {
            List <byte[]> args = new List <byte[]>();

            args.Add(PutRule(rule));
            args.Add(PutUInt64(expiration));
            List <byte[]> ret = RemoteExec("UpdateRule", args);

            return(ret != null?GetBool(ret[0]) : false);
        }
コード例 #9
0
        public bool RemoveRule(FirewallRule rule)
        {
            List <byte[]> args = new List <byte[]>();

            args.Add(PutStr(rule.guid));
            args.Add(PutProgID(rule.ProgID)); // we tell the progid so that we dont need to check all programs
            List <byte[]> ret = RemoteExec("RemoveRule", args);

            return(ret != null?GetBool(ret[0]) : false);
        }
コード例 #10
0
        public bool LoadRules(bool CleanUp = false)
        {
            if (App.engine.appMgr != null)
            {
                App.engine.appMgr.LoadApps();
            }

            foreach (Program prog in App.engine.programs.Progs.Values)
            {
                prog.Rules.Clear();
            }
            mAllRules.Clear();

            List <INetFwRule2> entries = new List <INetFwRule2>();

            try
            {
                foreach (INetFwRule2 entry in mFirewallPolicy.Rules)
                {
                    entries.Add(entry);
                }
            }
            catch // firewall service is deisabled :/
            {
                return(false);
            }

            foreach (INetFwRule2 entry in entries)
            {
                if (CleanUp && entry.Name.Contains(FirewallRule.TempRulePrefix))
                {
                    AppLog.Line("Cleaning Up temporary rule: {0}", entry.Name);
                    RemoveRule(entry);
                    continue;
                }

                FirewallRule rule = new FirewallRule();
                if (FirewallRule.LoadRule(rule, entry))
                {
                    mAllRules.Add(rule.guid, entry);

                    Program process = App.engine.programs.GetProgram(rule.mID, true);
                    process.Rules.Add(rule.guid, rule);
                }
            }

            foreach (Program prog in App.engine.programs.Progs.Values)
            {
                EvaluateRules(prog, false);
            }

            App.engine.NotifyChange(null);

            return(true);
        }
コード例 #11
0
        public int SetRuleApproval(Priv10Engine.ApprovalMode Mode, FirewallRule rule)
        {
            List <byte[]> args = new List <byte[]>();

            args.Add(PutStr(Mode));
            args.Add(PutStr(rule != null ? rule.guid : null));      // null means all rules
            args.Add(PutProgID(rule != null ? rule.ProgID : null)); // we tell the progid so that we dont need to check all programs
            List <byte[]> ret = RemoteExec("SetRuleApproval", args);

            return(ret != null?GetInt(ret[0]) : 0);
        }
コード例 #12
0
ファイル: FirewallManager.cs プロジェクト: CazDev/priv10
 public static bool MatchEndpoint(string Addresses, string Ports, IPAddress Address, UInt16 Port, NetworkMonitor.AdapterInfo NicInfo = null)
 {
     if (!FirewallRule.IsEmptyOrStar(Ports) && !MatchPort(Port, Ports))
     {
         return(false);
     }
     if (Address != null && !FirewallRule.IsEmptyOrStar(Addresses) && !MatchAddress(Address, Addresses, NicInfo))
     {
         return(false);
     }
     return(true);
 }
コード例 #13
0
        public static FirewallRule MakeBlockRule(ProgramList.ID id, Firewall.Directions direction, long expiration = 0)
        {
            FirewallRule rule = new FirewallRule(id);

            rule.Name       = MakeRuleName(BlockAllName, expiration != 0);
            rule.Grouping   = RuleGroup;
            rule.Action     = Firewall.Actions.Block;
            rule.Direction  = direction;
            rule.Enabled    = true;
            rule.Expiration = expiration;
            return(rule);
        }
コード例 #14
0
        public static FirewallRule MakeBlockInetRule(ProgramList.ID id, Firewall.Directions direction, long expiration = 0)
        {
            FirewallRule rule = new FirewallRule(id);

            rule.Name            = MakeRuleName(BlockInet, expiration != 0);
            rule.Grouping        = RuleGroup;
            rule.Action          = Firewall.Actions.Block;
            rule.Direction       = direction;
            rule.Enabled         = true;
            rule.RemoteAddresses = NetFunc.GetNonLocalNet();
            rule.Expiration      = expiration;
            return(rule);
        }
コード例 #15
0
        public static FirewallRule MakeAllowLanRule(ProgramList.ID id, Firewall.Directions direction, long expiration = 0)
        {
            FirewallRule rule = new FirewallRule(id);

            rule.Name            = MakeRuleName(AllowLan, expiration != 0);
            rule.Grouping        = RuleGroup;
            rule.Action          = Firewall.Actions.Allow;
            rule.Direction       = direction;
            rule.Enabled         = true;
            rule.RemoteAddresses = "LocalSubnet";
            rule.Expiration      = expiration;
            return(rule);
        }
コード例 #16
0
        public FirewallRuleEx(FirewallRuleEx other, FirewallRule rule)
        {
            this.State = other.State;

            //this.Changed = other.Changed;
            this.LastChangedTime = other.LastChangedTime;
            this.ChangedCount    = other.ChangedCount;

            this.Expiration = other.Expiration;

            this.Backup = other.Backup;

            this.Assign(rule);
        }
コード例 #17
0
        public bool UpdateRule(FirewallRule rule, bool silent = false)
        {
            bool bAdd = (rule.guid == Guid.Empty);

            try
            {
                INetFwRule2 entry;
                if (bAdd)
                {
                    entry = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                }
                else if (!mAllRules.TryGetValue(rule.guid, out entry))
                {
                    AppLog.Line("Failed Updating rule: ruls is not longer present");
                    return(false);
                }

                if (!FirewallRule.SaveRule(rule, entry))
                {
                    return(false);
                }

                Program prog = App.engine.programs.GetProgram(rule.mID, true);
                if (bAdd)
                {
                    mFirewallPolicy.Rules.Add(entry);

                    rule.guid = Guid.NewGuid();
                    mAllRules.Add(rule.guid, entry);
                }
                else
                {
                    prog.Rules.Remove(rule.guid);
                }
                prog.Rules.Add(rule.guid, rule);

                if (!silent)
                {
                    App.engine.NotifyChange(prog);
                }
            }
            catch (Exception err)
            {
                AppLog.Line("Failed to Write rule: " + err.Message);
                return(false);
            }
            return(true);
        }
コード例 #18
0
        public bool BlockInternet(bool bBlock)
        {
            bool    ret  = true;
            Program prog = App.engine.programs.GetProgram(new ProgramList.ID(ProgramList.Types.Global), true);

            if (bBlock)
            {
                ret &= UpdateRule(FirewallRule.MakeBlockRule(prog.GetMainID(), Directions.Inbound), true);
                ret &= UpdateRule(FirewallRule.MakeBlockRule(prog.GetMainID(), Directions.Outboun), true);
            }
            else
            {
                ClearRules(prog, false);
            }
            return(ret);
        }
コード例 #19
0
        public bool UpdateRule(FirewallRule rule)
        {
            bool bAdd = (rule.guid == null);

            try
            {
                NetFwRule FwRule;
                if (bAdd)
                {
                    FwRule = new NetFwRule()
                    {
                        Entry = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")), Rule = rule
                    }
                }
                ;
                else if (!Rules.TryGetValue(rule.guid, out FwRule))
                {
                    Priv10Logger.LogError("Failed Updating rule: ruls is not longer present");
                    return(false);
                }
                else
                {
                    FwRule.Rule = rule;
                }

                if (!SaveRule(rule, FwRule.Entry))
                {
                    return(false);
                }

                if (bAdd)
                {
                    NetFwPolicy.Rules.Add(FwRule.Entry);

                    rule.Index = RuleCounter++;
                    rule.guid  = Guid.NewGuid().ToString("B");
                    Rules.Add(rule.guid, FwRule);
                }
            }
            catch (Exception err)
            {
                Priv10Logger.LogError("Failed to Write rule: " + err.Message);
                return(false);
            }
            return(true);
        }
コード例 #20
0
        public override bool Load(XmlNode entryNode)
        {
            if (!base.Load(entryNode))
            {
                return(false);
            }

            foreach (XmlNode node in entryNode.ChildNodes)
            {
                if (node.Name == "State")
                {
                    Enum.TryParse <States>(node.InnerText, out State);
                }

                //else if (node.Name == "Changed")
                //    bool.TryParse(node.InnerText, out Changed);
                else if (node.Name == "LastChangedTime")
                {
                    DateTime.TryParse(node.InnerText, out LastChangedTime);
                }
                else if (node.Name == "ChangedCount")
                {
                    int.TryParse(node.InnerText, out ChangedCount);
                }

                else if (node.Name == "Expiration")
                {
                    UInt64.TryParse(node.InnerText, out Expiration);
                }

                else if (node.Name == "Backup")
                {
                    Backup = new FirewallRule(ProgID);
                    if (!Backup.Load(node))
                    {
                        Backup = null;
                    }
                }
            }

            return(true);
        }
コード例 #21
0
ファイル: Engine.cs プロジェクト: ExpLife0011/priv10
        public bool UpdateRule(FirewallRule rule)
        {
            return(mDispatcher.Invoke(new Func <bool>(() => {
                if (rule.guid == Guid.Empty)
                {
                    if (rule.Direction == Firewall.Directions.Bidirectiona)
                    {
                        FirewallRule copy = rule.Clone();
                        copy.Direction = Firewall.Directions.Inbound;
                        if (!firewall.UpdateRule(copy))
                        {
                            return false;
                        }

                        rule.Direction = Firewall.Directions.Outboun;
                    }
                }
                return firewall.UpdateRule(rule);
            })));
        }
コード例 #22
0
ファイル: FirewallManager.cs プロジェクト: CazDev/priv10
        public bool ApplyRule(Program prog, FirewallRule rule, UInt64 expiration = 0)
        {
            if (!UpdateRule(rule)) // if the rule is new i.e. guid == null this call will set a new unique guid and add the rule to the global list
            {
                return(false);
            }

            FirewallRuleEx ruleEx;

            if (!prog.Rules.TryGetValue(rule.guid, out ruleEx))
            {
                ruleEx        = new FirewallRuleEx();
                ruleEx.ProgID = FirewallRuleEx.GetIdFromRule(rule);
                prog.Rules.Add(rule.guid, ruleEx);
            }
            ruleEx.Expiration = expiration;
            ruleEx.SetApplied();
            ruleEx.Assign(rule);
            return(true);
        }
コード例 #23
0
 public bool UpdateRule(FirewallRule rule, UInt64 expiration = 0)
 {
     return(RemoteExec("UpdateRule", new object[2] {
         rule, expiration
     }, false));
 }
コード例 #24
0
 public bool RemoveRule(FirewallRule rule)
 {
     return(RemoteExec("RemoveRule", rule, false));
 }
コード例 #25
0
        public void EvaluateRules(Program prog, bool apply)
        {
            String InetRanges = NetFunc.GetNonLocalNet();

            prog.config.CurAccess = Program.Config.AccessLevels.Unconfigured;

            bool StrictTest = false;

            if (prog.Rules.Count > 0)
            {
                SortedDictionary <ProgramList.ID, RuleStat> RuleStats = new SortedDictionary <ProgramList.ID, RuleStat>();
                int enabledCound = 0;

                foreach (FirewallRule rule in prog.Rules.Values.ToList())
                {
                    RuleStat Stat;
                    if (!RuleStats.TryGetValue(rule.mID, out Stat))
                    {
                        Stat = new RuleStat();
                        RuleStats.Add(rule.mID, Stat);
                    }

                    if (!rule.Enabled)
                    {
                        continue;
                    }

                    enabledCound++;

                    if (!IsEmptyOrStar(rule.LocalAddresses))
                    {
                        continue;
                    }
                    if (!IsEmptyOrStar(rule.LocalPorts) || !IsEmptyOrStar(rule.RemotePorts))
                    {
                        continue;
                    }
                    if (!IsEmptyOrStar(rule.IcmpTypesAndCodes))
                    {
                        continue;
                    }

                    bool AllProts  = (rule.Protocol == (int)NetFunc.KnownProtocols.Any);
                    bool InetProts = AllProts || (rule.Protocol == (int)FirewallRule.KnownProtocols.TCP) || (rule.Protocol == (int)FirewallRule.KnownProtocols.UDP);

                    if (!InetProts)
                    {
                        continue;
                    }

                    if (rule.Profile != (int)Profiles.All && (rule.Profile != ((int)Profiles.Public | (int)Profiles.Private | (int)Profiles.Domain)))
                    {
                        continue;
                    }
                    if (rule.Interface != (int)Interfaces.All)
                    {
                        continue;
                    }

                    if (IsEmptyOrStar(rule.RemoteAddresses))
                    {
                        if (rule.Action == Actions.Allow && InetProts)
                        {
                            Stat.AllowAll |= ((int)rule.Direction);
                        }
                        else if (rule.Action == Actions.Block && AllProts)
                        {
                            Stat.BlockAll |= ((int)rule.Direction);
                        }
                    }
                    else if (rule.RemoteAddresses == InetRanges)
                    {
                        if (rule.Action == Actions.Block && AllProts)
                        {
                            Stat.BlockInet |= ((int)rule.Direction);
                        }
                    }
                    else if (rule.RemoteAddresses == "LocalSubnet")
                    {
                        if (rule.Action == Actions.Allow && InetProts)
                        {
                            Stat.AllowLan |= ((int)rule.Direction);
                        }
                    }
                    RuleStats[rule.mID] = Stat;
                }

                RuleStat MergedStat = RuleStats.Values.ElementAt(0);

                for (int i = 1; i < RuleStats.Count; i++)
                {
                    RuleStat Stat = RuleStats.Values.ElementAt(i);

                    MergedStat.AllowAll  &= Stat.AllowAll;
                    MergedStat.BlockAll  &= Stat.BlockAll;
                    MergedStat.AllowLan  &= Stat.AllowLan;
                    MergedStat.BlockInet &= Stat.BlockInet;
                }

                if ((MergedStat.BlockAll & (int)Directions.Outboun) != 0 && (!StrictTest || (MergedStat.BlockAll & (int)Directions.Inbound) != 0))
                {
                    prog.config.CurAccess = Program.Config.AccessLevels.BlockAccess;
                }
                else if ((MergedStat.AllowAll & (int)Directions.Outboun) != 0 && (!StrictTest || (MergedStat.AllowAll & (int)Directions.Inbound) != 0))
                {
                    prog.config.CurAccess = Program.Config.AccessLevels.FullAccess;
                }
                else if ((MergedStat.AllowLan & (int)Directions.Outboun) != 0 && (!StrictTest || ((MergedStat.AllowLan & (int)Directions.Inbound) != 0 && (MergedStat.AllowLan & (int)Directions.Inbound) != 0)))
                {
                    prog.config.CurAccess = Program.Config.AccessLevels.LocalOnly;
                }
                else if (enabledCound > 0)
                {
                    prog.config.CurAccess = Program.Config.AccessLevels.CustomConfig;
                }
            }


            if (!apply || prog.config.NetAccess == Program.Config.AccessLevels.Unconfigured || prog.config.NetAccess == Program.Config.AccessLevels.CustomConfig)
            {
                return;
            }

            if (prog.config.NetAccess == prog.config.CurAccess)
            {
                return;
            }


            if (prog.config.NetAccess != Program.Config.AccessLevels.CustomConfig)
            {
                DisableUserRules(prog);
            }

            ClearPrivRules(prog);

            foreach (ProgramList.ID id in prog.IDs)
            {
                for (int i = 1; i <= 2; i++)
                {
                    Directions direction = (Directions)i;

                    switch (prog.config.NetAccess)
                    {
                    case Program.Config.AccessLevels.FullAccess:

                        // add and enable allow all rule
                        UpdateRule(FirewallRule.MakeAllowRule(id, direction), true);
                        break;

                    case Program.Config.AccessLevels.LocalOnly:

                        // create block rule only of we operate in blacklist mode
                        //if (GetFilteringMode() == FilteringModes.BlackList)
                        //{
                        //add and enable block rules for the internet
                        UpdateRule(FirewallRule.MakeBlockInetRule(id, direction), true);
                        //}

                        //add and enable allow rules for the lan
                        UpdateRule(FirewallRule.MakeAllowLanRule(id, direction), true);
                        break;

                    case Program.Config.AccessLevels.BlockAccess:

                        // add and enable broad block rules
                        UpdateRule(FirewallRule.MakeBlockRule(id, direction), true);
                        break;
                    }
                }
            }

            prog.config.CurAccess = prog.config.NetAccess;

            App.engine.NotifyChange(prog);
        }
コード例 #26
0
        public static bool SaveRule(FirewallRule rule, INetFwRule2 entry)
        {
            try
            {
                entry.EdgeTraversalOptions = (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY;

                INetFwRule3 entry3 = entry as INetFwRule3;

                entry.ApplicationName = rule.BinaryPath;
                entry.serviceName     = rule.ServiceTag;
                if (entry3 != null)
                {
                    entry3.LocalAppPackageId = rule.AppSID;
                }

                /*
                 * switch (rule.ProgID.Type)
                 * {
                 *  case ProgramID.Types.Global:
                 *      entry.ApplicationName = null;
                 *      break;
                 *  case ProgramID.Types.System:
                 *      entry.ApplicationName = "System";
                 *      break;
                 *  default:
                 *      if (rule.ProgID.Path != null && rule.ProgID.Path.Length > 0)
                 *          entry.ApplicationName = rule.ProgID.Path;
                 *      break;
                 * }
                 *
                 * if (rule.ProgID.Type == ProgramID.Types.App)
                 *  entry3.LocalAppPackageId = rule.ProgID.GetPackageSID();
                 * else
                 *  entry3.LocalAppPackageId = null;
                 *
                 * if (rule.ProgID.Type == ProgramID.Types.Service)
                 *  entry.serviceName = rule.ProgID.GetServiceId();
                 * else
                 *  entry.serviceName = null;
                 */

                entry.Name        = rule.Name;
                entry.Grouping    = rule.Grouping;
                entry.Description = rule.Description;

                entry.Enabled = rule.Enabled;

                switch (rule.Direction)
                {
                case FirewallRule.Directions.Inbound: entry.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; break;

                case FirewallRule.Directions.Outboun: entry.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT; break;
                }

                switch (rule.Action)
                {
                case FirewallRule.Actions.Allow: entry.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; break;

                case FirewallRule.Actions.Block: entry.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; break;
                }

                entry.Profiles = rule.Profile;

                if (rule.Interface == (int)FirewallRule.Interfaces.All)
                {
                    entry.InterfaceTypes = "All";
                }
                else
                {
                    List <string> interfaces = new List <string>();
                    if ((rule.Interface & (int)FirewallRule.Interfaces.Lan) != 0)
                    {
                        interfaces.Add("Lan");
                    }
                    if ((rule.Interface & (int)FirewallRule.Interfaces.Wireless) != 0)
                    {
                        interfaces.Add("Wireless");
                    }
                    if ((rule.Interface & (int)FirewallRule.Interfaces.RemoteAccess) != 0)
                    {
                        interfaces.Add("RemoteAccess");
                    }
                    entry.InterfaceTypes = string.Join(",", interfaces.ToArray().Reverse());
                }

                // Note: if this is not cleared protocol change may trigger an exception
                if (entry.LocalPorts != null)
                {
                    entry.LocalPorts = null;
                }
                if (entry.RemotePorts != null)
                {
                    entry.RemotePorts = null;
                }
                if (entry.IcmpTypesAndCodes != null)
                {
                    entry.IcmpTypesAndCodes = null;
                }

                // Note: protocol must be set early enough or other sets will cause errors!
                entry.Protocol = rule.Protocol;

                switch (rule.Protocol)
                {
                case (int)FirewallRule.KnownProtocols.ICMP:
                case (int)FirewallRule.KnownProtocols.ICMPv6:
                    entry.IcmpTypesAndCodes = rule.GetIcmpTypesAndCodes();
                    break;

                case (int)FirewallRule.KnownProtocols.TCP:
                case (int)FirewallRule.KnownProtocols.UDP:
                    entry.LocalPorts  = rule.LocalPorts;
                    entry.RemotePorts = rule.RemotePorts;
                    break;
                }

                if (rule.EdgeTraversal != (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_USER)
                {
                    entry.LocalAddresses  = rule.LocalAddresses;
                    entry.RemoteAddresses = rule.RemoteAddresses;
                }

                entry.EdgeTraversalOptions = rule.EdgeTraversal;


                if (entry3 != null)
                {
                    /*
                     * string s0 = entry3.LocalAppPackageId // 8
                     * string s1 = entry3.RemoteUserAuthorizedList; // 7
                     * string s2 = entry3.RemoteMachineAuthorizedList; // 7
                     * string s3 = entry3.LocalUserAuthorizedList; // 8
                     * string s4 = entry3.LocalUserOwner; // 8
                     * int i1 = entry3.SecureFlags; // ??
                     */
                }
            }
            catch (Exception err)
            {
                Priv10Logger.LogError("Firewall Rule Commit failed {0}", err.ToString());
                return(false);
            }
            return(true);
        }
コード例 #27
0
ファイル: FirewallManager.cs プロジェクト: CazDev/priv10
        public void ApplyRules(ProgramSet progSet, UInt64 expiration = 0)
        {
            EvaluateRules(progSet, true);

            if (progSet.config.NetAccess == ProgramConfig.AccessLevels.Unconfigured)
            {
                return;
            }

            if (progSet.config.NetAccess == progSet.config.CurAccess)
            {
                return;
            }

            foreach (Program prog in progSet.Programs.Values)
            {
                ClearRules(prog, progSet.config.NetAccess != ProgramConfig.AccessLevels.CustomConfig);

                if (progSet.config.NetAccess == ProgramConfig.AccessLevels.CustomConfig)
                {
                    continue; // dont create any rules
                }
                for (int i = 1; i <= 2; i++)
                {
                    FirewallRule.Directions direction = (FirewallRule.Directions)i;

                    if ((progSet.config.NetAccess == ProgramConfig.AccessLevels.InBoundAccess && direction != FirewallRule.Directions.Inbound) ||
                        (progSet.config.NetAccess == ProgramConfig.AccessLevels.OutBoundAccess && direction != FirewallRule.Directions.Outbound))
                    {
                        continue;
                    }

                    switch (progSet.config.NetAccess)
                    {
                    case ProgramConfig.AccessLevels.FullAccess:
                    case ProgramConfig.AccessLevels.InBoundAccess:
                    case ProgramConfig.AccessLevels.OutBoundAccess:
                    {
                        // add and enable allow all rule
                        FirewallRule rule = new FirewallRule();
                        FirewallRuleEx.SetProgID(rule, prog.ID);
                        rule.Name      = MakeRuleName(AllowAllName, expiration != 0, prog.Description);
                        rule.Grouping  = RuleGroup;
                        rule.Action    = FirewallRule.Actions.Allow;
                        rule.Direction = direction;
                        rule.Enabled   = true;
                        ApplyRule(prog, rule, expiration);
                        break;
                    }

                    case ProgramConfig.AccessLevels.LocalOnly:
                    {
                        // create block rule only of we operate in blacklist mode
                        //if (GetFilteringMode() == FilteringModes.BlackList)
                        //{
                        //add and enable block rules for the internet
                        FirewallRule rule1 = new FirewallRule();
                        FirewallRuleEx.SetProgID(rule1, prog.ID);
                        rule1.Name      = MakeRuleName(BlockInet, expiration != 0, prog.Description);
                        rule1.Grouping  = RuleGroup;
                        rule1.Action    = FirewallRule.Actions.Block;
                        rule1.Direction = direction;
                        rule1.Enabled   = true;
                        if (UwpFunc.IsWindows7OrLower)
                        {
                            rule1.RemoteAddresses = GetSpecialNet(FirewallRule.AddrKeywordIntErnet);
                        }
                        else
                        {
                            rule1.RemoteAddresses = FirewallRule.AddrKeywordIntErnet;
                        }
                        ApplyRule(prog, rule1, expiration);
                        //}

                        //add and enable allow rules for the lan
                        FirewallRule rule2 = new FirewallRule();
                        FirewallRuleEx.SetProgID(rule2, prog.ID);
                        rule2.Name      = MakeRuleName(AllowLan, expiration != 0, prog.Description);
                        rule2.Grouping  = RuleGroup;
                        rule2.Action    = FirewallRule.Actions.Allow;
                        rule2.Direction = direction;
                        rule2.Enabled   = true;
                        //rule.RemoteAddresses = FirewallRule.GetSpecialNet(FirewallRule.AddrKeywordLocalSubnet);
                        rule2.RemoteAddresses = FirewallRule.AddrKeywordLocalSubnet;
                        ApplyRule(prog, rule2, expiration);
                        break;
                    }

                    case ProgramConfig.AccessLevels.BlockAccess:
                    {
                        // add and enable broad block rules
                        FirewallRule rule = new FirewallRule();
                        FirewallRuleEx.SetProgID(rule, prog.ID);
                        rule.Name      = MakeRuleName(BlockAllName, expiration != 0, prog.Description);
                        rule.Grouping  = RuleGroup;
                        rule.Action    = FirewallRule.Actions.Block;
                        rule.Direction = direction;
                        rule.Enabled   = true;
                        ApplyRule(prog, rule, expiration);
                        break;
                    }
                    }
                }
            }

            progSet.config.CurAccess = progSet.config.NetAccess;

            App.engine.OnRulesUpdated(progSet);
        }
コード例 #28
0
ファイル: FirewallManager.cs プロジェクト: CazDev/priv10
        public void EvaluateRules(ProgramSet progSet, bool StrictTest = false)
        {
            String InetRanges = FirewallRule.AddrKeywordIntErnet;

            if (UwpFunc.IsWindows7OrLower)
            {
                InetRanges = GetSpecialNet(InetRanges);
            }

            progSet.config.CurAccess = ProgramConfig.AccessLevels.Unconfigured;

            SortedDictionary <ProgramID, RuleStat> RuleStats = new SortedDictionary <ProgramID, RuleStat>();
            int enabledCound = 0;

            foreach (Program prog in progSet.Programs.Values)
            {
                RuleStat Stat = new RuleStat();

                foreach (FirewallRule rule in prog.Rules.Values)
                {
                    if (!rule.Enabled)
                    {
                        continue;
                    }

                    enabledCound++;

                    if (!FirewallRule.IsEmptyOrStar(rule.LocalAddresses))
                    {
                        continue;
                    }
                    if (!FirewallRule.IsEmptyOrStar(rule.LocalPorts) || !FirewallRule.IsEmptyOrStar(rule.RemotePorts))
                    {
                        continue;
                    }
                    if (rule.IcmpTypesAndCodes != null && rule.IcmpTypesAndCodes.Length > 0)
                    {
                        continue;
                    }

                    bool AllProts  = (rule.Protocol == (int)NetFunc.KnownProtocols.Any);
                    bool InetProts = AllProts || (rule.Protocol == (int)FirewallRule.KnownProtocols.TCP) || (rule.Protocol == (int)FirewallRule.KnownProtocols.UDP);

                    if (!InetProts)
                    {
                        continue;
                    }

                    //if (rule.Profile != (int)FirewallRule.Profiles.All && (rule.Profile != ((int)FirewallRule.Profiles.Public | (int)FirewallRule.Profiles.Private | (int)FirewallRule.Profiles.Domain)))
                    //    continue;
                    if (rule.Interface != (int)FirewallRule.Interfaces.All)
                    {
                        continue;
                    }

                    if (FirewallRule.IsEmptyOrStar(rule.RemoteAddresses))
                    {
                        if (rule.Action == FirewallRule.Actions.Allow && InetProts)
                        {
                            Stat.AllowAll.Add(rule.Profile, rule.Direction);
                        }
                        else if (rule.Action == FirewallRule.Actions.Block && AllProts)
                        {
                            Stat.BlockAll.Add(rule.Profile, rule.Direction);
                        }
                    }
                    else if (rule.RemoteAddresses == InetRanges)
                    {
                        if (rule.Action == FirewallRule.Actions.Block && AllProts)
                        {
                            Stat.BlockInet.Add(rule.Profile, rule.Direction);
                        }
                    }
                    else if (rule.RemoteAddresses == FirewallRule.AddrKeywordLocalSubnet)
                    {
                        if (rule.Action == FirewallRule.Actions.Allow && InetProts)
                        {
                            Stat.AllowLan.Add(rule.Profile, rule.Direction);
                        }
                    }
                }

                RuleStats.Add(prog.ID, Stat);
            }

            if (RuleStats.Count == 0 || enabledCound == 0)
            {
                return;
            }

            RuleStat MergedStat = RuleStats.Values.First();

            for (int i = 1; i < RuleStats.Count; i++)
            {
                RuleStat Stat = RuleStats.Values.ElementAt(i);

                MergedStat.AllowAll.Merge(Stat.AllowAll);
                MergedStat.BlockAll.Merge(Stat.BlockAll);
                MergedStat.AllowLan.Merge(Stat.AllowLan);
                MergedStat.BlockInet.Merge(Stat.BlockInet);
            }

            if (MergedStat.BlockAll.IsOutbound(IgnoreDomain) && (!StrictTest || MergedStat.BlockAll.IsInbound(IgnoreDomain)))
            {
                progSet.config.CurAccess = ProgramConfig.AccessLevels.BlockAccess;
            }
            //else if (MergedStat.AllowAll.IsOutbound(SkipDomain) && (!StrictTest || MergedStat.AllowAll.IsInbound(SkipDomain)))
            else if (MergedStat.AllowAll.IsOutbound(IgnoreDomain) && MergedStat.AllowAll.IsInbound(IgnoreDomain))
            {
                progSet.config.CurAccess = ProgramConfig.AccessLevels.FullAccess;
            }
            else if (MergedStat.AllowLan.IsOutbound(IgnoreDomain) && (!StrictTest || (MergedStat.AllowLan.IsInbound(IgnoreDomain) && MergedStat.AllowLan.IsInbound(IgnoreDomain))))
            {
                progSet.config.CurAccess = ProgramConfig.AccessLevels.LocalOnly;
            }
            else if (MergedStat.AllowAll.IsOutbound(IgnoreDomain))
            {
                progSet.config.CurAccess = ProgramConfig.AccessLevels.OutBoundAccess;
            }
            else if (MergedStat.AllowAll.IsInbound(IgnoreDomain))
            {
                progSet.config.CurAccess = ProgramConfig.AccessLevels.InBoundAccess;
            }
            else if (enabledCound > 0)
            {
                progSet.config.CurAccess = ProgramConfig.AccessLevels.CustomConfig;
            }
        }
コード例 #29
0
 public int SetRuleApproval(Priv10Engine.ApprovalMode Mode, FirewallRule rule)
 {
     return(RemoteExec("SetRuleApproval", new object[2] {
         Mode, rule
     }, 0));
 }
コード例 #30
0
        public static bool LoadRule(FirewallRule rule, INetFwRule2 entry)
        {
            try
            {
                INetFwRule3 entry3 = entry as INetFwRule3;

                rule.BinaryPath = entry.ApplicationName;
                rule.ServiceTag = entry.serviceName;
                if (entry3 != null)
                {
                    rule.AppSID = entry3.LocalAppPackageId;
                }

                // Note: while LocalAppPackageId and serviceName can be set at the same timea universall App can not be started as a service
                ProgramID progID;
                if (entry.ApplicationName != null && entry.ApplicationName.Equals("System", StringComparison.OrdinalIgnoreCase))
                {
                    progID = ProgramID.NewID(ProgramID.Types.System);
                }
                // Win10
                else if (entry3 != null && entry3.LocalAppPackageId != null)
                {
                    if (entry.serviceName != null)
                    {
                        throw new ArgumentException("Firewall paremeter conflict");
                    }
                    progID = ProgramID.NewAppID(entry3.LocalAppPackageId, entry.ApplicationName);
                }
                //
                else if (entry.serviceName != null)
                {
                    progID = ProgramID.NewSvcID(entry.serviceName, entry.ApplicationName);
                }
                else if (entry.ApplicationName != null)
                {
                    progID = ProgramID.NewProgID(entry.ApplicationName);
                }
                else // if nothing is configured than its a global roule
                {
                    progID = ProgramID.NewID(ProgramID.Types.Global);
                }

                rule.ProgID = Priv10Engine.AdjustProgID(progID);

                // https://docs.microsoft.com/en-us/windows/desktop/api/netfw/nn-netfw-inetfwrule

                rule.Name        = entry.Name;
                rule.Grouping    = entry.Grouping;
                rule.Description = entry.Description;

                //rule.ProgramPath = entry.ApplicationName;
                //rule.ServiceName = entry.serviceName;

                rule.Enabled = entry.Enabled;

                switch (entry.Direction)
                {
                case NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN: rule.Direction = FirewallRule.Directions.Inbound; break;

                case NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT: rule.Direction = FirewallRule.Directions.Outboun; break;
                }

                switch (entry.Action)
                {
                case NET_FW_ACTION_.NET_FW_ACTION_ALLOW: rule.Action = FirewallRule.Actions.Allow; break;

                case NET_FW_ACTION_.NET_FW_ACTION_BLOCK: rule.Action = FirewallRule.Actions.Block; break;
                }

                rule.Profile = entry.Profiles;

                if (entry.InterfaceTypes.Equals("All", StringComparison.OrdinalIgnoreCase))
                {
                    rule.Interface = (int)FirewallRule.Interfaces.All;
                }
                else
                {
                    rule.Interface = 0;
                    if (entry.InterfaceTypes.IndexOf("Lan", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        rule.Interface |= (int)FirewallRule.Interfaces.Lan;
                    }
                    if (entry.InterfaceTypes.IndexOf("Wireless", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        rule.Interface |= (int)FirewallRule.Interfaces.Wireless;
                    }
                    if (entry.InterfaceTypes.IndexOf("RemoteAccess", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        rule.Interface |= (int)FirewallRule.Interfaces.RemoteAccess;
                    }
                }

                rule.Protocol = entry.Protocol;

                /*The localAddrs parameter consists of one or more comma-delimited tokens specifying the local addresses from which the application can listen for traffic. "*" is the default value. Valid tokens include:
                 *
                 * "*" indicates any local address. If present, this must be the only token included.
                 * "Defaultgateway"
                 * "DHCP"
                 * "WINS"
                 * "LocalSubnet" indicates any local address on the local subnet. This token is not case-sensitive.
                 * A subnet can be specified using either the subnet mask or network prefix notation. If neither a subnet mask not a network prefix is specified, the subnet mask defaults to 255.255.255.255.
                 * A valid IPv6 address.
                 * An IPv4 address range in the format of "start address - end address" with no spaces included.
                 * An IPv6 address range in the format of "start address - end address" with no spaces included.*/

                switch (rule.Protocol)
                {
                case (int)FirewallRule.KnownProtocols.ICMP:
                case (int)FirewallRule.KnownProtocols.ICMPv6:
                    rule.SetIcmpTypesAndCodes(entry.IcmpTypesAndCodes);
                    break;

                case (int)FirewallRule.KnownProtocols.TCP:
                case (int)FirewallRule.KnownProtocols.UDP:
                    // , separated number or range 123-456
                    rule.LocalPorts  = entry.LocalPorts;
                    rule.RemotePorts = entry.RemotePorts;
                    break;
                }

                rule.LocalAddresses  = entry.LocalAddresses;
                rule.RemoteAddresses = entry.RemoteAddresses;

                // https://docs.microsoft.com/de-de/windows/desktop/api/icftypes/ne-icftypes-net_fw_edge_traversal_type_
                //EdgeTraversal = (int)(Entry.EdgeTraversal ? NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_ALLOW : NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY);
                rule.EdgeTraversal = entry.EdgeTraversalOptions;

                if (entry3 != null)
                {
                    /*
                     * string s0 = entry3.LocalAppPackageId // 8
                     * string s1 = entry3.RemoteUserAuthorizedList; // 7
                     * string s2 = entry3.RemoteMachineAuthorizedList; // 7
                     * string s3 = entry3.LocalUserAuthorizedList; // 8
                     * string s4 = entry3.LocalUserOwner; // 8
                     * int i1 = entry3.SecureFlags; // ??
                     */
                }
            }
            catch (Exception err)
            {
                Priv10Logger.LogError("Reading Firewall Rule failed {0}", err.ToString());
                return(false);
            }
            return(true);
        }