예제 #1
0
        /// <summary>
        /// Main entry point of the application.
        /// </summary>
        public static void Main(string[] args)
        {
            ConfigFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            Log.Dest   = Log.Destinations.EventLog;
            Log.Level  = EventLogEntryType.Information;

            int    i          = 0;
            string command    = null;
            string user       = null;
            ulong  maxmem     = 0;
            string address    = null;
            long   expiration = 0;
            UInt64 weight     = 0;
            bool   permit     = false;
            bool   persistent = false;
            UInt64 filterId   = 0;

            while (i < args.Length)
            {
                string param = args[i];
                if (args[i][0] == '/')
                {
                    param = "-" + param.Substring(1);
                }

                if (param == "-h" || param == "-help" || param == "--help")
                {
                    Usage();
                    return;
                }
                else if (param == "-l" || param == "-log-level" || param == "--log-level")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        switch (args[i].ToUpper())
                        {
                        case "INFORMATION":
                        case "INFO":
                            Log.Level = EventLogEntryType.Information;
                            break;

                        case "WARNING":
                        case "WARN":
                            Log.Level = EventLogEntryType.Warning;
                            break;

                        case "ERROR":
                            Log.Level = EventLogEntryType.Error;
                            break;
                        }
                    }
                }
                else if (param == "-g" || param == "-log-file" || param == "--log-file")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        Log.File = args[i];
                        Log.Dest = Log.Destinations.File;
                    }
                }
                else if (param == "-log-size" || param == "--log-size")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        Log.FileSize = long.Parse(args[i]);
                    }
                }
                else if (param == "-log-history" || param == "--log-history")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        Log.FileRotate = int.Parse(args[i]);
                    }
                }
                else if (param == "-c" || param == "-config" || param == "--config")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        ConfigFile = args[i];
                    }
                }
                else if (param == "-u" || param == "-user" || param == "--user")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        user = args[i];
                    }
                }
                else if (param == "-x" || param == "-max-mem" || param == "--max-mem")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        maxmem = ulong.Parse(args[i]);
                    }
                }
                else if (param == "-a" || param == "-address" || param == "--address")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        address = args[i];
                    }
                }
                else if (param == "-e" || param == "-expiration" || param == "--expiration")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        expiration = long.Parse(args[i]);
                    }
                }
                else if (param == "-w" || param == "-weight" || param == "--weight")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        weight = UInt64.Parse(args[i]);
                    }
                }
                else if (param == "-t" || param == "-permit" || param == "--permit")
                {
                    permit = true;
                }
                else if (param == "-s" || param == "-persistent" || param == "--persistent")
                {
                    persistent = true;
                }
                else if (param == "-f" || param == "-filter-id" || param == "--filter-id")
                {
                    if (i + 1 < args.Length)
                    {
                        i++;
                        filterId = UInt64.Parse(args[i]);
                    }
                }
                else if (param.Length > 0 && param[0] == '-')
                {
                    Log.Error("Unknown argument #" + i + " (" + args[i] + ")");
                    if (Environment.UserInteractive)
                    {
                        Usage();
                    }
                    return;
                }
                else
                {
                    command = args[i];
                }
                i++;
            }

            // Set memory limit for this process
            if (maxmem > 0)
            {
                Limit limitMemory = new Limit(maxmem * 1024 * 1024, maxmem * 1024 * 1024);
                limitMemory.AddProcess(Process.GetCurrentProcess().Handle);
                limitMemory.Dispose();
            }

            if (Environment.UserInteractive)
            {
                if (command == null)
                {
                    command = "help";
                }

                if ((Log.Dest & Log.Destinations.File) == 0)
                {
                    Log.Dest = Log.Destinations.Console;
                }
                Log.Info("F2BFwCmd in interactive mode executing command: " + command);
            }

            if (true)
            {
                if (command.ToLower() == "help")
                {
                    Usage();
                }
                else if (command.ToLower() == "examples")
                {
                    Examples();
                }
                else if (command.ToLower() == "list-wfp")
                {
                    Log.Info("Dump F2B WFP provider and sublyer");
                    try
                    {
                        F2B.Firewall.Instance.DumpWFP();
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error(ex.Message);
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "add-wfp")
                {
                    Log.Info("Adding F2B WFP provider and sublyer");
                    try
                    {
                        F2B.Firewall.Instance.Install();
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error(ex.Message);
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "remove-wfp")
                {
                    Log.Info("Removing F2B WFP provider and sublyer");
                    try
                    {
                        F2B.Firewall.Instance.Uninstall();
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error(ex.Message);
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "list-privileges")
                {
                    Log.Info("List F2B WFP privileges");
                    try
                    {
                        F2B.Firewall.Instance.DumpPrivileges();
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error(ex.Message);
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "add-privileges")
                {
                    if (user != null)
                    {
                        Log.Info("Adding privileges to modify F2B firewall rules to account " + user);
                        try
                        {
                            F2B.Firewall.Instance.AddPrivileges(F2B.Sid.Get(user));
                        }
                        catch (FirewallException ex)
                        {
                            Log.Error(ex.Message);
                            Environment.Exit(1);
                        }
                    }
                    else
                    {
                        Console.WriteLine("ERROR: missing user argument");
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "remove-privileges")
                {
                    if (user != null)
                    {
                        Log.Info("Removing privileges to modify F2B firewall rules from account " + user);
                        try
                        {
                            F2B.Firewall.Instance.RemovePrivileges(F2B.Sid.Get(user));
                        }
                        catch (FirewallException ex)
                        {
                            Log.Error(ex.Message);
                            Environment.Exit(1);
                        }
                    }
                    else
                    {
                        Console.WriteLine("ERROR: missing user argument");
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "list-filters")
                {
                    try
                    {
                        var details = F2B.Firewall.Instance.List(true);
                        foreach (var item in F2B.Firewall.Instance.List())
                        {
                            try
                            {
                                Tuple <long, byte[]> fwname = FwData.DecodeName(item.Value);
                                string tmp = Convert.ToString(fwname.Item1);
                                try
                                {
                                    DateTime tmpExp = new DateTime(fwname.Item1, DateTimeKind.Utc);
                                    tmp = tmpExp.ToLocalTime().ToString();
                                }
                                catch (Exception)
                                {
                                }
                                Console.WriteLine("{0}: {1} (expiration={2}, md5={3}) ... {4}",
                                                  item.Key, item.Value, tmp,
                                                  BitConverter.ToString(fwname.Item2).Replace("-", ":"),
                                                  details.ContainsKey(item.Key) ? details[item.Key] : "");
                            }
                            catch (ArgumentException)
                            {
                                // can't parse filter rule name to F2B structured data
                                Console.WriteLine("{0}: {1}", item.Key, item.Value);
                            }
                        }
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error("Unable to list firewall filters: " + ex.Message);
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "remove-filters")
                {
                    try
                    {
                        F2B.Firewall.Instance.Cleanup();
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error("Unable to remove all firewall filters: " + ex.Message);
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "remove-expired-filters")
                {
                    long currTime = DateTime.UtcNow.Ticks;

                    try
                    {
                        foreach (var item in F2B.Firewall.Instance.List())
                        {
                            try
                            {
                                Tuple <long, byte[]> fwname = FwData.DecodeName(item.Value);
                                if (currTime > fwname.Item1)
                                {
                                    Log.Info("Remove expired filter #" + item.Key
                                             + " (expiration=" + fwname.Item1 + ", md5="
                                             + BitConverter.ToString(fwname.Item2).Replace("-", ":")
                                             + ")");
                                    F2B.Firewall.Instance.Remove(item.Key);
                                }
                            }
                            catch (ArgumentException)
                            {
                                // can't parse filter rule name to F2B structured data
                                Log.Info("Unable to parse expiration time from filter #" + item.Key);
                            }
                        }
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error("Unable to remove expired firewall filters: " + ex.Message);
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "remove-unknown-filters")
                {
                    try
                    {
                        foreach (var item in F2B.Firewall.Instance.List())
                        {
                            try
                            {
                                Tuple <long, byte[]> fwname = FwData.DecodeName(item.Value);
                            }
                            catch (ArgumentException)
                            {
                                // can't parse filter rule name to F2B structured data
                                Log.Info("Remove filter #" + item.Key + " with unparsable filter name: " + item.Value);
                                F2B.Firewall.Instance.Remove(item.Key);
                            }
                        }
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error("Unable to remove unknown firewall filters: " + ex.Message);
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "add-filter")
                {
                    if (address == null)
                    {
                        Console.WriteLine("ERROR: missing address argument");
                        Environment.Exit(1);
                    }

                    IPAddress addr;
                    int       prefix = 128;
                    if (address.IndexOf('/') > 0)
                    {
                        if (!IPAddress.TryParse(address.Substring(0, address.IndexOf('/')), out addr) || !int.TryParse(address.Substring(address.IndexOf('/') + 1), out prefix))
                        {
                            Console.WriteLine("ERROR: unable to parse address " + address);
                            Environment.Exit(1);
                        }
                    }
                    else
                    {
                        if (!IPAddress.TryParse(address, out addr))
                        {
                            Console.WriteLine("ERROR: unable to parse address " + address);
                            Environment.Exit(1);
                        }
                    }

                    try
                    {
                        if (expiration == 0)
                        {
                            string filterName  = "F2B " + (permit ? "permit " : "block ") + address + " with no expiration" + (persistent ? " (persistent rule)" : "");
                            UInt64 filterIdNew = F2B.Firewall.Instance.Add(filterName, addr, prefix, weight, permit, persistent);
                            Log.Info("Added new filter #" + filterIdNew + " with name: " + filterName);
                        }
                        else
                        {
                            FwData fwdata = new FwData(expiration, addr, prefix);

                            // This code doesn't enumerate and check existing F2B firewall rules,
                            // but it must be updated together with changes in FwManager ... so
                            // to get consistent behavior in future it is better to use directly
                            // less optimal function from FwManager
                            //
                            //byte[] hash = fwdata.Hash;
                            //FirewallConditions conds = fwdata.Conditions();
                            //
                            //// IPv4 filter layer
                            //if (conds.HasIPv4() || (!conds.HasIPv4() && !conds.HasIPv6()))
                            //{
                            //    byte[] hash4 = new byte[hash.Length];
                            //    hash.CopyTo(hash4, 0);
                            //    hash4[hash4.Length - 1] &= 0xfe;
                            //    string filterName = FwData.EncodeName(expiration, hash4);
                            //    UInt64 filterIdNew = F2B.Firewall.Instance.AddIPv4(filterName, conds);
                            //    Log.Info("Added new IPv4 filter #" + filterIdNew + " for " + addr + "/" + prefix + " with encoded name: " + filterName);
                            //}
                            //
                            //// IPv6 filter layer
                            //if (conds.HasIPv6() || (!conds.HasIPv4() && !conds.HasIPv6()))
                            //{
                            //    byte[] hash6 = new byte[hash.Length];
                            //    hash.CopyTo(hash6, 0);
                            //    hash6[hash6.Length - 1] |= 0x01;
                            //    string filterName = FwData.EncodeName(expiration, hash6);
                            //    UInt64 filterIdNew = F2B.Firewall.Instance.AddIPv4(filterName, conds);
                            //    Log.Info("Added new IPv6 filter #" + filterIdNew + " for " + addr + "/" + prefix + " with encoded name: " + filterName);
                            //}

                            FwManager.Instance.Add(fwdata, weight, permit, persistent);
                        }
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error("Unable to add firewall filter: " + ex.Message);
                        Environment.Exit(1);
                    }
                }
                else if (command.ToLower() == "remove-filter")
                {
                    if (filterId == 0)
                    {
                        Console.WriteLine("ERROR: missing filterId argument");
                        Environment.Exit(1);
                    }
                    try
                    {
                        F2B.Firewall.Instance.Remove(filterId);
                    }
                    catch (FirewallException ex)
                    {
                        Log.Error("Unable to remove firewall filter: " + ex.Message);
                        Environment.Exit(1);
                    }
                }
                else
                {
                    Log.Error("Unknown F2BFwCmd command: " + command);
                    return;
                }

                // Waiting a key press to not return to VS directly
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.WriteLine();
                    Console.Write("=== Press a key to quit ===");
                    Console.ReadKey();
                    Console.WriteLine();
                }
            }

            Log.Info("F2BFwCmd main finished");
        }
예제 #2
0
파일: Fw.cs 프로젝트: phoenixyj/F2B
        public void Refresh()
        {
            Log.Info("Refresh list of F2B filter rules from WFP data structures");

            lock (dataLock)
            {
                data    = new Dictionary <UInt64, byte[]>();
                expire  = new Dictionary <byte[], long>(new ByteArrayComparer());
                cleanup = new SortedDictionary <long, UInt64>();

                IDictionary <ulong, string> filters;
                long currtime = DateTime.UtcNow.Ticks;

                try
                {
                    filters = F2B.Firewall.Instance.List();
                }
                catch (FirewallException ex)
                {
                    Log.Error("Unable to list F2B firewall filters: " + ex.Message);
                    return;
                }

                // get current F2B firewall rules from WFP configuration
                foreach (var item in filters)
                {
                    Tuple <long, byte[]> fwName = null;
                    try
                    {
                        fwName = FwData.DecodeName(item.Value);
                    }
                    catch (ArgumentException)
                    {
                        Log.Info("Refresh: Unable to parse F2B data from filter rule name: " + item.Value);
                        continue;
                    }

                    UInt64 filterId   = item.Key;
                    long   expiration = fwName.Item1;
                    byte[] hash       = fwName.Item2;

                    // cleanup expired rules
                    if (expiration < currtime)
                    {
                        try
                        {
                            F2B.Firewall.Instance.Remove(filterId);
                            Log.Info("Refresh: Removed expired filter rule #" + filterId);
                        }
                        catch (Exception ex)
                        {
                            Log.Warn("Refresh: Unable to remove expired filter rule #" + filterId + ": " + ex.Message);
                            //fail++;
                        }
                        continue;
                    }

                    // cleanup rules with same hash
                    long expirationOld;
                    if (expire.TryGetValue(hash, out expirationOld))
                    {
                        UInt64 filterIdOld    = cleanup[expirationOld];
                        UInt64 filterIdRemove = (expiration < expirationOld ? filterId : filterIdOld);
                        try
                        {
                            F2B.Firewall.Instance.Remove(filterIdRemove);
                            Log.Info("Refresh: Removed older filter rule #" + filterId);
                        }
                        catch (Exception ex)
                        {
                            Log.Warn("Refresh: Unable to remove older rule #" + filterIdRemove + ": " + ex.Message);
                            //fail++;
                        }

                        if (expiration < expirationOld)
                        {
                            Log.Info("Refresh: Skipping older (removed) filter rule");
                            continue;
                        }
                        else
                        {
                            data.Remove(filterIdOld);
                            expire.Remove(hash); // not necessary
                            cleanup.Remove(expirationOld);
                        }
                    }

                    // we need unique expiration time to keep all required
                    // data in simple key/value hashmap structure (and we
                    // really don't care about different expiration time in ns)
                    while (cleanup.ContainsKey(expiration))
                    {
                        expiration++;
                    }

                    Log.Info("Refresh: Add filter rule e/f/h: " + expiration + "/" + filterId + "/" + BitConverter.ToString(hash).Replace("-", ":"));
                    data[filterId]      = hash;
                    expire[hash]        = expiration;
                    cleanup[expiration] = filterId;
                }

                if (data.Count > 0)
                {
                    if (tCleanupExpired.Enabled)
                    {
                        Log.Info("Found " + data.Count + " F2B existing filter rules, cleanup timer already running (interval " + tCleanupExpired.Interval + " ms)");
                    }
                    else
                    {
                        Log.Info("Found " + data.Count + " F2B existing filter rules, enabling cleanup timer (interval " + tCleanupExpired.Interval + " ms)");
                        tCleanupExpired.Enabled = true;
                    }
                }
                else
                {
                    if (tCleanupExpired.Enabled)
                    {
                        Log.Info("No F2B filter rules currently defined in WFP, disabling cleanup timer");
                        tCleanupExpired.Enabled = true;
                    }
                    else
                    {
                        Log.Info("No F2B filter rules currently defined in WFP, cleanup timer already disabled");
                    }
                }
            }
        }