Beispiel #1
0
 public LocationNetwork(Guid id, string ipAddress, byte cidr)
 {
     Id   = id;
     Cidr = cidr;
     IPNetwork.TryParse(ipAddress, cidr, out var network);
     Network = network;
 }
Beispiel #2
0
        private static bool TryParseIPNetwork(string ip, CidrParseEnum cidrParseEnum, byte cidr, out IPNetwork ipn)
        {
            IPNetwork ipnetwork = null;

            if (cidrParseEnum == CidrParseEnum.Default)
            {
                if (!IPNetwork.TryParse(ip, out ipnetwork))
                {
                    ipn = null;
                    return(false);
                }
            }
            else if (cidrParseEnum == CidrParseEnum.Value)
            {
                if (!IPNetwork.TryParse(ip, cidr, out ipnetwork))
                {
                    if (!IPNetwork.TryParse(ip, out ipnetwork))
                    {
                        ipn = null;
                        return(false);
                    }
                }
            }
            ipn = ipnetwork;
            return(true);
        }
        private IDictionary <IPNetwork, string> CreateSubnetDictionary()
        {
            var subnets = new Dictionary <IPNetwork, string>();

            foreach (string filePath in AzureSpeedConstants.AzureIpRangeFileList.Split(';'))
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(this.dataFilePath + @"\Data\IpRangeFiles\Azure\" + filePath);
                var root = xmlDoc.DocumentElement;
                foreach (XmlElement ele in root)
                {
                    string region = ele.GetAttribute("Name");
                    foreach (XmlElement ipRange in ele)
                    {
                        var subnet = ipRange.GetAttribute("Subnet");
                        if (IPNetwork.TryParse(subnet, out IPNetwork net))
                        {
                            if (!subnets.ContainsKey(net))
                            {
                                subnets.Add(net, region);
                            }
                        }
                    }
                }
            }

            return(subnets);
        }
        /// <summary>
        /// Parse a single line.
        /// </summary>
        /// <param name="line">The line to parse.</param>
        private void ParseLine(string line)
        {
            string trimmedLine = line.Trim();

            if ((trimmedLine.Length == 0) || trimmedLine.StartsWith('#'))
            {
                // empty or comment line
                return;
            }

            var splitLine = trimmedLine.Split(new [] { ' ', '#' }, StringSplitOptions.RemoveEmptyEntries);

            if (splitLine.Length == 0)
            {
                // line somehow doesn't split at all (this normally shouldn't happen)
                return;
            }

            IPNetwork parsedNetwork = null;

            if (!IPNetwork.TryParse(splitLine[0], out parsedNetwork))
            {
                log.Warn($"'{this.FileToParse}' line #{this.currentLine}: Is not a comment or empty but cannot be parsed as valid IP network. It will be ignored. Line content '{line}'");
            }

            this.parsedNetworksBacking.Add(parsedNetwork);
        }
        private IDictionary <IPNetwork, string> CreateSubnetDictionary()
        {
            var subnets = new Dictionary <IPNetwork, string>();

            foreach (string filePath in this.azureIpFileList.Split(';'))
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(this.dataFilePath + @"\Data\IpRangeFiles\Azure\" + filePath);
                var root = xmlDoc.DocumentElement;
                foreach (XmlElement ele in root)
                {
                    string region = ele.GetAttribute("Name");
                    foreach (XmlElement ipRange in ele)
                    {
                        var       subnet = ipRange.GetAttribute("Subnet");
                        IPNetwork net;
                        if (IPNetwork.TryParse(subnet, out net))
                        {
                            if (!subnets.ContainsKey(net))
                            {
                                subnets.Add(net, region);
                            }
                        }
                    }
                }
            }

            // Get AWS ip range data
            string json = File.ReadAllText(this.dataFilePath + @"\Data\IpRangeFiles\AWS\" + this.awsIpFile);

            var awsIpRangeData = JsonConvert.DeserializeObject <AwsIpRangeData>(json);

            foreach (var prefix in awsIpRangeData.Prefixes)
            {
                IPNetwork net;
                if (IPNetwork.TryParse(prefix.IpPrefix, out net))
                {
                    if (!subnets.ContainsKey(net))
                    {
                        subnets.Add(net, prefix.Region);
                    }
                }
            }

            // Get AliCloud ip range data
            string[] lines = File.ReadAllLines(this.dataFilePath + @"\Data\IpRangeFiles\AliCloud\" + this.aliCloudIpFile);
            foreach (var line in lines)
            {
                IPNetwork net;
                if (IPNetwork.TryParse(line, out net))
                {
                    if (!subnets.ContainsKey(net))
                    {
                        subnets.Add(net, "alicloud");
                    }
                }
            }

            return(subnets);
        }
        /// <inheritdoc />
        public IHamnetDbSubnets QuerySubnets()
        {
            var connection = this.GetConnection();
            List <IHamnetDbSubnet> subnets = new List <IHamnetDbSubnet>();

            using (MySqlCommand cmd = new MySqlCommand("SELECT ip FROM hamnet_subnet;", this.connection))
            {
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var       networkCidr = reader.GetString("ip");
                        IPNetwork ipNet;
                        if (!IPNetwork.TryParse(networkCidr, out ipNet))
                        {
                            log.Error($"Cannot convert retrieved string '{networkCidr}' to a valid IP network. This entry will be skipped.");
                            continue;
                        }

                        subnets.Add(new HamnetDbSubnet(ipNet));
                    }
                }
            }

            return(new HamnetDbSubnets(subnets));
        }
        public FindDevices()
        {
            InitializeComponent();
            DataContext = this;
            Closed     += FindDevices_Closed;

            Properties.Settings.Default.Upgrade();
            Properties.Settings.Default.Save();

            // Load Address Range
            AddressFrom = Properties.Settings.Default.AddressFrom;
            AddressTo   = Properties.Settings.Default.AddressTo;
            if (string.IsNullOrEmpty(AddressFrom) || string.IsNullOrEmpty(AddressTo))
            {
                var hostAddress = GetHostAddress();
                if (hostAddress != null)
                {
                    IPNetwork ip;
                    if (IPNetwork.TryParse(hostAddress.ToString(), out ip))
                    {
                        var addresses = IPNetwork.ListIPAddress(ip);
                        if (addresses != null)
                        {
                            AddressFrom = addresses.First().ToString();
                            AddressTo   = addresses.Last().ToString();
                        }
                    }
                }
            }

            // Load Port Range
            PortFrom = Properties.Settings.Default.PortFrom;
            PortTo   = Properties.Settings.Default.PortTo;
        }
Beispiel #8
0
        private IPAddress[] GetDefaultAddresses()
        {
            var l = new List <IPAddress>();

            var hosts = GetHostAddresses();

            if (hosts != null)
            {
                foreach (var host in hosts)
                {
                    IPNetwork ip;
                    if (IPNetwork.TryParse(host.ToString(), out ip))
                    {
                        var addresses = IPNetwork.ListIPAddress(ip);
                        if (addresses != null)
                        {
                            foreach (var address in addresses)
                            {
                                l.Add(address);
                            }
                        }
                    }
                }
            }

            return(l.ToArray());
        }
        private static void ParseConfigList(
            string fullConfigEntry, string filterName, out List <IPNetwork> networks, out List <IPEndPoint> endPoints)
        {
            // Parse blacklist
            string[] configBlacklistEntries
                = fullConfigEntry.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            configBlacklistEntries = configBlacklistEntries.Select(e => e.Trim()).ToArray();

            networks  = new List <IPNetwork>();
            endPoints = new List <IPEndPoint>();

            foreach (string configEntry in configBlacklistEntries)
            {
                if (configEntry.Contains("/"))
                {
                    IPNetwork network;

                    if (!IPNetwork.TryParse(configEntry, out network))
                    {
                        m_log.ErrorFormat(
                            "[OUTBOUND URL FILTER]: Entry [{0}] is invalid network for {1}", configEntry, filterName);

                        continue;
                    }

                    networks.Add(network);
                }
                else
                {
                    Uri configEntryUri;

                    if (!Uri.TryCreate("http://" + configEntry, UriKind.Absolute, out configEntryUri))
                    {
                        m_log.ErrorFormat(
                            "[OUTBOUND URL FILTER]: EndPoint entry [{0}] is invalid endpoint for {1}",
                            configEntry, filterName);

                        continue;
                    }

                    IPAddress[] addresses = Dns.GetHostAddresses(configEntryUri.Host);

                    foreach (IPAddress addr in addresses)
                    {
                        if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            //                        m_log.DebugFormat("[OUTBOUND URL FILTER]: Found address [{0}] in config", addr);

                            IPEndPoint configEntryEp = new IPEndPoint(addr, configEntryUri.Port);
                            endPoints.Add(configEntryEp);

                            //                        m_log.DebugFormat("[OUTBOUND URL FILTER]: Added blacklist exception [{0}]", configEntryEp);
                        }
                    }
                }
            }
        }
Beispiel #10
0
        internal static bool Validate(string ipAddress)
        {
            if (IPNetwork.TryParse(ipAddress, out var output))
            {
                return(output.AddressFamily == AddressFamily.InterNetworkV6);
            }

            return(false);
        }
    public bool IsAllowListed(IPAddress clientIpAddress, string allowedIpString)
    {
        if (IPNetwork.TryParse(allowedIpString, out IPNetwork allowedIp) && allowedIp.Contains(clientIpAddress))
        {
            return(true);
        }

        return(false);
    }
Beispiel #12
0
        internal IPNetwork ResolveAddresses(string ipaddress)
        {
            if (IPNetwork.TryParse(ipaddress, out IPNetwork ipnetwork1))
            {
                return(ipnetwork1);
            }

            return(null);
        }
Beispiel #13
0
 public void SetIpv4Address(Ipv4AddressAndMask ipv4Address)
 {
     if (IPNetwork.TryParse(ipv4Address.Ipv4Address, ipv4Address.Ipv4SubnetMask, out IPNetwork network))
     {
         this.Ipv4AddressAndMask = new Ipv4AddressAndMask(network.FirstUsable.ToString(), network.Netmask.ToString());
     }
     else
     {
         throw new AttachmentDomainException($"Invalid IPv4 address/mask - '{ipv4Address.Ipv4Address}, {ipv4Address.Ipv4SubnetMask}'");
     }
 }
        public bool IsIpAllowListed(IPAddress clientIpAddress)
        {
            foreach (var allowedIpString in _basicAuthSettings.AllowedIPs)
            {
                if (IPNetwork.TryParse(allowedIpString, out IPNetwork allowedIp) && allowedIp.Contains(clientIpAddress))
                {
                    return(true);
                }
            }

            return(false);
        }
        public IEnumerable <(string ipAddress, string fqdn)> ExpandScope(string scopeText, bool doNotExpandNamesToIPs)
        {
            scopeText = scopeText ?? throw new ArgumentNullException(nameof(scopeText));
            scopeText = scopeText.Replace(" ", string.Empty);
            scopeText = scopeText.Replace("\t", string.Empty);

            var lines = scopeText.Split(",;\r\n".ToCharArray());

            var scope = new HashSet <(string ipAddress, string fqdn)>();

            foreach (var line in lines)
            {
                if (!string.IsNullOrWhiteSpace(line))
                {
                    if (line.Contains("/") && IPNetwork.TryParse(line, out var ipNetwork))
                    {
                        using (var ipAddresses = ipNetwork.ListIPAddress())
                        {
                            foreach (var ipAddress in ipAddresses)
                            {
                                if (ipAddress.AddressFamily == AddressFamily.InterNetwork && (ipAddress.Equals(ipNetwork.Network) || ipAddress.Equals(ipNetwork.Broadcast)))
                                {
                                    continue;
                                }

                                scope.Add((ipAddress.ToString(), ipAddress.AddressFamily == AddressFamily.InterNetworkV6 ? $"{ipAddress.ToString().Replace(':', '-')}.ipv6-literal.net" : string.Empty));
                            }
                        }
                    }
                    else if (IPAddress.TryParse(line, out var ipAddress))
                    {
                        scope.Add((ipAddress.ToString(), ipAddress.AddressFamily == AddressFamily.InterNetworkV6 ? $"{ipAddress.ToString().Replace(':', '-')}.ipv6-literal.net" : string.Empty));
                    }
                    else
                    {
                        if (doNotExpandNamesToIPs)
                        {
                            scope.Add((string.Empty, line));
                        }
                        else if (_dnsUtilitiesService.TryResolveHost(line, out var ipAddresses))
                        {
                            foreach (var address in ipAddresses)
                            {
                                scope.Add((address.ToString(), address.AddressFamily == AddressFamily.InterNetworkV6 ? $"{address.ToString().Replace(':', '-')}.ipv6-literal.net" : string.Empty));
                            }
                        }
                    }
                }
            }

            return(scope);
        }
Beispiel #16
0
        public static Dictionary <string, string> ReturnMatchedIPRange(List <string> ips, List <Value> azureIps)
        {
            Dictionary <string, string> matchedIps = new Dictionary <string, string>();

            foreach (var ip in ips)
            {
                bool      ipFound               = false;
                IPNetwork incomingNetwork       = null;
                IPAddress incomingIp            = IsValidIP(ip) ? IPAddress.Parse(ip) : null;
                bool      incomingNetworkParsed = incomingIp == null?IPNetwork.TryParse(ip, out incomingNetwork) : false;

                if (incomingIp != null || incomingNetwork != null)
                {
                    foreach (var azureip in azureIps)
                    {
                        foreach (var subnet in azureip.properties.addressPrefixes)
                        {
                            IPNetwork network = IPNetwork.Parse(subnet);


                            if (((incomingIp != null && network.Contains(incomingIp)) ||
                                 (incomingNetwork != null && network.Contains(incomingNetwork))) &&
                                !ipFound)
                            {
                                matchedIps.Add(ip, $"{subnet} - {azureip.name}");
                                ipFound = true;
                                break;
                            }
                        }
                    }

                    if (!ipFound)
                    {
                        if (!matchedIps.ContainsKey(ip))
                        {
                            matchedIps.Add(ip, "No Match");
                        }
                    }
                }
                else
                {
                    if (!matchedIps.ContainsKey(ip))
                    {
                        matchedIps.Add(ip, "No Match");
                    }
                }
            }


            return(matchedIps);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value is null)
            {
                return(ValidationResult.Success);
            }

            if (value is string str && IPNetwork.TryParse(str, out _))
            {
                return(ValidationResult.Success);
            }

            return(new ValidationResult($"The value {value} is not a correct IP network."));
        }
        public (ValidationResult, MarkupString) ValidateSubnet(string s)
        {
            if (s.Length == 0)
            {
                return(ValidationResult.Undefined, new MarkupString(""));
            }

            bool valid = IPNetwork.TryParse(s, out IPNetwork parsed);

            if (valid)
            {
                return(ValidationResult.Valid, new MarkupString($"Parsed: {parsed}"));
            }

            return(ValidationResult.Invalid, new MarkupString("Parse failure"));
        }
        public bool Validate(out ImmutableArray <string> errors, CRUDOperation operation = CRUDOperation.Create)
        {
            var builder = ImmutableArray.CreateBuilder <string>();

            var result = ValitRules <OpenVPNConfigUpdateRequest>
                         .Create()
                         // Ensure the listeners array exists in the request.
                         .Ensure(m => m.Listeners, _ => _
                                 .Required()
                                 .WithMessage(FormatValidationError(Errors.FIELD_REQUIRED, "listeners"))
                                 .MinItems(1)
                                 .WithMessage(FormatValidationError(Errors.FIELD_MINLENGTH, "1")))
                         // IPAddress / IPNetwork validation, after this, no further "TryParse" is required.
                         .EnsureFor(m => m.Listeners, OpenVPNListener.validator)
                         .Ensure(m => m.AllowMultipleConnectionsFromSameClient, _ => _
                                 .Required()
                                 .WithMessage(FormatValidationError(Errors.FIELD_REQUIRED, "allowMultipleConnectionsFromSameClient")))
                         .Ensure(m => m.ClientToClient, _ => _
                                 .Required()
                                 .WithMessage(FormatValidationError(Errors.FIELD_REQUIRED, "clientToClient")))
                         .Ensure(m => m.MaxClients, _ => _
                                 .Required()
                                 .WithMessage(FormatValidationError(Errors.FIELD_REQUIRED, "maxClients"))
                                 .IsGreaterThanOrEqualTo(512)
                                 .WithMessage(FormatValidationError(Errors.FIELD_MINLENGTH, "512"))
                                 .IsLessThanOrEqualTo(2048)
                                 .WithMessage(FormatValidationError(Errors.FIELD_MAXLENGTH, "2048")))
                         .Ensure(m => m.DhcpOptions, _ => _
                                 .Required()
                                 .WithMessage(FormatValidationError(Errors.FIELD_REQUIRED, "dhcpOptions")))
                         .Ensure(m => m.PushedNetworks, _ => _
                                 .Required()
                                 .WithMessage(FormatValidationError(Errors.FIELD_REQUIRED, "pushedNetworks")))
                         .EnsureFor(m => m.PushedNetworks, _ => _
                                    .Satisfies(x => IPNetwork.TryParse(x, out var _))
                                    .WithMessage(FormatValidationError(Errors.FIELD_INVALID, "pushedNetworks")))
                         .Ensure(m => m.RedirectGateway, _ => _
                                 .Required()
                                 .WithMessage(FormatValidationError(Errors.FIELD_REQUIRED, "redirectGateway")))
                         .For(this)
                         .Validate();


            errors = result.ErrorMessages;

            return(result.Succeeded);
        }
Beispiel #20
0
        public UserNetCreateCommands()
        {
            IsCommand("user-net-create", "Create allow/deny for user network");

            HasRequiredOption("u|user="******"Enter user that already exists", arg =>
            {
                if (string.IsNullOrEmpty(arg))
                {
                    throw new ConsoleHelpAsException($"  *** No user name given ***");
                }

                _conf = (IConfiguration) new ConfigurationBuilder()
                        .AddJsonFile("clisettings.json", optional: false, reloadOnChange: true)
                        .Build();

                var instance = new ContextService(InstanceContext.DeployedOrLocal);
                _uow         = new UnitOfWork(_conf["Databases:AuroraEntities"], instance);

                _user = _uow.Users.Get(QueryExpressionFactory.GetQueryExpression <tbl_User>()
                                       .Where(x => x.IdentityAlias == arg).ToLambda(),
                                       new List <Expression <Func <tbl_User, object> > >()
                {
                    x => x.tbl_UserMount,
                }).SingleOrDefault();

                if (_user == null)
                {
                    throw new ConsoleHelpAsException($"  *** Invalid user '{arg}' ***");
                }
            });

            HasRequiredOption("c|cidr=", "Enter CIDR address to use", arg =>
            {
                if (!IPNetwork.TryParse(arg, out _cidr))
                {
                    throw new ConsoleHelpAsException($"*** Invalid cidr address ***");
                }
            });

            HasRequiredOption("a|action=", "Enter type of action to use", arg =>
            {
                if (!Enum.TryParse(arg, out _actionType))
                {
                    throw new ConsoleHelpAsException($"*** Invalid auth type. Options are '{_actionTypeList}' ***");
                }
            });
        }
Beispiel #21
0
        public IEnumerable <IPAddress> ExpandScopeToIPAddresses(string scope)
        {
            scope = scope ?? throw new ArgumentNullException(nameof(scope));
            scope = scope.Replace(" ", string.Empty);
            scope = scope.Replace("\t", string.Empty);

            var lines = scope.Split(",;\r\n".ToCharArray());

            var scopeIPAddresses = new HashSet <IPAddress>();

            foreach (var line in lines)
            {
                if (!string.IsNullOrWhiteSpace(line))
                {
                    if (line.Contains("/") && IPNetwork.TryParse(line, out var ipNetwork))
                    {
                        using (var ipAddresses = ipNetwork.ListIPAddress())
                        {
                            foreach (var ipAddress in ipAddresses)
                            {
                                if (ipAddress.AddressFamily == AddressFamily.InterNetwork && (ipAddress.Equals(ipNetwork.Network) || ipAddress.Equals(ipNetwork.Broadcast)))
                                {
                                    continue;
                                }

                                scopeIPAddresses.Add(ipAddress);
                            }
                        }
                    }
                    else if (IPAddress.TryParse(line, out var ipAddress))
                    {
                        scopeIPAddresses.Add(ipAddress);
                    }
                    else if (_dnsUtilitiesService.TryResolveHost(line, out var ipAddresses))
                    {
                        foreach (var address in ipAddresses)
                        {
                            scopeIPAddresses.Add(address);
                        }
                    }
                }
            }

            return(scopeIPAddresses);
        }
Beispiel #22
0
        /// <summary>
        /// Construct for a specific host.
        /// </summary>
        /// <param name="network">The network to test in CIDR or IP/Netmask notation.</param>
        /// <param name="logger">The logger to use.</param>
        /// <param name="hamnetDbAccess">The service configuration.</param>
        /// <param name="querierOptions">The options to the Hamnet querier.</param>
        public NetworkTest(string network, ILogger logger, IHamnetDbAccess hamnetDbAccess, IQuerierOptions querierOptions)
        {
            if (string.IsNullOrWhiteSpace(network))
            {
                throw new ArgumentNullException(nameof(network), "Network to test is null, empty or white-space-only");
            }

            IPNetwork subnet = null;

            if (!IPNetwork.TryParse(network, out subnet))
            {
                throw new ArgumentException($"Specified network '{network}' is not a valid IP network specification", nameof(network));
            }

            this.logger         = logger;
            this.hamnetDbAccess = hamnetDbAccess ?? throw new ArgumentNullException(nameof(hamnetDbAccess), "Handle to the HamnetDB accessor is null");
            this.network        = subnet;
            this.querierOptions = querierOptions ?? new FromUrlQueryQuerierOptions();
        }
Beispiel #23
0
        private IEnumerable <IPNetwork> GetIPNetworks()
        {
            List <IPNetwork> nets = new List <IPNetwork>();
            string           text = IPNetworks;

            if (string.IsNullOrEmpty(text) == false)
            {
                string[] subs = text.Split(',', StringSplitOptions.RemoveEmptyEntries);
                foreach (var i in subs)
                {
                    if (IPNetwork.TryParse(i, out IPNetwork net))
                    {
                        nets.Add(net);
                    }
                }
            }

            return(nets);
        }
Beispiel #24
0
        public static bool ValidateAddress(IEnumerable <tbl_Network> networks, IPAddress client)
        {
            var found = false;

            foreach (var network in networks)
            {
                IPNetwork cidr;

                if (IPNetwork.TryParse(network.Address, out cidr))
                {
                    if (cidr.Contains(client))
                    {
                        found = true;
                        continue;
                    }
                }
            }

            return(found);
        }
        public IEnumerable <IPNetwork> GetIPNetworksForServiceTag(string serviceTagId, AddressFamily[] addressFamilies = null)
        {
            var addressPrefixes = this.data.Values.FirstOrDefault(x => x.Id.Equals(serviceTagId, StringComparison.InvariantCultureIgnoreCase))?.Properties?.AddressPrefixes ?? Array.Empty <string>();

            var result = new List <IPNetwork>(addressPrefixes.Length);

            foreach (var addressPrefix in addressPrefixes)
            {
                if (!IPNetwork.TryParse(addressPrefix, out var ipNetwork))
                {
                    Console.WriteLine($"Failed to parse address prefix {addressPrefix}");
                }

                if (addressFamilies == null || addressFamilies.Contains(ipNetwork.AddressFamily))
                {
                    result.Add(ipNetwork);
                }
            }

            return(result);
        }
Beispiel #26
0
        /// <inheritdoc />
        public IHamnetDbSubnets QuerySubnets()
        {
            var responseString = this.SendHttpRequest(new Uri(this.SubnetsApiUrl, UriKind.Absolute));

            var responseData             = JsonConvert.DeserializeObject <IEnumerable <JsonSubnetDataSet> >(responseString);
            List <IHamnetDbSubnet> hosts = new List <IHamnetDbSubnet>();

            foreach (var responseDataSet in responseData.Where(r => !r.Deleted))
            {
                IPNetwork network;
                if (!IPNetwork.TryParse(responseDataSet.Subnet, out network))
                {
                    log.Error($"Cannot convert retrieved string '{responseDataSet.Subnet}' to a valid IP subnet. This entry will be skipped.");
                    continue;
                }

                hosts.Add(new HamnetDbSubnet(network));
            }

            return(new HamnetDbSubnets(hosts));
        }
Beispiel #27
0
        public static void EnableMulticast(this UdpClient client, string multicastAddress, int multicastPort, string localAddress)
        {
            IPAddress multicastIpAddress = IPAddress.Parse(multicastAddress);
            IPAddress localIpAddress     = null;
            IPNetwork localNetwork       = null;

            if (IPNetwork.TryParse(localAddress, out localNetwork))
            {
                localIpAddress = GetLocalIpAddress(localNetwork);
            }
            else
            {
                localIpAddress = IPAddress.Parse(localAddress);
            }
            var localEndPoint = new IPEndPoint(localIpAddress, multicastPort);

            client.ExclusiveAddressUse = false;
            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            // Bind, Join
            client.Client.Bind(localEndPoint);
            client.JoinMulticastGroup(multicastIpAddress, localIpAddress);
            //return client;
        }
Beispiel #28
0
        /// <summary>
        /// Returns true if <see cref="source"/> equals or within range of the specified IPs
        /// </summary>
        public static bool IsInRange(this IPAddress source, string[] comparer)
        {
            if (comparer == null)
            {
                return(false);
            }

            foreach (var value in comparer)
            {
                if (IPAddress.TryParse(value, out var ipAddress))
                {
                    // normal IP comparer

                    if (value.Equals(source))
                    {
                        return(true);
                    }

                    continue;
                }

                if (IPNetwork.TryParse(value, out var network))
                {
                    // CIDR comparer

                    if (network.Contains(source))
                    {
                        return(true);
                    }

                    continue;
                }
            }

            return(false);
        }
Beispiel #29
0
        static bool SaveApplySettings(SQLLib sql, ServerSettings newsettings)
        {
            if (Certificates.CertificateExists(newsettings.UseCertificate, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine) == false)
            {
                return(false);
            }

            if (newsettings.EMailPort < 1 || newsettings.EMailPort > 65535)
            {
                return(false);
            }

            if (newsettings.KeepEventLogDays < 0)
            {
                return(false);
            }
            if (newsettings.KeepNonPresentDisks < 0)
            {
                return(false);
            }
            if (newsettings.KeepReports < 0)
            {
                return(false);
            }
            if (newsettings.KeepChatLogs < 0)
            {
                return(false);
            }
            if (newsettings.KeepBitlockerRK < 0)
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(newsettings.AdministratorName) == true)
            {
                newsettings.AdministratorName = "Administrator";
            }

            if (string.IsNullOrWhiteSpace(newsettings.AdminIPAddresses) == true)
            {
                newsettings.AdminIPAddresses = "";
            }
            else
            {
                foreach (string s in newsettings.AdminIPAddresses.Split(','))
                {
                    if (s.Contains("/") == false)
                    {
                        return(false);
                    }
                    IPNetwork ip;
                    if (IPNetwork.TryParse(s, out ip) == false)
                    {
                        return(false);
                    }
                }
            }

            Settings.UseCertificate        = newsettings.UseCertificate;
            Settings.KeepEventLogDays      = newsettings.KeepEventLogDays;
            Settings.KeepBitlockerRK       = newsettings.KeepBitlockerRK;
            Settings.KeepChatLogs          = newsettings.KeepChatLogs;
            Settings.KeepNonPresentDisks   = newsettings.KeepNonPresentDisks;
            Settings.EMailAdminTo          = newsettings.EMailAdminTo;
            Settings.EMailFrom             = newsettings.EMailFrom;
            Settings.EMailFromFriendly     = newsettings.EMailFromFriendly;
            Settings.EMailPort             = newsettings.EMailPort;
            Settings.EMailServer           = newsettings.EMailServer;
            Settings.EMailUsername         = newsettings.EMailUsername;
            Settings.EMailPassword         = newsettings.EMailPassword;
            Settings.EMailUseSSL           = newsettings.EMailUseSSL;
            Settings.EMailAdminScheduling  = newsettings.EMailAdminScheduling;
            Settings.EMailClientScheduling = newsettings.EMailClientScheduling;
            Settings.EMailAdminIsHTML      = newsettings.EMailAdminIsHTML;
            Settings.EMailClientIsHTML     = newsettings.EMailClientIsHTML;
            Settings.EMailAdminText        = newsettings.EMailAdminText;
            Settings.EMailClientText       = newsettings.EMailClientText;
            Settings.EMailAdminSubject     = newsettings.EMailAdminSubject;
            Settings.EMailClientSubject    = newsettings.EMailClientSubject;
            Settings.AdminIPAddresses      = newsettings.AdminIPAddresses;
            Settings.AdministratorName     = newsettings.AdministratorName;
            Settings.KeepReports           = newsettings.KeepReports;
            Settings.MessageDisclaimer     = newsettings.MessageDisclaimer;

            PutString(sql, "UseCertificate", Settings.UseCertificate);
            PutInt64(sql, "KeepEventLogDays", Settings.KeepEventLogDays);
            PutInt64(sql, "KeepNonPresentDisks", Settings.KeepNonPresentDisks);
            PutInt64(sql, "KeepBitlockerRK", Settings.KeepBitlockerRK);
            PutInt64(sql, "KeepReports", Settings.KeepReports);
            PutInt64(sql, "KeepChatLogs", Settings.KeepChatLogs);
            PutString(sql, "EMailAdminTo", Settings.EMailAdminTo);
            PutString(sql, "EMailFrom", Settings.EMailFrom);
            PutString(sql, "EMailFromFriendly", Settings.EMailFromFriendly);
            PutInt(sql, "EMailPort", Settings.EMailPort);
            PutString(sql, "EMailServer", Settings.EMailServer);
            PutString(sql, "EMailUsername", Settings.EMailUsername);
            PutString(sql, "EMailPassword", Settings.EMailPassword);
            PutBool(sql, "EMailUseSSL", Settings.EMailUseSSL);
            PutBool(sql, "EMailAdminIsHTML", Settings.EMailAdminIsHTML);
            PutBool(sql, "EMailClientIsHTML", Settings.EMailClientIsHTML);
            PutString(sql, "EMailAdminText", Settings.EMailAdminText);
            PutString(sql, "EMailClientText", Settings.EMailClientText);
            PutString(sql, "EMailAdminSubject", Settings.EMailAdminSubject);
            PutString(sql, "EMailClientSubject", Settings.EMailClientSubject);
            PutString(sql, "AdminIPAddresses", Settings.AdminIPAddresses);
            PutString(sql, "AdminstratorName", Settings.AdministratorName);
            PutString(sql, "MessageDisclaimer", Settings.MessageDisclaimer);
            PutString(sql, "EMailAdminSched", JsonConvert.SerializeObject(Settings.EMailAdminScheduling));
            PutString(sql, "EMailClientSched", JsonConvert.SerializeObject(Settings.EMailClientScheduling));
            return(true);
        }
Beispiel #30
0
        /// <summary>
        ///     设置绕行规则
        /// </summary>
        /// <returns>是否设置成功</returns>
        private bool SetupRouteTable()
        {
            Logging.Info("收集路由表规则");
            Global.MainForm.StatusText(i18N.Translate("SetupBypass"));

            Logging.Info("绕行 → 全局绕过 IP");
            _directIPs.AddRange(Global.Settings.BypassIPs.Select(IPNetwork.Parse));

            Logging.Info("绕行 → 服务器 IP");
            _directIPs.AddRange(_serverAddresses.Where(address => !IPAddress.IsLoopback(address)).Select(address => IPNetwork.Parse(address.ToString(), 32)));

            Logging.Info("绕行 → 局域网 IP");
            _directIPs.AddRange(_bypassLanIPs.Select(IPNetwork.Parse));

            switch (_savedMode.Type)
            {
            case 1:
                // 代理规则
                Logging.Info("代理 → 规则 IP");
                _proxyIPs.AddRange(_savedMode.Rule.Select(IPNetwork.Parse));

                //处理 NAT 类型检测,由于协议的原因,无法仅通过域名确定需要代理的 IP,自己记录解析了返回的 IP,仅支持默认检测服务器
                if (Global.Settings.STUN_Server == "stun.stunprotocol.org")
                {
                    try
                    {
                        Logging.Info("代理 → STUN 服务器 IP");
                        _proxyIPs.AddRange(new[]
                        {
                            Dns.GetHostAddresses(Global.Settings.STUN_Server)[0],
                            Dns.GetHostAddresses("stunresponse.coldthunder11.com")[0]
                        }.Select(ip => IPNetwork.Parse(ip.ToString(), 32)));
                    }
                    catch
                    {
                        Logging.Info("NAT 类型测试域名解析失败,将不会被添加到代理列表");
                    }
                }

                if (Global.Settings.TUNTAP.ProxyDNS)
                {
                    Logging.Info("代理 → 自定义 DNS");
                    if (Global.Settings.TUNTAP.UseCustomDNS)
                    {
                        var dns = string.Empty;
                        foreach (var value in Global.Settings.TUNTAP.DNS)
                        {
                            dns += value;
                            dns += ',';
                        }

                        dns = dns.Trim();
                        dns = dns.Substring(0, dns.Length - 1);
                        RouteAction(Action.Create, dns, 32, RouteType.TUNTAP);
                    }
                    else
                    {
                        _proxyIPs.AddRange(new[] { "1.1.1.1", "8.8.8.8", "9.9.9.9", "185.222.222.222" }.Select(ip => IPNetwork.Parse(ip, 32)));
                    }
                }

                break;

            case 2:
                // 绕过规则

                // 将 TUN/TAP 网卡权重放到最高
                Process.Start(new ProcessStartInfo
                {
                    FileName        = "netsh",
                    Arguments       = $"interface ip set interface {Global.TUNTAP.Index} metric=0",
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    UseShellExecute = true,
                    CreateNoWindow  = true
                }
                              );

                if (_savedMode.BypassChina)
                {
                    Logging.Info("绕行 → 中国 IP");

                    foreach (var str in File.ReadAllLines("bin\\china_ip_list", Encoding.UTF8))
                    {
                        if (IPNetwork.TryParse(str, out var entry))
                        {
                            _directIPs.Add(entry);
                        }
                    }
                }

                Logging.Info("绕行 → 规则 IP");
                _directIPs.AddRange(_savedMode.Rule.Select(IPNetwork.Parse));

                Logging.Info("代理 → 全局");
                if (!RouteAction(Action.Create, IPNetwork.Parse("0.0.0.0", 0), RouteType.TUNTAP))
                {
                    State = State.Stopped;
                    return(false);
                }

                break;
            }

            Logging.Info("设置路由规则");
            RouteAction(Action.Create, _directIPs, RouteType.Gateway);
            RouteAction(Action.Create, _proxyIPs, RouteType.TUNTAP);

            return(true);
        }