public async Task <RegistryInformation> RegisterServiceAsync(ServiceConfiguration serviceConfiguration, ProtocolConfiguration protocolConfiguration, Uri healthCheckUri = null, IEnumerable <string> tags = null) { var serviceId = ServiceDiscoveryHelper.GetServiceId(serviceConfiguration.Interface, serviceConfiguration.Port.ToString()); var serviceName = ServiceDiscoveryHelper.GetServiceName(protocolConfiguration.Protocol, serviceConfiguration.Interface); string versionLabel = $"{ServiceDiscoveryHelper.VERSION_PREFIX}{serviceConfiguration.Version}"; var tagList = (tags ?? Enumerable.Empty <string>()).ToList(); tagList.Add(protocolConfiguration.Protocol); tagList.Add(protocolConfiguration.Transmit); tagList.Add(versionLabel); var instance = new RegistryInformation { Name = serviceName, Id = serviceId, Address = await DnsUtil.GetIpAddressAsync(), Port = serviceConfiguration.Port, Version = serviceConfiguration.Version, Tags = tagList }; ServiceInstances.Add(instance); return(instance); }
private async void testDnsAnswerButton_Click(object sender, EventArgs e) { var dnsChallenge = SelectedAuthorization?.DnsChallenge; if (dnsChallenge == null) { return; } await InvokeWithWaitCursor(async() => { try { var dnsValues = (await DnsUtil.LookupRecordAsync(dnsChallenge.DnsRecordType, dnsChallenge.DnsRecordName))?.ToArray(); var dnsValue = string.Join(",", dnsValues ?? EmptyStrings); if (string.IsNullOrEmpty(dnsValue)) { MessageBox.Show("Could not resolve DNS value!"); } else if (!string.Equals(dnsChallenge.DnsRecordValue, dnsValue)) { MessageBox.Show("DNS value is not expected! " + dnsValue); } else { MessageBox.Show("Looks good!"); } } catch (Exception ex) { MessageBox.Show("Failed to resolve DNS value: " + ex.Message); } }); }
private string PerformAutoDiscover(ZPushAccount account) { // Fetch the txt record IList <string> txt = DnsUtil.GetTxtRecord(account.Account.DomainName); if (txt == null) { return(null); } // Find kdiscover string kdiscover = txt.FirstOrDefault((record) => record.StartsWith(TXT_KDISCOVER)); Logger.Instance.Trace(this, "kdiscover: {0} -> {1}", account.Account.DomainName, kdiscover); if (string.IsNullOrEmpty(kdiscover)) { return(null); } string url = kdiscover.Substring(TXT_KDISCOVER.Length).Trim(); if (string.IsNullOrWhiteSpace(url)) { return(null); } return(url); }
/// <summary> /// Write the answer data into the given byte array and return the number of bytes written /// </summary> /// <param name="array">Array.</param> /// <param name="offset">Offset.</param> public int WriteAnswer(byte[] array, int offset) { int startingOffset = offset; // 2 bytes - NAME POINTER // 16 bit pointer, with two first bits 11 indiciating we are sending a pointer // If the answer is linked to an answer with a pointer, return a pointer, otherwise return a label if (this.Question != null && this.Question.DataPointer > 0) { var pointerBytes = BitConverter.GetBytes(this.Question.DataPointer); ByteArray.SwapFields(pointerBytes, 0, 1); // First two bits indicate a pointer pointerBytes[0] += (1 << 7); pointerBytes[0] += (1 << 6); array[offset++] = pointerBytes[0]; array[offset++] = pointerBytes[1]; } // If not linked to an answer, check if we can output the hostname label else if (this.Hostname != null && this.Hostname.Length > 0) { offset += DnsUtil.WriteHostnameLabel(array, offset, this.Hostname); } // Finally, if we can't find another hostname, we output an empty pointer else { array[offset++] = 0; array[offset++] = 0; } // Write the record and finish offset += this.Record.WriteRecord(array, offset); return(offset - startingOffset); }
/// <summary> /// Write the response data /// </summary> /// <param name="array"></param> /// <param name="offset"></param> /// <returns></returns> protected override int WriteResponseData(byte[] array, int offset) { int bytesWritten = DnsEncoder.WriteUint16(array, this.Priority, offset); bytesWritten += DnsUtil.WriteHostnameLabel(array, offset + bytesWritten, this.Value); return(bytesWritten); }
public async Task DefaultTest() { var ip1 = await DnsUtil.QueryAsync(@"dns.google"); Assert.IsTrue(Equals(ip1, IPAddress.Parse(@"8.8.8.8")) || Equals(ip1, IPAddress.Parse(@"8.8.4.4"))); var ip2 = await DnsUtil.QueryAsync(@"dns.google"); Assert.IsTrue(Equals(ip2, IPAddress.Parse(@"2001:4860:4860::8888")) || Equals(ip2, IPAddress.Parse(@"2001:4860:4860::8844"))); }
public static IPAddress GetAddressByName(string name) { if (name == "0.0.0.0") { return(IPAddress.Any); } var addresses = DnsUtil.GetHostAddresses(name); var ipv4 = addresses.FirstOrDefault(m => m.AddressFamily == AddressFamily.InterNetwork); return(ipv4 ?? addresses.FirstOrDefault()); }
/// <summary> /// Write the response data /// </summary> /// <param name="array"></param> /// <param name="offset"></param> /// <returns></returns> protected override int WriteResponseData(byte[] array, int offset) { int bytesWritten = DnsUtil.WriteHostnameLabel(array, offset, this.MasterHostname); bytesWritten += DnsUtil.WriteHostnameLabel(array, offset + bytesWritten, this.ResponsibleMailboxHostname); bytesWritten += DnsEncoder.WriteUint32(array, this.SerialNumber, offset + bytesWritten); bytesWritten += DnsEncoder.WriteInt32(array, this.RefreshInterval, offset + bytesWritten); bytesWritten += DnsEncoder.WriteInt32(array, this.RetryInterval, offset + bytesWritten); bytesWritten += DnsEncoder.WriteInt32(array, this.ExpirationLimit, offset + bytesWritten); bytesWritten += DnsEncoder.WriteInt32(array, this.MinimumTTL, offset + bytesWritten); return(bytesWritten); }
public async Task <RegistryInformation> RegisterServiceAsync(ServiceConfiguration serviceConfiguration, ProtocolConfiguration protocolConfiguration, Uri healthCheckUri = null, IEnumerable <string> tags = null) { var serviceId = ServiceDiscoveryHelper.GetServiceId(serviceConfiguration.Interface, serviceConfiguration.Port.ToString()); var serviceName = ServiceDiscoveryHelper.GetServiceName(protocolConfiguration.Protocol, serviceConfiguration.Interface); string versionLabel = $"{ServiceDiscoveryHelper.VERSION_PREFIX}{serviceConfiguration.Version}"; var tagList = (tags ?? Enumerable.Empty <string>()).ToList(); tagList.Add(protocolConfiguration.Protocol); tagList.Add(protocolConfiguration.Transmit); tagList.Add(versionLabel); string check = healthCheckUri?.ToString() ?? $""; var agentServiceCheck = protocolConfiguration.Transmit == "tcp" ? new AgentServiceCheck { TCP = check, Interval = TimeSpan.FromSeconds(2) } : new AgentServiceCheck { HTTP = check, Interval = TimeSpan.FromSeconds(2) }; var registration = new AgentServiceRegistration { ID = serviceId, Name = serviceName, Tags = tagList.ToArray(), Address = await DnsUtil.GetIpAddressAsync(), Port = serviceConfiguration.Port, Check = new AgentServiceCheck { HTTP = check, Interval = TimeSpan.FromSeconds(2) } }; await _consul.Agent.ServiceRegister(registration); return(new RegistryInformation { Name = registration.Name, Id = registration.ID, Address = registration.Address, Port = registration.Port, Version = serviceConfiguration.Version, Tags = tagList }); }
public async Task TestTwoDnsAsync() { const string host = @"www.google.com"; var clients = new List <Shadowsocks.Model.DnsClient> { new Shadowsocks.Model.DnsClient(DnsType.Default) { DnsServer = @"101.6.6.6", Port = 5353, IsTcpEnabled = true, IsUdpEnabled = false }, new Shadowsocks.Model.DnsClient(DnsType.DnsOverTls) }; var res = await DnsUtil.QueryAsync(host, clients); Assert.IsNotNull(res); Console.WriteLine(res); }
private void buttonScan_Click(object sender, EventArgs e) { try { string host = textBoxHost.Text; int beginPort = int.Parse(textBoxBeginPort.Text); int endPort = int.Parse(textBoxEndPort.Text); string ip = ""; if (RegexUtil.IsIPv4(host)) { ip = host; } else { ip = new DnsUtil().GetIpByUrl(host); } richTextBoxOut.Text = String.Format("开始扫描 {0}\r\n", ip); Thread thread = new Thread(ScanThreadPoolWork); thread.Start(this); for (int i = beginPort; i <= endPort; i++) { ScanPortWorkData data = new ScanPortWorkData(); data.Wnd = this; data.Host = ip; data.Port = i; ThreadPool.QueueUserWorkItem(new WaitCallback(IsPortOpenWork), data); } } catch (Exception ex) { richTextBoxOut.Text = ex.Message; } }
public static string CreateAddress(string transmit, string port, string name) { var ip = DnsUtil.GetIpAddressAsync().Result; return(CreateAddress(transmit, ip, port, name)); }
private void Connect() { try { IPAddress ipAddress = null; var _targetPort = 0; { if (_firstPacket[0] == 1) { var addr = new byte[4]; Array.Copy(_firstPacket, 1, addr, 0, addr.Length); ipAddress = new IPAddress(addr); _targetPort = (_firstPacket[5] << 8) | _firstPacket[6]; _remote_host = ipAddress.ToString(); Logging.Info((_local_proxy ? "Local proxy" : "Direct") + " connect " + _remote_host + ":" + _targetPort); } else if (_firstPacket[0] == 4) { var addr = new byte[16]; Array.Copy(_firstPacket, 1, addr, 0, addr.Length); ipAddress = new IPAddress(addr); _targetPort = (_firstPacket[17] << 8) | _firstPacket[18]; _remote_host = ipAddress.ToString(); Logging.Info((_local_proxy ? "Local proxy" : "Direct") + " connect " + _remote_host + ":" + _targetPort); } else if (_firstPacket[0] == 3) { int len = _firstPacket[1]; var addr = new byte[len]; Array.Copy(_firstPacket, 2, addr, 0, addr.Length); _remote_host = Encoding.UTF8.GetString(_firstPacket, 2, len); _targetPort = (_firstPacket[len + 2] << 8) | _firstPacket[len + 3]; Logging.Info((_local_proxy ? "Local proxy" : "Direct") + " connect " + _remote_host + ":" + _targetPort); //if (!_local_proxy) { if (!IPAddress.TryParse(_remote_host, out ipAddress)) { if (_config.proxyRuleMode == ProxyRuleMode.UserCustom) { var hostMap = HostMap.Instance(); if (hostMap.GetHost(_remote_host, out var host_addr)) { if (!string.IsNullOrEmpty(host_addr)) { var lower_host_addr = host_addr.ToLower(); if (lower_host_addr.StartsWith("reject")) { Close(); return; } if (lower_host_addr.IndexOf('.') >= 0 || lower_host_addr.IndexOf(':') >= 0) { if (!IPAddress.TryParse(lower_host_addr, out ipAddress)) { // } } } } } if (ipAddress == null) { ipAddress = DnsUtil.LocalDnsBuffer.Get(_remote_host); } } if (ipAddress == null) { ipAddress = DnsUtil.QueryDns(_remote_host, _remote_host.IndexOf('.') >= 0 ? _config.localDnsServer : null); } if (ipAddress != null) { DnsUtil.LocalDnsBuffer.Set(_remote_host, new IPAddress(ipAddress.GetAddressBytes())); DnsUtil.LocalDnsBuffer.Sweep(); } else { if (!_local_proxy) { throw new SocketException((int)SocketError.HostNotFound); } } } } _remote_port = _targetPort; } if (ipAddress != null && _config.proxyRuleMode == ProxyRuleMode.UserCustom) { var hostMap = HostMap.Instance(); if (hostMap.GetIP(ipAddress, out var host_addr)) { var lower_host_addr = host_addr.ToLower(); if (lower_host_addr.StartsWith("reject") ) { Close(); return; } } } if (_local_proxy) { IPAddress.TryParse(_config.proxyHost, out ipAddress); _targetPort = _config.proxyPort; } // ProxyAuth recv only socks5 head, so don't need to save anything else var remoteEP = new IPEndPoint(ipAddress ?? throw new InvalidOperationException(), _targetPort); _remote = new ProxySocketTun(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _remote.GetSocket().NoDelay = true; // Connect to the remote endpoint. _remote.BeginConnect(remoteEP, ConnectCallback, null); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
public RrNs(string name, uint ttl, string nsName) : base(name, DnsType.Ns, ttl, DnsUtil.Str2DnsName(nsName)) { }
public RrPtr(string name, uint ttl, string ptr) : base(name, DnsType.Ptr, ttl, DnsUtil.Str2DnsName(ptr)) { }
public static string GetServiceId(string port, string path) { var ip = DnsUtil.GetIpAddressAsync().Result; return($"{port}_{ip.Replace(".", "-")}_{path.Replace(".", "-")}"); }
/// <summary> /// Write the record response data /// </summary> /// <param name="array"></param> /// <param name="offset"></param> /// <returns></returns> protected override int WriteResponseData(byte[] array, int offset) { var hostnameLength = DnsUtil.WriteHostnameLabel(array, offset, this.Hostname); return(hostnameLength); }
public RrCname(string name, uint ttl, string cname) : base(name, DnsType.Cname, ttl, DnsUtil.Str2DnsName(cname)) { }
private int IsHandle(byte[] firstPacket, int length) { if (length >= 7 && _config.proxyRuleMode != ProxyRuleMode.Disable) { IPAddress ipAddress = null; if (firstPacket[0] == 1) { var addr = new byte[4]; Array.Copy(firstPacket, 1, addr, 0, addr.Length); ipAddress = new IPAddress(addr); } else if (firstPacket[0] == 3) { int len = firstPacket[1]; var addr = new byte[len]; if (length >= len + 2) { Array.Copy(firstPacket, 2, addr, 0, addr.Length); var host = Encoding.UTF8.GetString(firstPacket, 2, len); if (IPAddress.TryParse(host, out ipAddress)) { //pass } else { if ((_config.proxyRuleMode == ProxyRuleMode.BypassLanAndChina || _config.proxyRuleMode == ProxyRuleMode.BypassLanAndNotChina) && _IPRange != null || _config.proxyRuleMode == ProxyRuleMode.UserCustom) { if (!IPAddress.TryParse(host, out ipAddress)) { if (_config.proxyRuleMode == ProxyRuleMode.UserCustom) { var hostMap = HostMap.Instance(); if (hostMap.GetHost(host, out var host_addr)) { if (!string.IsNullOrEmpty(host_addr)) { var lower_host_addr = host_addr.ToLower(); if (lower_host_addr.StartsWith("reject") || lower_host_addr.StartsWith("direct") ) { return(CONNECT_DIRECT); } if (lower_host_addr.StartsWith("localproxy")) { return(CONNECT_LOCALPROXY); } if (lower_host_addr.StartsWith("remoteproxy")) { return(CONNECT_REMOTEPROXY); } if (lower_host_addr.IndexOf('.') >= 0 || lower_host_addr.IndexOf(':') >= 0) { if (!IPAddress.TryParse(lower_host_addr, out ipAddress)) { // } } } } } if (ipAddress == null) { ipAddress = DnsUtil.DnsBuffer.Get(host); } } if (ipAddress == null) { ipAddress = DnsUtil.QueryDns(host, host.IndexOf('.') >= 0 ? _config.dnsServer : null); if (ipAddress != null) { DnsUtil.DnsBuffer.Set(host, new IPAddress(ipAddress.GetAddressBytes())); if (host.IndexOf('.') >= 0) { if (IPSubnet.IsLan(ipAddress)) // assume that it is polution if return LAN address { return(CONNECT_REMOTEPROXY); } } } else { Logging.Log(LogLevel.Debug, "DNS query fail: " + host); } } } } } } else if (firstPacket[0] == 4) { var addr = new byte[16]; Array.Copy(firstPacket, 1, addr, 0, addr.Length); ipAddress = new IPAddress(addr); } if (ipAddress != null) { if (_config.proxyRuleMode == ProxyRuleMode.UserCustom) { var hostMap = HostMap.Instance(); if (hostMap.GetIP(ipAddress, out var host_addr)) { var lower_host_addr = host_addr.ToLower(); if (lower_host_addr.StartsWith("reject") || lower_host_addr.StartsWith("direct") ) { return(CONNECT_DIRECT); } if (lower_host_addr.StartsWith("localproxy")) { return(CONNECT_LOCALPROXY); } if (lower_host_addr.StartsWith("remoteproxy")) { return(CONNECT_REMOTEPROXY); } } } else { if (IPSubnet.IsLan(ipAddress)) { return(CONNECT_DIRECT); } if ((_config.proxyRuleMode == ProxyRuleMode.BypassLanAndChina || _config.proxyRuleMode == ProxyRuleMode.BypassLanAndNotChina) && _IPRange != null && ipAddress.AddressFamily == AddressFamily.InterNetwork ) { if (_IPRange.IsInIPRange(ipAddress)) { return(CONNECT_LOCALPROXY); } DnsUtil.DnsBuffer.Sweep(); } } } } return(CONNECT_REMOTEPROXY); }
DnsMessageBase?processDnsQuery(DnsMessageBase message, IPAddress clientAddress) { try { bool is_fix_record = false; DnsMessage?q = message as DnsMessage; string? domainname = null; List <string> matchIPList = new List <string>(); if (q == null) { return(null); } if (hc.IsEmpty) { return(null); } q.IsQuery = false; q.ReturnCode = ReturnCode.ServerFailure; // 2022.8.18 dnsdist のキャッシュを効かせるためすべての AdditionalRecords を無視 if (Ini["CopyQueryAdditionalRecordsToResponse"].BoolValue == false) { q.AdditionalRecords.Clear(); } List <DnsRecordBase> answers = new List <DnsRecordBase>(); int num_match = 0; string queryDomainName = ""; foreach (DnsQuestion question in q.Questions) { q.ReturnCode = ReturnCode.NoError; string tmp; //Con.WriteLine("{0}: Query - {2} '{1}'", Str.DateTimeToStrShort(DateTime.Now), question.Name, question.RecordType); if (question.RecordType == RecordType.Ns) { bool b = false; foreach (string dom in ValidDomainNames) { string qname = question.Name.ToString(); if (qname.EndsWith(".")) { qname = qname.Substring(0, qname.Length - 1); } if (Str.StrCmpi(qname, dom)) { string[] keys = Ini.GetKeys(); int num_ns = 0; foreach (string key in keys) { if (key.StartsWith("NS", StringComparison.OrdinalIgnoreCase)) { string ns = Ini[key].StrValue; answers.Add(new NsRecord(DomainName.Parse(dom), (int)Ini["TtlFix"].IntValue, DomainName.Parse(ns))); num_ns++; } } if (num_ns == 0) { answers.Add(new NsRecord(DomainName.Parse(dom), (int)Ini["TtlFix"].IntValue, DomainName.Parse(Ini["PrimaryServer"].StrValue))); } num_match++; b = true; } if (qname.EndsWith(dom) && (Str.StrCmpi(qname, dom) == false)) { string[] keys = Ini.GetKeys(); //int num_ns = 0; q.IsAuthoritiveAnswer = true; q.AuthorityRecords.Add(new SoaRecord(DomainName.Parse(dom), (int)Ini["Ttl"].IntValue, DomainName.Parse(Ini["PrimaryServer"].StrValue), DomainName.Parse(Ini["EMail"].StrValue), DnsUtil.GenerateSoaSerialNumberFromDateTime(this.hc.LastHealthyTime), (int)Ini["Ttl"].IntValue, (int)Ini["Ttl"].IntValue, 88473600, (int)Ini["Ttl"].IntValue)); num_match++; /* if (num_ns == 0) * { * answers.Add(new NsRecord(dom, (int)Ini["TtlFix"].IntValue, Ini["PrimaryServer"].StrValue)); * } */ num_match++; b = true; } } if (b) { break; } } queryDomainName = question.Name.ToString(); List <IPAddress>?ret = nameToIpAddresses(queryDomainName, question.RecordType, out tmp, out is_fix_record); if (ret == null) { q.ReturnCode = ReturnCode.Refused; break; } else { if (Str.IsEmptyStr(tmp) == false) { domainname = tmp; } foreach (IPAddress addr in ret) { num_match++; int ttl = (int)Ini["Ttl"].IntValue; int ttl_fix = (int)Ini["TtlFix"].IntValue; if (is_fix_record) { ttl = ttl_fix; } if (addr.AddressFamily == AddressFamily.InterNetwork && (question.RecordType == RecordType.A || question.RecordType == RecordType.Any)) { answers.Add(new ARecord(question.Name, ttl, addr)); } else if (addr.AddressFamily == AddressFamily.InterNetworkV6 && (question.RecordType == RecordType.Aaaa || question.RecordType == RecordType.Any)) { answers.Add(new AaaaRecord(question.Name, ttl, addr)); } else if (question.RecordType == RecordType.Ns) { answers.Add(new NsRecord(DomainName.Parse(domainname), ttl_fix, DomainName.Parse(Ini["PrimaryServer"].StrValue))); } // ログ if (addr.AddressFamily == AddressFamily.InterNetwork || addr.AddressFamily == AddressFamily.InterNetworkV6) { matchIPList.Add(addr.ToString()); } } } } if (q.ReturnCode == ReturnCode.NoError) { if (num_match >= 1) { q.AnswerRecords = answers; q.IsAuthoritiveAnswer = true; } else { q.ReturnCode = ReturnCode.NxDomain; } if (Ini["SaveAccessLog"].BoolValue) { string logStr = string.Format("Query Domain={0} From={1} ", queryDomainName, clientAddress.ToString()); if (matchIPList.Count == 0) { logStr += "Result: Not Found"; } else { logStr += "Result: " + Str.CombineStringArray(matchIPList.ToArray(), " "); } write(logStr); } } // SOA if (Str.IsEmptyStr(domainname) == false) { q.IsAuthoritiveAnswer = true; q.AuthorityRecords.Add(new SoaRecord(DomainName.Parse(domainname), (int)Ini["Ttl"].IntValue, DomainName.Parse(Ini["PrimaryServer"].StrValue), DomainName.Parse(Ini["EMail"].StrValue), DnsUtil.GenerateSoaSerialNumberFromDateTime(this.hc.LastHealthyTime), (int)Ini["Ttl"].IntValue, (int)Ini["Ttl"].IntValue, 88473600, (int)Ini["Ttl"].IntValue)); } q.IsRecursionAllowed = false; return(q); } catch (Exception ex) { ex._Debug(); return(null); } }