Example #1
0
        /// <summary>
        /// Retrieves a collection of <see cref="Network"/> objects that represent the networks defined for this machine.
        /// </summary>
        /// <param name="level">
        /// The <see cref="NetworkConnectivityLevels"/> that specify the connectivity level of the returned <see cref="Network"/> objects.
        /// </param>
        /// <returns>
        /// A <see cref="NetworkCollection"/> of <see cref="Network"/> objects.
        /// </returns>
        public static NetworkCollection GetNetworks(NetworkConnectivityLevels level)
        {
            // Throw PlatformNotSupportedException if the user is not running Vista or beyond
            //CoreHelpers.ThrowIfNotVista();

            return(new NetworkCollection(manager.GetNetworks(level)));
        }
Example #2
0
        public void SetWiFiPolicy()
        {
            Log.Info($"Setting WiFi Policy for Firewall");
            try
            {
                WlanClient wlan              = new WlanClient();
                var        intf              = wlan.Interfaces.First();
                var        profilename       = intf.CurrentConnection.profileName;
                var        manager           = new NetworkListManagerClass();
                var        connectedNetworks = manager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast <INetwork>();

                foreach (var network in connectedNetworks)
                {
                    var netname = network.GetName();
                    if (profilename == netname)
                    {
                        //network in profile list is same as network in wifi connection:
                        var cat = network.GetCategory();

                        if (cat != NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PRIVATE)
                        {
                            network.SetCategory(NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PRIVATE);
                            Log.Info($"Success setting WiFi Policy for Firewall to Private");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e, $"Problem setting WiFi Policy");
            }
        }
Example #3
0
        private void GetConnectedNetworkNames()
        {
            ConnectedNetworks = new List <string>();
            var manager           = new NetworkListManagerClass();
            var connectedNetworks = manager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast <INetwork>();

            foreach (var network in connectedNetworks)
            {
                ConnectedNetworks.Add(network.GetName());
            }
        }
Example #4
0
        public bool UpdateNetworks()
        {
            //  foreach (NetworkInterface adapter in Interfaces)
            // todo: get data rates etc... adapter.GetIPStatistics()

            if (!UpdateInterfaces)
            {
                return(false);
            }
            UpdateInterfaces = false;

            Dictionary <string, FirewallRule.Profiles> NetworkProfiles = new Dictionary <string, FirewallRule.Profiles>();

            foreach (INetwork network in netMgr.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast <INetwork>())
            {
                FirewallRule.Profiles FirewallProfile = FirewallRule.Profiles.Undefined;
                switch (network.GetCategory())
                {
                case NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PRIVATE:                 FirewallProfile = FirewallRule.Profiles.Private; break;

                case NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PUBLIC:                  FirewallProfile = FirewallRule.Profiles.Public; break;

                case NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_DOMAIN_AUTHENTICATED:    FirewallProfile = FirewallRule.Profiles.Domain; break;
                }

                foreach (INetworkConnection connection in network.GetNetworkConnections().Cast <INetworkConnection>())
                {
                    string id = ("{" + connection.GetAdapterId().ToString() + "}").ToLower();

                    NetworkProfiles.Add(id, FirewallProfile);
                }
            }

            //DefaultProfile = App.engine.FirewallManager.GetCurrentProfiles();

            AdapterInfoByIP.Clear();
            //AppLog.Debug("ListingNetworks:");

            Interfaces = NetworkInterface.GetAllNetworkInterfaces(); // this is a bit slow!
            foreach (NetworkInterface adapter in Interfaces)
            {
                try
                {
                    //AppLog.Debug("{0} {1} {2} {3}", adapter.Description, adapter.Id, adapter.NetworkInterfaceType.ToString(), adapter.OperationalStatus.ToString());

                    string id = adapter.Id.ToLower();

                    AdapterInfo Info = new AdapterInfo();
                    if (!NetworkProfiles.TryGetValue(id, out Info.Profile))
                    {
                        Info.Profile = DefaultProfile;
                    }

                    switch (adapter.NetworkInterfaceType)
                    {
                    case NetworkInterfaceType.Ethernet:
                    case NetworkInterfaceType.GigabitEthernet:
                    case NetworkInterfaceType.FastEthernetT:
                    case NetworkInterfaceType.FastEthernetFx:
                    case NetworkInterfaceType.Ethernet3Megabit:
                    case NetworkInterfaceType.TokenRing: Info.Type = FirewallRule.Interfaces.Lan; break;

                    case NetworkInterfaceType.Wireless80211: Info.Type = FirewallRule.Interfaces.Wireless; break;

                    case NetworkInterfaceType.Ppp: Info.Type = FirewallRule.Interfaces.RemoteAccess; break;

                    default: Info.Type = FirewallRule.Interfaces.All; break;
                    }

                    Info.Addresses = new List <UnicastIPAddressInformation>();
                    IPInterfaceProperties ip_info = adapter.GetIPProperties();
                    Info.GatewayAddresses = new List <IPAddress>();
                    foreach (var gw in ip_info.GatewayAddresses)
                    {
                        Info.GatewayAddresses.Add(gw.Address);
                    }
                    Info.DnsAddresses         = ip_info.DnsAddresses;
                    Info.DhcpServerAddresses  = ip_info.DhcpServerAddresses;
                    Info.WinsServersAddresses = ip_info.WinsServersAddresses;

                    foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses)
                    {
                        Info.Addresses.Add(ip);

                        // Sanitize IPv6 addresses
                        IPAddress _ip = new IPAddress(ip.Address.GetAddressBytes());

                        //AppLog.Debug("{2}({5}) has IP {0}/{3}/{4} has profile {1}", ip.Address.ToString(), ((FirewallRule.Profiles)Info.Profile).ToString(),
                        //    adapter.Description, ip.IPv4Mask.ToString(), ip.PrefixLength.ToString(), adapter.NetworkInterfaceType.ToString());

                        if (!AdapterInfoByIP.ContainsKey(_ip))
                        {
                            AdapterInfoByIP[_ip] = Info;
                        }
                    }
                }
                catch { } // in case a adapter becomes invalid justa fter the enumeration
            }
            //AppLog.Debug("+++");

            NetworksChanged?.Invoke(this, new EventArgs());
            return(true);
        }
Example #5
0
 /// <summary>
 /// Retrieves a collection of <see cref="Microsoft.SDK.Samples.VistaBridge.Library.Network.Network"/> objects that represent the networks defined for this machine.
 /// </summary>
 /// <param name="level">
 /// The <see cref="Microsoft.SDK.Samples.VistaBridge.Library.Network.NetworkConnectivityLevels"/> that specify the connectivity level of the returned <see cref="Microsoft.SDK.Samples.VistaBridge.Library.Network.Network"/> objects.
 /// </param>
 /// <returns>
 /// A <see cref="Microsoft.SDK.Samples.VistaBridge.Library.Network.NetworkCollection"/> of <see cref="Microsoft.SDK.Samples.VistaBridge.Library.Network.Network"/> objects.
 /// </returns>
 public static NetworkCollection GetNetworks(NetworkConnectivityLevels level)
 {
     return(new NetworkCollection(manager.GetNetworks(level)));
 }
Example #6
0
        public FirewallRule.Profiles DefaultProfile = FirewallRule.Profiles.Public; // default windows behavioure: default profile is public

        public void UpdateNetworks()
        {
            LastNetworkUpdate = MiscFunc.GetTickCount64();

            Dictionary <string, FirewallRule.Profiles> NetworkProfiles = new Dictionary <string, FirewallRule.Profiles>();

            foreach (INetwork network in netMgr.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast <INetwork>())
            {
                FirewallRule.Profiles FirewallProfile = FirewallRule.Profiles.Undefined;
                switch (network.GetCategory())
                {
                case NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PRIVATE:                 FirewallProfile = FirewallRule.Profiles.Private; break;

                case NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PUBLIC:                  FirewallProfile = FirewallRule.Profiles.Public; break;

                case NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_DOMAIN_AUTHENTICATED:    FirewallProfile = FirewallRule.Profiles.Domain; break;
                }

                foreach (INetworkConnection connection in network.GetNetworkConnections().Cast <INetworkConnection>())
                {
                    string id = ("{" + connection.GetAdapterId().ToString() + "}").ToLower();

                    NetworkProfiles.Add(id, FirewallProfile);
                }
            }

            //DefaultProfile = App.engine.FirewallManager.GetCurrentProfiles();

            AdapterInfoByIP.Clear();
            //AppLog.Debug("ListingNetworks:");

            foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces()) // this is a bit slow!
            {
                string id = adapter.Id.ToLower();

                AdapterInfo Info = new AdapterInfo();
                if (!NetworkProfiles.TryGetValue(id, out Info.Profile))
                {
                    Info.Profile = DefaultProfile;
                }

                switch (adapter.NetworkInterfaceType)
                {
                case NetworkInterfaceType.Ethernet:
                case NetworkInterfaceType.GigabitEthernet:
                case NetworkInterfaceType.FastEthernetT:
                case NetworkInterfaceType.FastEthernetFx:
                case NetworkInterfaceType.Ethernet3Megabit:
                case NetworkInterfaceType.TokenRing: Info.Type = FirewallRule.Interfaces.Lan; break;

                case NetworkInterfaceType.Wireless80211: Info.Type = FirewallRule.Interfaces.Wireless; break;

                case NetworkInterfaceType.Ppp: Info.Type = FirewallRule.Interfaces.RemoteAccess; break;

                default: Info.Type = FirewallRule.Interfaces.All; break;
                }

                Info.Addresses = new List <UnicastIPAddressInformation>();
                IPInterfaceProperties ip_info = adapter.GetIPProperties();
                Info.GatewayAddresses = new List <IPAddress>();
                foreach (var gw in ip_info.GatewayAddresses)
                {
                    Info.GatewayAddresses.Add(gw.Address);
                }
                Info.DnsAddresses         = ip_info.DnsAddresses;
                Info.DhcpServerAddresses  = ip_info.DhcpServerAddresses;
                Info.WinsServersAddresses = ip_info.WinsServersAddresses;

                foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses)
                {
                    Info.Addresses.Add(ip);

                    // Sanitize IPv6 addresses
                    IPAddress _ip = new IPAddress(ip.Address.GetAddressBytes());

                    //AppLog.Debug("{2}({5}) has IP {0}/{3}/{4} has profile {1}", ip.Address.ToString(), ((FirewallRule.Profiles)Info.Profile).ToString(),
                    //    adapter.Description, ip.IPv4Mask.ToString(), ip.PrefixLength.ToString(), adapter.NetworkInterfaceType.ToString());

                    if (!AdapterInfoByIP.ContainsKey(_ip))
                    {
                        AdapterInfoByIP[_ip] = Info;
                    }
                }
            }
            //AppLog.Debug("+++");
        }
Example #7
0
        private async void Monitor_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                //INIT:
                var Document = File.ReadAllText(DockerComposeFile);
                var input    = new StringReader(Document);

                WebClient client = new TimeOutWebClient();


                var KnownContainerCount = 0;

                // Load the stream
                var yaml = new YamlStream();
                yaml.Load(input);
                var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;

                foreach (var entry in mapping.Children)
                {
                    if ((entry.Key as YamlScalarNode).Value == "services")
                    {
                        foreach (var service in (entry.Value as YamlMappingNode).Children)
                        {
                            KnownContainerCount++;
                        }
                    }
                }

                var        wifi = new Wifi();
                WlanClient wlan = new WlanClient();


                while (true)
                {
                    try
                    {
                        List <ContainerListResponse> containers = (await dockerclient.Containers.ListContainersAsync(new ContainersListParameters()
                        {
                            All = true,
                            Filters = new Dictionary <string, IDictionary <string, bool> >()
                            {
                                ["status"] = new Dictionary <string, bool>()
                                {
                                    { "running", true }
                                },
                                ["label"] = new Dictionary <string, bool>()
                                {
                                    { "com.docker.compose.project=bootleggerlocal", true }
                                }
                            }
                        })).ToList();

                        //TODO: Check containers against the known list:

                        if (containers.Count != KnownContainerCount)
                        {
                            if (!CurrentErrors.Contains(CONTAINEREXCEPTION))
                            {
                                CurrentErrors.Add(CONTAINEREXCEPTION);
                            }
                        }
                        else
                        {
                            CurrentErrors.Remove(CONTAINEREXCEPTION);
                        }

                        //CHECK WIFI CONNECTION:


                        //CHECK IP
                        //get ip information:
                        ManagementClass            objMC  = new ManagementClass("Win32_NetworkAdapterConfiguration");
                        ManagementObjectCollection objMOC = objMC.GetInstances();
                        bool ipaddressok = false;
                        //string actualip = "none found";
                        foreach (ManagementObject objMO in objMOC)
                        {
                            if ((bool)objMO["IPEnabled"])
                            {
                                var ip = (objMO["IPAddress"] as string[]);

                                if (ip?[0]?.Equals(IP) ?? false)
                                {
                                    ipaddressok = true;
                                    //actualip = "10.10.10.1";
                                }
                            }
                        }

                        if (!ipaddressok)
                        {
                            if (!CurrentErrors.Contains(IPEXCEPTION))
                            {
                                CurrentErrors.Add(IPEXCEPTION);
                            }
                        }
                        else
                        {
                            CurrentErrors.Remove(IPEXCEPTION);
                        }



                        //CHECK DISK SPACE:

                        try
                        {
                            DriveInfo driveInfo = new DriveInfo(@"C:");
                            long      FreeSpace = driveInfo.AvailableFreeSpace / 1024 / 1024;
                            if (FreeSpace < 1000)
                            {
                                if (!CurrentErrors.Contains(DRIVESPACEXCEPTION))
                                {
                                    CurrentErrors.Add(DRIVESPACEXCEPTION);
                                }
                            }
                            else
                            {
                                CurrentErrors.Remove(DRIVESPACEXCEPTION);
                            }
                        }
                        catch (System.IO.IOException)
                        {
                            //Console.WriteLine(errorMesage);
                        }

                        //WIFI:
                        if (wifi.ConnectionStatus != WifiStatus.Connected)
                        {
                            if (!CurrentErrors.Contains(WIFIEXCEPTION))
                            {
                                CurrentErrors.Add(WIFIEXCEPTION);
                            }
                        }
                        else
                        {
                            CurrentErrors.Remove(WIFIEXCEPTION);
                            //wifi is connected, so check for public/private



                            //check for network on right policy otherwise firewall rule wont work...
                            if (CurrentInstallerType == InstallerType.HYPER_V)
                            {
                                var  manager           = new NetworkListManagerClass();
                                var  connectedNetworks = manager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast <INetwork>();
                                var  intf          = wlan.Interfaces.First();
                                var  profilename   = intf.CurrentConnection.profileName;
                                bool matchespolicy = false;

                                foreach (var network in connectedNetworks)
                                {
                                    //Console.WriteLine(network.GetName() + " ");
                                    if (profilename == network.GetName())
                                    {
                                        //network in profile list is same as network in wifi connection:

                                        var cat = network.GetCategory();

                                        if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PRIVATE)
                                        {
                                            matchespolicy = true;
                                        }
                                    }
                                }

                                if (!matchespolicy)
                                {
                                    if (!CurrentErrors.Contains(WIFIPOLICYEXCEPTION))
                                    {
                                        CurrentErrors.Add(WIFIPOLICYEXCEPTION);
                                    }
                                }
                                else
                                {
                                    CurrentErrors.Remove(WIFIPOLICYEXCEPTION);
                                }
                            }
                        }


                        OnRunWarning?.Invoke(CurrentErrors);

                        //CHECK APPLICATION
                        bool connected = false;
                        try
                        {
                            var result = await client.DownloadStringTaskAsync($"http://{IP}:{PORT}/status");

                            connected = true;
                        }
                        catch
                        {
                        }

                        if (!connected)
                        {
                            if (!CurrentErrors.Contains(SERVEREXCEPTION))
                            {
                                CurrentErrors.Add(SERVEREXCEPTION);
                            }
                        }
                        else
                        {
                            CurrentErrors.Remove(SERVEREXCEPTION);
                        }
                    }
                    catch (Exception ex)
                    {
                        CurrentErrors.Add(new NamedException()
                        {
                            Name = "Unknown", Description = ex.Message
                        });
                    }
                    finally
                    {
                        OnRunWarning?.Invoke(CurrentErrors);
                    }

                    Thread.Sleep(5000);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Monitor_DoWork(sender, e);
            }
        }