private void addIPPort()
        {
            var conn = new ConnectionOptions
            {
                EnablePrivileges = true,
                Impersonation    = ImpersonationLevel.Impersonate
            };

            var mPath = new ManagementPath("Win32_TCPIPPrinterPort");

            var mScope = new ManagementScope(@"\\.\root\cimv2", conn)
            {
                Options =
                {
                    EnablePrivileges = true,
                    Impersonation    = ImpersonationLevel.Impersonate
                }
            };

            var mPort = new ManagementClass(mScope, mPath, null).CreateInstance();

            var remotePort = 9100;

            try
            {
                if (IP != null && IP.Contains(":"))
                {
                    var arIP = IP.Split(':');
                    if (arIP.Length == 2)
                    {
                        remotePort = int.Parse(arIP[1]);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(LogName, "Could not parse port from IP");
                Log.Error(LogName, ex);
            }

            mPort.SetPropertyValue("Name", Port);
            mPort.SetPropertyValue("Protocol", 1);
            mPort.SetPropertyValue("HostAddress", IP);
            mPort.SetPropertyValue("PortNumber", remotePort);
            mPort.SetPropertyValue("SNMPEnabled", false);

            var put = new PutOptions
            {
                UseAmendedQualifiers = true,
                Type = PutType.UpdateOrCreate
            };

            mPort.Put(put);
        }
        /// <summary>
        /// Кеш настроек WhiteList
        /// </summary>
        public static void UpdateCache()
        {
            // Оригинальные настройки WhiteList
            var conf = Service.Get <JsonDB>().WhiteList;

            #region Локальный метод - "JoinMass"
            string JoinMass(List <string> mass, bool IsUserAgent = false, bool IsIPv6 = false)
            {
                if (mass == null || mass.Count == 0)
                {
                    return("^$");
                }

                if (IsUserAgent || IsIPv6)
                {
                    return($"({string.Join("|", mass)})");
                }

                return($"^({string.Join("|", mass)})$");
            }

            #endregion

            #region Обновляем список IPv4/6
            // Базовый список IPv6
            var IPv6ToMass = new List <string>()
            {
                "::1"
            };

            // Базовый список IPv4
            var IPv4ToMass = new List <CidrToIPv4>();
            IPv4ToMass.Add(IPNetwork.IPv4ToRange("127.0.0.1"));
            IPv4ToMass.Add(IPNetwork.IPv4ToRange("8.8.4.4"));
            IPv4ToMass.Add(IPNetwork.IPv4ToRange("8.8.8.8"));
            IPv4ToMass.Add(IPNetwork.IPv4ToRange("192.168.0.1", "192.168.0.254"));

            // Пользовательский список IPv4/6
            foreach (string IP in conf.Where(i => i.Type == WhiteListType.IPv4Or6).Select(i => i.Value))
            {
                if (IP.Contains(":"))
                {
                    // IPv6
                    if (IPNetwork.CheckingSupportToIPv4Or6(IP, out var ipnetwork))
                    {
                        IPv6ToMass.Add(IPNetwork.IPv6ToRegex(ipnetwork.FirstUsable));
                    }
                }
                else
                {
                    // IPv4
                    if (IPNetwork.CheckingSupportToIPv4Or6(IP, out var ipnetwork))
                    {
                        if (IPNetwork.IPv4ToRange(ipnetwork.FirstUsable, ipnetwork.LastUsable) is var item && item.FirstUsable != 0)
                        {
                            IPv4ToMass.Add(item);
                        }
                    }
                }
            }

            // Обновляем базу
            IPv4ToRange = IPv4ToMass.OrderBy(i => i.FirstUsable).ToList();
            IPv6ToRegex = JoinMass(IPv6ToMass, IsIPv6: true);
            #endregion

            // Базовый список PTR
            List <string> PTRs = new List <string>(conf.Where(i => i.Type == WhiteListType.PTR).Select(i => i.Value).ToArray());
            PTRs.Add(@".*\.(yandex.(ru|net|com)|googlebot.com|google.com|mail.ru|search.msn.com)");

            // Создаем кеш
            PtrRegex        = JoinMass(PTRs);
            UserAgentRegex  = JoinMass(conf.Where(i => i.Type == WhiteListType.UserAgent).Select(i => i.Value).ToList(), IsUserAgent: true);
            LastUpdateCache = DateTime.Now;
        }
Beispiel #3
0
        public override void Add()
        {
            Log.Entry(LogName, "Attempting to add printer:");
            Log.Entry(LogName, string.Format("--> Name = {0}", Name));
            Log.Entry(LogName, string.Format("--> IP = {0}", IP));
            Log.Entry(LogName, string.Format("--> Port = {0}", Port));

            if (string.IsNullOrEmpty(IP) || !Name.StartsWith("\\\\"))
            {
                return;
            }

            if (IP.Contains(":"))
            {
                var arIP = IP.Split(':');
                if (arIP.Length == 2)
                {
                    IP   = arIP[0];
                    Port = arIP[1];
                }
            }

            var conn = new ConnectionOptions
            {
                EnablePrivileges = true,
                Impersonation    = ImpersonationLevel.Impersonate
            };

            var mPath = new ManagementPath("Win32_TCPIPPrinterPort");

            var mScope = new ManagementScope(@"\\.\root\cimv2", conn)
            {
                Options =
                {
                    EnablePrivileges = true,
                    Impersonation    = ImpersonationLevel.Impersonate
                }
            };

            var mPort = new ManagementClass(mScope, mPath, null).CreateInstance();

            if (mPort != null)
            {
                mPort.SetPropertyValue("Name", "IP_" + IP);
                mPort.SetPropertyValue("Protocol", 1);
                mPort.SetPropertyValue("HostAddress", IP);
                mPort.SetPropertyValue("PortNumber", Port);
                mPort.SetPropertyValue("SNMPEnabled", false);

                var put = new PutOptions
                {
                    UseAmendedQualifiers = true,
                    Type = PutType.UpdateOrCreate
                };
                mPort.Put(put);
            }

            if (!Name.StartsWith("\\\\"))
            {
                return;
            }

            // Add per machine printer connection
            var proc = Process.Start("rundll32.exe", " printui.dll,PrintUIEntry /ga /n " + Name);

            if (proc != null)
            {
                proc.WaitForExit(120000);
            }
            // Add printer network connection, download the drivers from the print server
            proc = Process.Start("rundll32.exe", " printui.dll,PrintUIEntry /in /n " + Name);
            if (proc != null)
            {
                proc.WaitForExit(120000);
            }
        }
Beispiel #4
0
        public static void RunBlocked(JsonDB jsonDB, IMemoryCache memoryCache)
        {
            if (IsRunBlocked || BlockedIP.IsEmpty)
            {
                return;
            }
            IsRunBlocked = true;

            //
            bool BlockToIPtables = jsonDB.AntiDdos.BlockToIPtables;

            #region Получаем текущий список заблокированных IP
            string IPv4 = string.Empty;
            string IPv6 = string.Empty;

            if (BlockToIPtables)
            {
                IPv4 = new Bash().Run("iptables -L -n -v | grep \"ISPCore_\" | awk '{print $8}'");
                IPv6 = new Bash().Run("ip6tables -L -n -v | grep \"ISPCore_\" | awk '{print $8}'");
            }
            #endregion

            // Блокируем IP
            Parallel.For(0, BlockedIP.Count, new ParallelOptions {
                MaxDegreeOfParallelism = jsonDB.Base.CountParallel
            }, (index, state) =>
            {
                try
                {
                    if (BlockedIP.TryDequeue(out string IP))
                    {
                        // IP уже заблокирован
                        if (IPv4.Contains(IP) || IPv6.Contains(IP))
                        {
                            return;
                        }

                        #region DNSLookup
                        string HostName = null;
                        try
                        {
                            if (jsonDB.AntiDdos.DNSLookupEnabled)
                            {
                                // Получаем имя хоста по IP
                                var host = Dns.GetHostEntryAsync(IP).Result;

                                // Получаем IP хоста по имени
                                host = Dns.GetHostEntryAsync(host.HostName).Result;

                                // Проверяем имя хоста и IP на совпадение
                                if (host.AddressList.Where(i => i.ToString() == IP).FirstOrDefault() != null)
                                {
                                    HostName = host.HostName;

                                    // Проверяем имя хоста на белый список DNSLookup
                                    if (Regex.IsMatch(host.HostName, WhiteUserList.PtrRegex, RegexOptions.IgnoreCase))
                                    {
                                        // Добовляем IP в белый список на неделю
                                        WhitePtr.Add(IP, host.HostName, DateTime.Now.AddDays(7));
                                        Trigger.OnAddToWhitePtr((IP, HostName, 7));

                                        // Удаляем временное значение с кеша
                                        memoryCache.Remove($"AntiDdosCheckBlockedIP-{IP}");
                                        return;
                                    }
                                }
                            }
                        }
                        catch { }
                        #endregion

                        // Добовляем IP в IPtables
                        if (BlockToIPtables)
                        {
                            string comandTables = IP.Contains(":") ? "ip6tables" : "iptables";
                            new Bash().Run($"{comandTables} -A INPUT -s {IP} -m comment --comment \"ISPCore_{DateTime.Now.AddMinutes(jsonDB.AntiDdos.BlockingTime).ToString("yyy-MM-ddTHH:mm:00")}\" -j REJECT");
                        }

                        //
                        Trigger.OnBlockedIP((IP, HostName, jsonDB.AntiDdos.BlockingTime));

                        // Пишем IP в базу
                        if (jsonDB.AntiDdos.Jurnal)
                        {
                            (string Country, string City, string Region)geo = ("Disabled", "Disabled", "Disabled");
                            if (jsonDB.AntiDdos.GeoIP)
                            {
                                geo = GeoIP2.City(IP);
                            }

                            WriteLogTo.SQL(new Jurnal()
                            {
                                City     = geo.City,
                                Country  = geo.Country,
                                Region   = geo.Region,
                                HostName = HostName,
                                IP       = IP,
                                Time     = DateTime.Now
                            });
                        }

                        // Обновляем кеш
                        int BlockingTime = jsonDB.AntiDdos.BlockingTime > 10 ? 10 : jsonDB.AntiDdos.BlockingTime;
                        memoryCache.Set($"AntiDdosCheckBlockedIP-{IP}", (byte)0, TimeSpan.FromMinutes(BlockingTime));
                    }
                }