Example #1
0
        public IEnumerable <IPAddressRange> EnumerateIPAddresses(string ruleNamePrefix = null)
        {
            string tempFile = IPBanOS.GetTempFileName();

            try
            {
                string prefix = RulePrefix + (ruleNamePrefix ?? string.Empty);
                RunProcess("ipset", true, $"save > \"{tempFile}\"");
                bool inSet = false;
                foreach (string line in File.ReadLines(tempFile))
                {
                    string[] pieces = line.Split(' ');
                    if (pieces.Length > 1 && pieces[0].Equals("create", StringComparison.OrdinalIgnoreCase))
                    {
                        inSet = (pieces[1].StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
                    }
                    else if (inSet && pieces.Length > 2 && pieces[0] == "add")
                    {
                        yield return(IPAddressRange.Parse(pieces[2]));
                    }
                }
            }
            finally
            {
                IPBanExtensionMethods.FileDeleteWithRetry(tempFile);
            }
        }
Example #2
0
        private void RemoveAllTablesAndSets()
        {
            if (!IsIPV4)
            {
                return;
            }

            try
            {
                string dir = AppDomain.CurrentDomain.BaseDirectory;
                foreach (string setFile in Directory.GetFiles(dir, "*.set")
                         .Union(Directory.GetFiles(dir, "*.tbl")
                                .Union(Directory.GetFiles(dir, "*.set6"))
                                .Union(Directory.GetFiles(dir, "*.tbl6"))))
                {
                    IPBanExtensionMethods.FileDeleteWithRetry(setFile);
                }
                RunProcess(IpTablesProcess, true, "-F");
                RunProcess(ip6TablesProcess, true, "-F");
                RunProcess("ipset", true, "destroy");
            }
            catch
            {
            }
        }
Example #3
0
        public static int Main(string[] args)
        {
            IPBanExtensionMethods.RequireAdministrator();

            if (args.Length != 0 && args[0].Equals("info", StringComparison.OrdinalIgnoreCase))
            {
                IPBanLog.Warn("System info: {0}", IPBanOS.OSString());
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                IPBanWindowsApp.WindowsMain(args);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                IPBanLinuxApp.LinuxMain(args);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                throw new PlatformNotSupportedException("Mac OSX is not yet supported, but may be in the future.");
                //IPBanMacApp.MacMain(args);
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
            return(0);
        }
Example #4
0
        public IEnumerable <string> EnumerateAllowedIPAddresses()
        {
            string tempFile = IPBanOS.GetTempFileName();

            try
            {
                RunProcess("ipset", true, $"save > \"{tempFile}\"");
                bool inAllow = true;
                foreach (string line in File.ReadLines(tempFile))
                {
                    string[] pieces = line.Split(' ');
                    if (pieces.Length > 1 && pieces[0].Equals("create", StringComparison.OrdinalIgnoreCase))
                    {
                        inAllow = (pieces[1].Equals(AllowRuleName));
                    }
                    else if (inAllow && pieces.Length > 2 && pieces[0] == "add")
                    {
                        yield return(pieces[2]);
                    }
                }
            }
            finally
            {
                IPBanExtensionMethods.FileDeleteWithRetry(tempFile);
            }
        }
Example #5
0
 /// <summary>
 /// Update - if the text file path exists, all ip addresses from each line will be banned
 /// </summary>
 public async Task Update()
 {
     try
     {
         if (File.Exists(textFilePath))
         {
             string[] lines = (await File.ReadAllLinesAsync(textFilePath)).Where(l => IPAddress.TryParse(l, out _)).ToArray();
             IPBanLog.Warn("Queueing {0} ip addresses to ban from {1} file", lines.Length, textFilePath);
             List <IPAddressLogEvent> bans = new List <IPAddressLogEvent>();
             foreach (string[] pieces in lines.Select(l => l.Split(',')))
             {
                 if (pieces.Length < 1)
                 {
                     continue;
                 }
                 string ipAddress = pieces[0];
                 string source    = (pieces.Length < 2 ? "Block" : pieces[1]);
                 bans.Add(new IPAddressLogEvent(ipAddress, string.Empty, source, 1, IPAddressEventType.Blocked));
             }
             service.AddIPAddressLogEvents(bans);
             IPBanExtensionMethods.FileDeleteWithRetry(textFilePath);
         }
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
     }
 }
Example #6
0
        /// <summary>
        /// Run the service
        /// </summary>
        /// <param name="requireAdministrator">True to require administrator, false otherwise</param>
        /// <returns>Exit code</returns>
        public Task <int> RunAsync(bool requireAdministrator = true)
        {
            if (requireAdministrator)
            {
                IPBanExtensionMethods.RequireAdministrator();
            }

            if (args.Length != 0 && (args[0].Equals("info", StringComparison.OrdinalIgnoreCase) || args[0].Equals("-info", StringComparison.OrdinalIgnoreCase)))
            {
                IPBanLog.Warn("System info: {0}", IPBanOS.OSString());
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                RunWindowsService(args);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                RunLinuxService(args);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                throw new PlatformNotSupportedException("Mac OSX is not yet supported, but may be in the future.");
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
            return(Task.FromResult(0));
        }
Example #7
0
 /// <summary>
 /// Dispose of all resources, does not delete the database file
 /// </summary>
 public void Dispose()
 {
     GC.Collect();
     GC.WaitForPendingFinalizers();
     if (autoDelete)
     {
         IPBanExtensionMethods.FileDeleteWithRetry(dbPath);
     }
 }
Example #8
0
        /// <summary>
        /// Create a test IPBanService
        /// </summary>
        /// <param name="directory">Root directory</param>
        /// <param name="configFileName">Config file name</param>
        /// <param name="defaultBannedIPAddressHandlerUrl">Url for banned ip handling or null to not handle banned ip</param>
        /// <param name="configFileModifier">Change config file (param are file text, returns new file text)</param>
        /// <returns>Service</returns>
        public static T CreateAndStartIPBanTestService <T>(string directory = null, string configFileName = null, string defaultBannedIPAddressHandlerUrl = null,
                                                           Func <string, string> configFileModifier = null) where T : IPBanService
        {
            DefaultHttpRequestMaker.DisableLiveRequests = true;

            // cleanup any db, set or tbl files
            foreach (string file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.set")
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tbl"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.set6"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tbl6"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.sqlite*"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*journal*")))
            {
                IPBanExtensionMethods.FileDeleteWithRetry(file, 1000);
            }

            if (string.IsNullOrWhiteSpace(directory))
            {
                directory = Path.GetDirectoryName(IPBanAssembly.Location);
            }
            if (string.IsNullOrWhiteSpace(configFileName))
            {
                configFileName = IPBanService.ConfigFileName;
            }
            string configFilePath = Path.Combine(directory, configFileName);
            string configFileText = File.ReadAllText(configFilePath);

            configFilePath += ".tmp";
            if (configFileModifier != null)
            {
                configFileText = configFileModifier(configFileText);
            }
            IPBanExtensionMethods.FileWriteAllTextWithRetry(configFilePath, configFileText);
            T service = IPBanService.CreateService <T>() as T;

            service.ExternalIPAddressLookup = LocalMachineExternalIPAddressLookupTest.Instance;
            service.ConfigFilePath          = configFilePath;
            service.MultiThreaded           = false;
            service.ManualCycle             = true;
            if (defaultBannedIPAddressHandlerUrl is null)
            {
                service.BannedIPAddressHandler = service;
            }
            else
            {
                service.BannedIPAddressHandler = new DefaultBannedIPAddressHandler {
                    BaseUrl = defaultBannedIPAddressHandlerUrl
                };
            }
            service.Version = "1.1.1.1";
            service.StartAsync().Sync();
            service.DB.Truncate(true);
            service.Firewall.Truncate();
            return(service);
        }
Example #9
0
        /// <summary>
        /// Create an IPBanService by searching all types in all assemblies
        /// </summary>
        /// <returns>IPBanService (if not found an exception is thrown)</returns>
        public static T CreateService <T>() where T : IPBanService
        {
            Type typeOfT = typeof(T);

            // if any derived class of IPBanService, use that
            List <Type> allTypes = IPBanExtensionMethods.GetAllTypes();
            var         q        =
                from type in allTypes
                where typeOfT.IsAssignableFrom(type)
                select type;
            Type instanceType = (q.FirstOrDefault() ?? typeof(IPBanService));

            return(Activator.CreateInstance(instanceType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, null, null) as T);
        }
Example #10
0
        private void RunScript(string scriptFileName)
        {
            ProcessStartInfo info = new ProcessStartInfo
            {
                FileName        = "netsh",
                Arguments       = "exec \"" + scriptFileName + "\"",
                CreateNoWindow  = true,
                WindowStyle     = ProcessWindowStyle.Hidden,
                UseShellExecute = true
            };
            Process p = Process.Start(info);

            p.WaitForExit();
            IPBanExtensionMethods.FileDeleteWithRetry(scriptFileName);
        }
Example #11
0
 public static async Task MainService(string[] args, Func <string[], Task> start, Action stop, bool requireAdministrator = true)
 {
     try
     {
         using (IPBanServiceRunner runner = new IPBanServiceRunner(args, start, stop))
         {
             await runner.RunAsync(requireAdministrator);
         }
     }
     catch (Exception ex)
     {
         IPBanExtensionMethods.FileWriteAllTextWithRetry(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "startup_fail.txt"), ex.ToString());
         IPBanLog.Fatal("Fatal error starting service", ex);
     }
 }
 /// <summary>
 /// Update - if the text file path exists, all ip addresses from each line will be unbanned
 /// </summary>
 public async Task Update()
 {
     try
     {
         if (File.Exists(textFilePath))
         {
             string[] lines = (await File.ReadAllLinesAsync(textFilePath)).Where(l => IPAddress.TryParse(l, out _)).ToArray();
             IPBanLog.Warn("Queueing {0} ip addresses to unban from {1} file", lines.Length, textFilePath);
             UnblockIPAddresses(lines);
             IPBanExtensionMethods.FileDeleteWithRetry(textFilePath);
         }
     }
     catch (Exception ex)
     {
         IPBanLog.Error(ex);
     }
 }
Example #13
0
        private IPAddressEntry ParseIPAddressEntry(SQLiteDataReader reader)
        {
            string   ipAddress         = reader.GetString(0);
            long     lastFailedLogin   = reader.GetInt64(1);
            long     failedLoginCount  = reader.GetInt64(2);
            object   banDateObj        = reader.GetValue(3);
            long     banDateLong       = (banDateObj == null || banDateObj == DBNull.Value ? 0 : Convert.ToInt64(banDateObj));
            DateTime?banDate           = (banDateLong == 0 ? (DateTime?)null : IPBanExtensionMethods.UnixTimeStampToDateTimeMilliseconds(banDateLong));
            DateTime lastFailedLoginDt = IPBanExtensionMethods.UnixTimeStampToDateTimeMilliseconds(lastFailedLogin);

            return(new IPAddressEntry
            {
                IPAddress = ipAddress,
                LastFailedLogin = lastFailedLoginDt,
                FailedLoginCount = (int)failedLoginCount,
                BanDate = banDate
            });
        }
Example #14
0
 /// <summary>
 /// Get the ban date for an ip address
 /// </summary>
 /// <param name="ipAddress">IP address</param>
 /// <returns>Ban date or null if not banned or not in the database</returns>
 public DateTime?GetBanDate(string ipAddress)
 {
     if (IPAddress.TryParse(ipAddress, out IPAddress ipAddressObj))
     {
         byte[] ipBytes = ipAddressObj.GetAddressBytes();
         using (SQLiteDataReader reader = ExecuteReader("SELECT BanDate FROM IPAddresses WHERE IPAddress = @Param0", ipBytes))
         {
             if (reader.Read())
             {
                 object val = reader.GetValue(0);
                 if (val != null && val != DBNull.Value)
                 {
                     return(IPBanExtensionMethods.UnixTimeStampToDateTimeMilliseconds((long)val));
                 }
             }
         }
     }
     return(null);
 }
Example #15
0
 /// <summary>
 /// Write config
 /// </summary>
 /// <param name="config">Config string to write</param>
 /// <returns>Task</returns>
 public async Task WriteConfigAsync(string config)
 {
     if (UseFile)
     {
         await Locker.LockActionAsync(async() =>
         {
             // don't perform needless file write if config is identical
             string existingConfig = await File.ReadAllTextAsync(Path);
             if (existingConfig != config)
             {
                 await IPBanExtensionMethods.FileWriteAllTextWithRetryAsync(Path, config);
             }
         });
     }
     else
     {
         GlobalConfigString = config;
     }
 }
Example #16
0
        /// <summary>
        /// Run the service
        /// </summary>
        /// <param name="requireAdministrator">True to require administrator, false otherwise</param>
        /// <returns>Exit code</returns>
        public async Task RunAsync(bool requireAdministrator = true)
        {
            if (requireAdministrator)
            {
                IPBanExtensionMethods.RequireAdministrator();
            }

            if (args.Length != 0 && (args[0].Equals("info", StringComparison.OrdinalIgnoreCase) || args[0].Equals("-info", StringComparison.OrdinalIgnoreCase)))
            {
                IPBanLog.Warn("System info: {0}", IPBanOS.OSString());
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                await RunWindowsService(args);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                await RunLinuxService(args);
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
        }
Example #17
0
 /// <summary>
 /// Create a firewall
 /// </summary>
 /// <param name="osAndFirewall">Dictionary of string operating system name (Windows, Linux, OSX) and firewall class</param>
 /// <param name="rulePrefix">Rule prefix or null for default</param>
 /// <returns>Firewall</returns>
 public static IIPBanFirewall CreateFirewall(IReadOnlyDictionary <string, string> osAndFirewall, string rulePrefix = null, IIPBanFirewall existing = null)
 {
     try
     {
         bool        foundFirewallType = false;
         int         priority          = int.MinValue;
         Type        firewallType      = typeof(IIPBanFirewall);
         List <Type> allTypes          = IPBanExtensionMethods.GetAllTypes();
         var         q =
             from fwType in allTypes
             where fwType.IsPublic &&
             fwType != firewallType &&
             firewallType.IsAssignableFrom(fwType) &&
             fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>() != null &&
             fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>().IsValid
             select new { FirewallType = fwType, OS = fwType.GetCustomAttribute <RequiredOperatingSystemAttribute>(), Name = fwType.GetCustomAttribute <CustomNameAttribute>() };
         var array = q.ToArray();
         foreach (var result in array)
         {
             // look up the requested firewall by os name
             bool matchPriority = priority < result.OS.Priority;
             if (matchPriority)
             {
                 bool matchName = true;
                 if (osAndFirewall != null && osAndFirewall.Count != 0 &&
                     (osAndFirewall.TryGetValue(IPBanOS.Name, out string firewallToUse) || osAndFirewall.TryGetValue("*", out firewallToUse)))
                 {
                     matchName = result.Name.Name.Equals(firewallToUse, StringComparison.OrdinalIgnoreCase);
                 }
                 if (matchName)
                 {
                     // if IsAvailable method is provided, attempt to call
                     MethodInfo available = result.FirewallType.GetMethod("IsAvailable", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
                     if (available != null)
                     {
                         try
                         {
                             if (!Convert.ToBoolean(available.Invoke(null, null)))
                             {
                                 continue;
                             }
                         }
                         catch
                         {
                             continue;
                         }
                     }
                     firewallType      = result.FirewallType;
                     priority          = result.OS.Priority;
                     foundFirewallType = true;
                 }
             }
         }
         if (firewallType == null)
         {
             throw new ArgumentException("Firewall is null, at least one type should implement IIPBanFirewall");
         }
         else if (osAndFirewall.Count != 0 && !foundFirewallType)
         {
             string typeString = string.Join(',', osAndFirewall.Select(kv => kv.Key + ":" + kv.Value));
             throw new ArgumentException("Unable to find firewalls of types: " + typeString + ", osname: " + IPBanOS.Name);
         }
         if (existing != null && existing.GetType().Equals(firewallType))
         {
             return(existing);
         }
         return(Activator.CreateInstance(firewallType, new object[] { rulePrefix }) as IIPBanFirewall);
     }
     catch (Exception ex)
     {
         throw new ArgumentException("Unable to create firewall, please double check your Firewall configuration property", ex);
     }
 }
Example #18
0
        static IPBanOS()
        {
            try
            {
                tempFolder = Path.GetTempPath();
                if (string.IsNullOrWhiteSpace(tempFolder))
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        tempFolder = "c:\\temp";
                    }
                    else
                    {
                        tempFolder = "/tmp";
                    }
                }
                Directory.CreateDirectory(tempFolder);

                // start off with built in version info, this is not as detailed or nice as we like,
                //  so we try some other ways to get more detailed information
                Version     = Environment.OSVersion.VersionString;
                Description = RuntimeInformation.OSDescription;

                // attempt to get detailed version info
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    isLinux = true;
                    string tempFile = IPBanOS.GetTempFileName();
                    Process.Start("/bin/bash", "-c \"cat /etc/*release* > " + tempFile + "\"").WaitForExit();
                    System.Threading.Tasks.Task.Delay(100); // wait a small bit for file to really be closed
                    string versionText = File.ReadAllText(tempFile).Trim();
                    IPBanExtensionMethods.FileDeleteWithRetry(tempFile);
                    if (string.IsNullOrWhiteSpace(versionText))
                    {
                        IPBanLog.Error(new IOException("Unable to load os version from /etc/*release* ..."));
                    }
                    else
                    {
                        Name         = IPBanOS.Linux;
                        FriendlyName = ExtractRegex(versionText, "^(Id|Distrib_Id)=(?<value>.*?)$", string.Empty);
                        if (FriendlyName.Length != 0)
                        {
                            string codeName = ExtractRegex(versionText, "^(Name|Distrib_CodeName)=(?<value>.+)$", string.Empty);
                            if (codeName.Length != 0)
                            {
                                FriendlyName += " - " + codeName;
                            }
                            Version = ExtractRegex(versionText, "^Version_Id=(?<value>.+)$", Version);
                        }
                    }
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    isWindows   = true;
                    processVerb = "runas";
                    Name        = IPBanOS.Windows;
                    string tempFile = IPBanOS.GetTempFileName();

                    // .net core WMI has a strange bug where WMI will not initialize on some systems
                    // since this is the only place where WMI is used, we can just work-around it
                    // with the wmic executable, which exists (as of 2018) on all supported Windows.
                    StartProcessAndWait("cmd", "/C wmic path Win32_OperatingSystem get Caption,Version /format:table > \"" + tempFile + "\"");
                    if (File.Exists(tempFile))
                    {
                        // try up to 10 times to read the file
                        for (int i = 0; i < 10; i++)
                        {
                            try
                            {
                                string[] lines = File.ReadAllLines(tempFile);
                                IPBanExtensionMethods.FileDeleteWithRetry(tempFile);
                                if (lines.Length > 1)
                                {
                                    int versionIndex = lines[0].IndexOf("Version");
                                    if (versionIndex >= 0)
                                    {
                                        FriendlyName = lines[1].Substring(0, versionIndex - 1).Trim();
                                        Version      = lines[1].Substring(versionIndex).Trim();
                                        break;
                                    }
                                }
                                throw new IOException("Invalid file generated from wmic");
                            }
                            catch (Exception ex)
                            {
                                if (i < 9)
                                {
                                    System.Threading.Tasks.Task.Delay(200).Wait();
                                }
                                else
                                {
                                    IPBanLog.Error(ex, "Unable to load os version using wmic, trying wmi api...");

                                    // last resort, try wmi api
                                    LoadVersionFromWmiApi();
                                }
                            }
                        }
                    }
                    else
                    {
                        // last resort, try wmi api
                        LoadVersionFromWmiApi();
                    }
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    // TODO: Implement better for MAC
                    Name         = IPBanOS.Mac;
                    FriendlyName = "OSX";
                }
                else
                {
                    Name         = IPBanOS.Unknown;
                    FriendlyName = "Unknown";
                }
            }
            catch (Exception ex)
            {
                IPBanLog.Error("Error determining platform info", ex);
            }
        }
Example #19
0
        // deleteRule will drop the rule and matching set before creating the rule and set, use this is you don't care to update the rule and set in place
        protected bool UpdateRuleDelta(string ruleName, string action, IEnumerable <IPBanFirewallIPAddressDelta> deltas, string hashType,
                                       int maxCount, bool deleteRule, IEnumerable <PortRange> allowPorts, CancellationToken cancelToken)
        {
            string ipFileTemp = IPBanOS.GetTempFileName();

            try
            {
                // add and remove the appropriate ip addresses from the set
                using (StreamWriter writer = File.CreateText(ipFileTemp))
                {
                    if (cancelToken.IsCancellationRequested)
                    {
                        throw new OperationCanceledException(cancelToken);
                    }
                    writer.WriteLine($"create {ruleName} hash:{hashType} family {INetFamily} hashsize {hashSize} maxelem {maxCount} -exist");
                    foreach (IPBanFirewallIPAddressDelta delta in deltas)
                    {
                        if (cancelToken.IsCancellationRequested)
                        {
                            throw new OperationCanceledException(cancelToken);
                        }

                        if (IPAddressRange.TryParse(delta.IPAddress, out IPAddressRange range) &&
                            range.Begin.AddressFamily == addressFamily && range.End.AddressFamily == addressFamily)
                        {
                            try
                            {
                                if (delta.Added)
                                {
                                    if (range.Begin.Equals(range.End))
                                    {
                                        writer.WriteLine($"add {ruleName} {range.Begin} -exist");
                                    }
                                    else
                                    {
                                        writer.WriteLine($"add {ruleName} {range.ToCidrString()} -exist");
                                    }
                                }
                                else
                                {
                                    if (range.Begin.Equals(range.End))
                                    {
                                        writer.WriteLine($"del {ruleName} {range.Begin} -exist");
                                    }
                                    else
                                    {
                                        writer.WriteLine($"del {ruleName} {range.ToCidrString()} -exist");
                                    }
                                }
                            }
                            catch
                            {
                                // ignore invalid cidr ranges
                            }
                        }
                    }
                }

                if (cancelToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException(cancelToken);
                }
                else
                {
                    // restore the deltas into the existing set
                    bool result = (RunProcess("ipset", true, $"restore < \"{ipFileTemp}\"") == 0);
                    CreateOrUpdateRule(ruleName, action, hashType, maxCount, allowPorts, cancelToken);
                    return(result);
                }
            }
            finally
            {
                IPBanExtensionMethods.FileDeleteWithRetry(ipFileTemp);
            }
        }
Example #20
0
        /* // makes nlog go haywire, revisit later
         * private static readonly CustomTimeSource timeSource = new CustomTimeSource();
         *
         * private class CustomTimeSource : NLog.Time.TimeSource
         * {
         *  private TimeZoneInfo zoneInfo = TimeZoneInfo.Utc;
         *
         *  [Required]
         *  public string Zone
         *  {
         *      get { return zoneInfo.DisplayName; }
         *      set { zoneInfo = TimeZoneInfo.FindSystemTimeZoneById(value); }
         *  }
         *
         *  public override DateTime Time => IPBanService.UtcNow;
         *
         *  public override DateTime FromSystemTime(DateTime systemTime)
         *  {
         *      return systemTime.ToUniversalTime();
         *  }
         *
         *  public DateTime CurrentTime { get; set; } = IPBanService.UtcNow;
         * }
         */

        static IPBanLog()
        {
            try
            {
                LogFactory factory = null;
                try
                {
                    factory = LogManager.LoadConfiguration(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
                }
                catch
                {
                    // if no config, exception is thrown that is OK
                }
                if (factory is null || factory.Configuration.AllTargets.Count == 0)
                {
                    string nlogConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nlog.config");
                    if (!File.Exists(nlogConfigPath))
                    {
                        string logLevel = "Warn";
                        foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                        {
                            if (a.FullName.IndexOf("nunit.framework", StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                logLevel = "Trace";
                                break;
                            }
                        }

                        Console.WriteLine("Creating default nlog.config file");

                        // storing this as a resource fails to use correct string in precompiled .exe with .net core, bug with Microsoft I think
                        string defaultNLogConfig = $@"<?xml version=""1.0""?>
<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" throwExceptions=""false"" internalLogToConsole=""false"" internalLogToConsoleError=""false"" internalLogLevel=""Trace"">
  <targets>
    <target name=""logfile"" xsi:type=""File"" fileName=""${{basedir}}/logfile.txt"" archiveNumbering=""Sequence"" archiveEvery=""Day"" maxArchiveFiles=""28"" encoding=""UTF-8""/>
    <target name=""console"" xsi:type=""Console""/>
  </targets>
  <rules>
    <logger name=""*"" minlevel=""{logLevel}"" writeTo=""logfile""/>
    <logger name=""*"" minlevel=""{logLevel}"" writeTo=""console""/>
  </rules>
</nlog>";
                        IPBanExtensionMethods.FileWriteAllTextWithRetry(nlogConfigPath, defaultNLogConfig);
                    }
                    if (File.Exists(nlogConfigPath))
                    {
                        factory = LogManager.LoadConfiguration(nlogConfigPath);
                    }
                    else
                    {
                        throw new IOException("Unable to create nlog configuration file, nlog.config file failed to write default config.");
                    }
                }
                logger = factory.GetCurrentClassLogger();
                //NLog.Time.TimeSource.Current = timeSource;
            }
            catch (Exception ex)
            {
                // log to console as no other logger is available
                Console.WriteLine("Failed to initialize logger: {0}", ex);
            }
        }