private static async Task <HttpResponseMessage> SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, bool isProxyAuth, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken) { HttpResponseMessage response = await InnerSendAsync(request, isProxyAuth, connectionPool, connection, cancellationToken).ConfigureAwait(false); if (!isProxyAuth && connection.Kind == HttpConnectionKind.Proxy && !ProxySupportsConnectionAuth(response)) { // Proxy didn't indicate that it supports connection-based auth, so we can't proceed. if (NetEventSource.IsEnabled) { NetEventSource.Error(connection, $"Proxy doesn't support connection-based auth, uri={authUri}"); } return(response); } if (TryGetAuthenticationChallenge(response, isProxyAuth, authUri, credentials, out AuthenticationChallenge challenge)) { if (challenge.AuthenticationType == AuthenticationType.Negotiate || challenge.AuthenticationType == AuthenticationType.Ntlm) { bool isNewConnection = false; bool needDrain = true; try { if (response.Headers.ConnectionClose.GetValueOrDefault()) { // Server is closing the connection and asking us to authenticate on a new connection. (connection, response) = await connectionPool.CreateHttp11ConnectionAsync(request, cancellationToken).ConfigureAwait(false); if (response != null) { return(response); } connectionPool.IncrementConnectionCount(); connection.Acquire(); isNewConnection = true; needDrain = false; } if (NetEventSource.IsEnabled) { NetEventSource.Info(connection, $"Authentication: {challenge.AuthenticationType}, Uri: {authUri.AbsoluteUri.ToString()}"); } // Calculate SPN (Service Principal Name) using the host name of the request. // Use the request's 'Host' header if available. Otherwise, use the request uri. // Ignore the 'Host' header if this is proxy authentication since we need to use // the host name of the proxy itself for SPN calculation. string hostName; if (!isProxyAuth && request.HasHeaders && request.Headers.Host != null) { // Use the host name without any normalization. hostName = request.Headers.Host; if (NetEventSource.IsEnabled) { NetEventSource.Info(connection, $"Authentication: {challenge.AuthenticationType}, Host: {hostName}"); } } else { // Need to use FQDN normalized host so that CNAME's are traversed. // Use DNS to do the forward lookup to an A (host) record. // But skip DNS lookup on IP literals. Otherwise, we would end up // doing an unintended reverse DNS lookup. UriHostNameType hnt = authUri.HostNameType; if (hnt == UriHostNameType.IPv6 || hnt == UriHostNameType.IPv4) { hostName = authUri.IdnHost; } else { IPHostEntry result = await Dns.GetHostEntryAsync(authUri.IdnHost).ConfigureAwait(false); hostName = result.HostName; } } string spn = "HTTP/" + hostName; if (NetEventSource.IsEnabled) { NetEventSource.Info(connection, $"Authentication: {challenge.AuthenticationType}, SPN: {spn}"); } ChannelBinding channelBinding = connection.TransportContext?.GetChannelBinding(ChannelBindingKind.Endpoint); NTAuthentication authContext = new NTAuthentication(isServer: false, challenge.SchemeName, challenge.Credential, spn, ContextFlagsPal.Connection, channelBinding); string challengeData = challenge.ChallengeData; try { while (true) { string challengeResponse = authContext.GetOutgoingBlob(challengeData); if (challengeResponse == null) { // Response indicated denial even after login, so stop processing and return current response. break; } if (needDrain) { await connection.DrainResponseAsync(response).ConfigureAwait(false); } SetRequestAuthenticationHeaderValue(request, new AuthenticationHeaderValue(challenge.SchemeName, challengeResponse), isProxyAuth); response = await InnerSendAsync(request, isProxyAuth, connectionPool, connection, cancellationToken).ConfigureAwait(false); if (authContext.IsCompleted || !TryGetRepeatedChallenge(response, challenge.SchemeName, isProxyAuth, out challengeData)) { break; } needDrain = true; } } finally { authContext.CloseContext(); } } finally { if (isNewConnection) { connection.Release(); } } } } return(response); }
public async Task StartAsync() { await _semaphore.WaitAsync(); try { if (_webSocketListener != null) { throw new InvalidOperationException("The listener is already active"); } var listenerUri = ListenerUris[0]; IPEndPoint listenerEndPoint; if (listenerUri.IsLoopback) { listenerEndPoint = new IPEndPoint(IPAddress.Any, listenerUri.Port); } else { switch (listenerUri.HostNameType) { case UriHostNameType.Dns: var dnsEntry = await Dns.GetHostEntryAsync(listenerUri.Host).ConfigureAwait(false); if (dnsEntry.AddressList.Any(a => a.AddressFamily == AddressFamily.InterNetwork)) { listenerEndPoint = new IPEndPoint( dnsEntry.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork), listenerUri.Port); } else { throw new ArgumentException( $"Could not resolve the IPAddress for the host '{listenerUri.Host}'"); } break; case UriHostNameType.IPv4: case UriHostNameType.IPv6: listenerEndPoint = new IPEndPoint(IPAddress.Parse(listenerUri.Host), listenerUri.Port); break; default: throw new ArgumentException($"The host name type for '{listenerUri.Host}' is not supported"); } } _webSocketListener = new WebSocketListener( listenerEndPoint, new WebSocketListenerOptions() { SubProtocols = new[] { LimeUri.LIME_URI_SCHEME } }); var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(_webSocketListener); _webSocketListener.Standards.RegisterStandard(rfc6455); if (_sslCertificate != null) { _webSocketListener.ConnectionExtensions.RegisterExtension( new WebSocketSecureConnectionExtension(_sslCertificate)); } _webSocketListener.Start(); } finally { _semaphore.Release(); } }
/// <summary> /// Actively monitor ARP packets for signs of new clients after the scanner is done. This method should be called from the StartScan method. /// </summary> /// <param name="view">UI controls</param> public static void BackgroundScanStart(IView view) { view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Starting background scan...")); BackgroundScanDisabled = false; IPAddress myipaddress = AppConfiguration.LocalIp; #region Assign OnPacketArrival event handler and start capturing capturedevice.OnPacketArrival += (object sender, PacketCapture e) => { if (BackgroundScanDisabled) { return; } var rawCapture = e.GetPacket(); Packet packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); if (packet == null) { return; } ArpPacket ArpPacket = packet.Extract <ArpPacket>(); if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize)) { ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress); view.ListView1.BeginInvoke(new Action(() => { string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress); string ip = ArpPacket.SenderProtocolAddress.ToString(); var device = new Device { IP = ArpPacket.SenderProtocolAddress, MAC = PhysicalAddress.Parse(mac.Replace(":", "")), DeviceName = "Resolving", ManName = "Getting information...", DeviceStatus = "Online" }; //Add device to list view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); })); //Add device to main device list _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device); //Get hostname and mac vendor for the current device _ = Task.Run(async() => { try { #region Get Hostname IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip); device.DeviceName = hostEntry?.HostName ?? ip; #endregion #region Get MacVendor var Name = VendorAPI.GetVendorInfo(mac); device.ManName = (Name is null) ? "" : Name.data.organization_name; #endregion view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); })); } catch (Exception ex) { try { if (ex is SocketException) { var Name = VendorAPI.GetVendorInfo(mac); device.ManName = (Name is null) ? "" : Name.data.organization_name; view.ListView1.BeginInvoke(new Action(() => { device.DeviceName = ip; view.ListView1.UpdateObject(device); })); } else { view.MainForm.BeginInvoke( new Action(() => { device.DeviceName = ip; device.ManName = "Error"; view.ListView1.UpdateObject(device); })); } } catch { } } }); })); view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = ClientList.Count + " device(s) found")); } else if (ClientList.ContainsKey(ArpPacket.SenderProtocolAddress)) { foreach (var Device in Main.Devices) { if (Device.Key.Equals(ArpPacket.SenderProtocolAddress)) { Device.Value.TimeSinceLastArp = DateTime.Now; break; } } } }; //Start receiving packets capturedevice.StartCapture(); //Update UI state view.MainForm.BeginInvoke(new Action(() => { view.PictureBox.Image = NetStalker.Properties.Resources.color_ok; view.StatusLabel2.Text = "Ready"; view.Tile.Enabled = true; view.Tile2.Enabled = true; })); if (!LoadingBarCalled) { CallTheLoadingBar(view); view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning...")); } view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = ClientList.Count + " device(s) found")); #endregion }
public static void RunBlocked(JsonDB jsonDB, IMemoryCache memoryCache) { if (IsRunBlocked || BlockedIP.IsEmpty) { return; } IsRunBlocked = true; // Получаем текущий список заблокированных IP string IPv4 = new Bash().Run("iptables -L -n -v | grep \"ISPCore_\" | awk '{print $8}'"); string IPv6 = new Bash().Run("ip6tables -L -n -v | grep \"ISPCore_\" | awk '{print $8}'"); // Блокируем 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; // Достаем настройки WhiteList из кеша var whiteList = Engine.Base.SqlAndCache.WhiteList.GetCache(jsonDB.WhiteList); // Проверяем имя хоста на белый список DNSLookup if (Regex.IsMatch(host.HostName, whiteList.PtrRegex, RegexOptions.IgnoreCase)) { // Добовляем IP в белый список на неделю WhitePtr.Add(IP, DateTime.Now.AddDays(7)); // Удаляем временное значение с кеша memoryCache.Remove($"AntiDdosCheckBlockedIP-{IP}"); return; } } } } catch { } #endregion // Добовляем IP в IPtables 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"); // Пишем 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)); } }
//private static readonly Regex ipRegex = new Regex(@"ip[46]\:(?<ip>[^ ]+) ?", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant); //private static readonly Regex domainRegex = new Regex(@"include\:(?<domain>[^ ]+) ?", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant); /// <summary> /// Walk SPF records until a valid value is found. Two levels deep walk. /// </summary> /// <param name="writer">Stream writer</param> /// <param name="connectionEndPoint">Connected end point</param> /// <param name="fromAddress">Mail address from</param> /// <param name="fromAddressDomain">Mail address from domain</param> /// <returns>Task</returns> /// <exception cref="InvalidOperationException">SPF fails to validate</exception> public async Task ValidateSPF(StreamWriter writer, IPEndPoint connectionEndPoint, string fromAddress, string fromAddressDomain) { if (!requireSpfMatch) { return; } MailDemonLog.Info("Validating spf for end point {0}, from address: {1}, from domain: {2}", connectionEndPoint.Address, fromAddress, fromAddressDomain); // example smtp host: mail-it1-f173.google.com IPHostEntry entry = await Dns.GetHostEntryAsync(connectionEndPoint.Address); var spfValidator = new ARSoft.Tools.Net.Spf.SpfValidator(); ARSoft.Tools.Net.Spf.ValidationResult result = await spfValidator.CheckHostAsync(connectionEndPoint.Address, fromAddressDomain, fromAddress); if (result.Result == ARSoft.Tools.Net.Spf.SpfQualifier.Pass) { return; } else if (result.Result == ARSoft.Tools.Net.Spf.SpfQualifier.None) { // no spf record... what to do? // TODO: Maybe email back to the address and tell them to setup SPF records...? } /* * LookupClient lookup = new LookupClient(); * IDnsQueryResponse dnsQueryRoot = await lookup.QueryAsync(fromAddressDomain, QueryType.TXT); * foreach (var record in dnsQueryRoot.AllRecords) * { * MatchCollection ipMatches = ipRegex.Matches(record.ToString()); * foreach (Match ipMatch in ipMatches) * { * if (IPAddressRange.TryParse(ipMatch.Groups["ip"].Value, out IPAddressRange testIp)) * { * foreach (IPAddress ip in entry.AddressList) * { * if (testIp.Contains(ip)) * { * // good * return; * } * } * } * } * * MatchCollection matches = domainRegex.Matches(record.ToString()); * foreach (Match match in matches) * { * string domainHost = match.Groups["domain"].Value; * IDnsQueryResponse dnsQuery = await lookup.QueryAsync(domainHost, QueryType.TXT); * foreach (var record2 in dnsQuery.AllRecords) * { * MatchCollection ipMatches2 = ipRegex.Matches(record2.ToString()); * foreach (Match ipMatch in ipMatches2) * { * if (IPAddressRange.TryParse(ipMatch.Groups["ip"].Value, out IPAddressRange testIp)) * { * foreach (IPAddress ip in entry.AddressList) * { * if (testIp.Contains(ip)) * { * // good * return; * } * } * } * } * * MatchCollection matches2 = domainRegex.Matches(record2.ToString()); * foreach (Match match2 in matches2) * { * string domainHost2 = match2.Groups["domain"].Value; * IDnsQueryResponse dnsQuery3 = await lookup.QueryAsync(domainHost2, QueryType.TXT); * foreach (var record3 in dnsQuery3.AllRecords) * { * MatchCollection ipMatches3 = ipRegex.Matches(record3.ToString()); * foreach (Match ipMatch in ipMatches3) * { * if (IPAddressRange.TryParse(ipMatch.Groups["ip"].Value, out IPAddressRange testIp)) * { * foreach (IPAddress ip in entry.AddressList) * { * if (testIp.Contains(ip)) * { * // good * return; * } * } * } * } * } * } * } * } * } */ if (writer != null) { await writer.WriteLineAsync($"500 invalid command - SPF records from mail domain '{fromAddressDomain}' do not match connection host '{entry.HostName}'"); await writer.FlushAsync(); } throw new InvalidOperationException($"SPF validation failed for host '{entry.HostName}', address domain '{fromAddressDomain}'"); }
public static string GetLocalIp() { return(Dns.GetHostEntryAsync(Dns.GetHostName()).Result.AddressList.First(x => x.AddressFamily == AddressFamily.InterNetwork).ToString()); }
public async Task Dns_GetHostEntryAsync_HostString_Ok(string hostName) { await TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(hostName)); }
public void Dns_GetHostEntryAsync_HostString_Ok(string hostName) { TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(hostName)); }
public void Dns_GetHostEntryAsync_IPString_Ok() { TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(TestSettings.LocalIPString)); }
private async void StartPing() { DisplayStatusMessage = false; IsPingRunning = true; // Measure the time StartTime = DateTime.Now; stopwatch.Start(); dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); dispatcherTimer.Start(); EndTime = null; // Reset the latest results PingResult.Clear(); PingsTransmitted = 0; PingsReceived = 0; PingsLost = 0; AverageTime = 0; MinimumTime = 0; MaximumTime = 0; // Change the tab title (not nice, but it works) Window window = Application.Current.Windows.OfType <Window>().FirstOrDefault(x => x.IsActive); if (window != null) { foreach (TabablzControl tabablzControl in VisualTreeHelper.FindVisualChildren <TabablzControl>(window)) { tabablzControl.Items.OfType <DragablzTabItem>().First(x => x.ID == _tabId).Header = Host; } } // Try to parse the string into an IP-Address bool hostIsIP = IPAddress.TryParse(Host, out IPAddress ipAddress); try { // Try to resolve the hostname if (!hostIsIP) { IPHostEntry ipHostEntrys = await Dns.GetHostEntryAsync(Host); foreach (IPAddress ip in ipHostEntrys.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork && SettingsManager.Current.Ping_ResolveHostnamePreferIPv4) { ipAddress = ip; continue; } else if (ip.AddressFamily == AddressFamily.InterNetworkV6 && !SettingsManager.Current.Ping_ResolveHostnamePreferIPv4) { ipAddress = ip; continue; } } // Fallback --> If we could not resolve our prefered ip protocol for the hostname if (!hostIsIP) { foreach (IPAddress ip in ipHostEntrys.AddressList) { ipAddress = ip; continue; } } } } catch (SocketException) // This will catch DNS resolve errors { if (CancelPing) { UserHasCanceled(); } else { PingFinished(); } StatusMessage = string.Format(LocalizationManager.GetStringByKey("String_CouldNotResolveHostnameFor"), Host); DisplayStatusMessage = true; return; } // Add the hostname or ip address to the history AddHostToHistory(Host); cancellationTokenSource = new CancellationTokenSource(); PingOptions pingOptions = new PingOptions() { Attempts = SettingsManager.Current.Ping_Attempts, Timeout = SettingsManager.Current.Ping_Timeout, Buffer = new byte[SettingsManager.Current.Ping_Buffer], TTL = SettingsManager.Current.Ping_TTL, DontFragment = SettingsManager.Current.Ping_DontFragment, WaitTime = SettingsManager.Current.Ping_WaitTime, ExceptionCancelCount = SettingsManager.Current.Ping_ExceptionCancelCount, Hostname = hostIsIP ? string.Empty : Host }; Ping ping = new Ping(); ping.PingReceived += Ping_PingReceived; ping.PingCompleted += Ping_PingCompleted; ping.PingException += Ping_PingException; ping.UserHasCanceled += Ping_UserHasCanceled; ping.SendAsync(ipAddress, pingOptions, cancellationTokenSource.Token); }
internal static async Task <IPAddress[]> LookupHostName(string hostName) { return((await Dns.GetHostEntryAsync(hostName)).AddressList); }
public Task <IPHostEntry> GetHostEntryAsync(string hostNameOrAddress) { return(Dns.GetHostEntryAsync(hostNameOrAddress)); }
public void GetHostEntryAsyncWithHost() { GetHostEntryAsync(() => Dns.GetHostEntryAsync(TestSettings.LocalHost)); }
public async Task GetHostEntryAsyncWithAddress() { IPAddress localIPAddress = await TestSettings.GetLocalIPAddress(); GetHostEntryAsync(() => Dns.GetHostEntryAsync(localIPAddress)); }
public void SendAsync(IPAddress ipAddress, CancellationToken cancellationToken) { Task.Run(() => { var hostname = Hostname; // Try to resolve PTR if (string.IsNullOrEmpty(hostname)) { try { Task.Run(() => { hostname = Dns.GetHostEntryAsync(ipAddress).Result.HostName; }, cancellationToken); } catch (SocketException) { } } var pingTotal = 0; var errorCount = 0; var options = new PingOptions { Ttl = TTL, DontFragment = DontFragment }; using (var ping = new System.Net.NetworkInformation.Ping()) { do { try { // Get timestamp var timestamp = DateTime.Now; // Send ping var pingReply = ping.Send(ipAddress, Timeout, Buffer, options); // Reset the error count (if no exception was thrown) errorCount = 0; if (pingReply == null || pingReply.Status != IPStatus.Success) { if (pingReply != null && pingReply.Address == null) { OnPingReceived(new PingReceivedArgs(timestamp, ipAddress, hostname, pingReply.Status)); } else if (pingReply != null) { OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, pingReply.Status)); } } else { if (ipAddress.AddressFamily == AddressFamily.InterNetwork) { OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status)); } else { OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Status)); } } } catch (PingException ex) { errorCount++; if (errorCount == ExceptionCancelCount) { OnPingException(new PingExceptionArgs(ex.Message, ex.InnerException)); break; } } pingTotal++; // If ping is canceled... dont wait for example 5 seconds for (var i = 0; i < WaitTime; i += 100) { Thread.Sleep(100); if (cancellationToken.IsCancellationRequested) { break; } } } while ((Attempts == 0 || pingTotal < Attempts) && !cancellationToken.IsCancellationRequested); } if (cancellationToken.IsCancellationRequested) { OnUserHasCanceled(); } else { OnPingCompleted(); } }, cancellationToken); }
public async Task Dns_GetHostEntryAsync_NullStringHost_Fail() { await Assert.ThrowsAsync <ArgumentNullException>(() => Dns.GetHostEntryAsync((string)null)); }
private async void StartScan() { DisplayStatusMessage = false; StatusMessage = string.Empty; IsScanRunning = true; PreparingScan = true; // Measure the time StartTime = DateTime.Now; stopwatch.Start(); dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); dispatcherTimer.Start(); EndTime = null; PortScanResult.Clear(); PortsOpen = 0; cancellationTokenSource = new CancellationTokenSource(); string[] hosts = Hostname.Split(';'); List <Tuple <IPAddress, string> > hostData = new List <Tuple <IPAddress, string> >(); for (int i = 0; i < hosts.Length; i++) { string host = hosts[i].Trim(); string hostname = string.Empty; IPAddress.TryParse(host, out IPAddress ipAddress); try { // Resolve DNS // Try to resolve the hostname if (ipAddress == null) { IPHostEntry ipHostEntry = await Dns.GetHostEntryAsync(host); foreach (IPAddress ip in ipHostEntry.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork && SettingsManager.Current.PortScanner_ResolveHostnamePreferIPv4) { ipAddress = ip; continue; } else if (ip.AddressFamily == AddressFamily.InterNetworkV6 && !SettingsManager.Current.PortScanner_ResolveHostnamePreferIPv4) { ipAddress = ip; continue; } } // Fallback --> If we could not resolve our prefered ip protocol if (ipAddress == null) { foreach (IPAddress ip in ipHostEntry.AddressList) { ipAddress = ip; continue; } } hostname = host; } else { try { IPHostEntry ipHostEntry = await Dns.GetHostEntryAsync(ipAddress); hostname = ipHostEntry.HostName; } catch { } } } catch (SocketException) // This will catch DNS resolve errors { if (!string.IsNullOrEmpty(StatusMessage)) { StatusMessage += Environment.NewLine; } StatusMessage += string.Format(Application.Current.Resources["String_CouldNotResolveHostnameFor"] as string, host); DisplayStatusMessage = true; continue; } hostData.Add(Tuple.Create(ipAddress, hostname)); } if (hostData.Count == 0) { StatusMessage += Environment.NewLine + Application.Current.Resources["String_NothingToDoCheckYourInput"] as string; DisplayStatusMessage = true; ScanFinished(); return; } int[] ports = await PortRangeHelper.ConvertPortRangeToIntArrayAsync(Ports); try { PortsToScan = ports.Length * hostData.Count; PortsScanned = 0; PreparingScan = false; HostnameHistory = new List <string>(HistoryListHelper.Modify(HostnameHistory, Hostname, SettingsManager.Current.Application_HistoryListEntries)); PortsHistory = new List <string>(HistoryListHelper.Modify(PortsHistory, Ports, SettingsManager.Current.Application_HistoryListEntries)); PortScannerOptions portScannerOptions = new PortScannerOptions { Threads = SettingsManager.Current.PortScanner_Threads, ShowClosed = SettingsManager.Current.PortScanner_ShowClosed, Timeout = SettingsManager.Current.PortScanner_Timeout }; PortScanner portScanner = new PortScanner(); portScanner.PortScanned += PortScanner_PortScanned; portScanner.ScanComplete += PortScanner_ScanComplete; portScanner.ProgressChanged += PortScanner_ProgressChanged; portScanner.UserHasCanceled += PortScanner_UserHasCanceled; portScanner.ScanAsync(hostData, ports, portScannerOptions, cancellationTokenSource.Token); } catch (Exception ex) // This will catch any exception { StatusMessage = ex.Message; DisplayStatusMessage = true; ScanFinished(); } }
public async Task Dns_GetHostEntryAsync_NullIPAddressHost_Fail() { await Assert.ThrowsAsync <ArgumentNullException>(() => Dns.GetHostEntryAsync((IPAddress)null)); }
public async Task Dns_GetHostEntryAsync_IPAddress_Ok() { IPAddress localIPAddress = await TestSettings.GetLocalIPAddress(); await TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(localIPAddress)); }
private static string GetIp(string hostname) => Dns.GetHostEntryAsync(hostname) .Result .AddressList .First(a => a.AddressFamily == AddressFamily.InterNetwork) .ToString();
public async Task Dns_GetHostEntryAsync_IPString_Ok() => await TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(TestSettings.LocalIPString));
internal async static Task <IPHostEntry> GetHostEntryFromName(String hostname) { IPHostEntry entry = await Dns.GetHostEntryAsync(hostname); return(entry); }
private async Task <bool> ReceiveMail(Stream reader, StreamWriter writer, string line, IPEndPoint endPoint) { IPHostEntry entry = await Dns.GetHostEntryAsync(endPoint.Address); MailFromResult result = await ParseMailFrom(null, reader, writer, line, endPoint); if (result == null) { return(false); } try { string subject; MimeMessage msg; using (Stream stream = File.OpenRead(result.BackingFile)) { msg = await MimeMessage.LoadAsync(stream, true, cancelToken); subject = msg.Subject; } subject = (subject ?? string.Empty).Trim(); if (subject.Equals("unsubscribe", StringComparison.OrdinalIgnoreCase)) { UnsubscribeHandler?.Invoke(result.From.Address, subject, msg.HtmlBody); return(true); } // mail demon doesn't have an inbox yet, only forwarding, so see if any of the to addresses can be forwarded foreach (var kv in result.ToAddresses) { foreach (MailboxAddress address in kv.Value) { MailDemonUser user = users.FirstOrDefault(u => u.MailAddress.Address.Equals(address.Address, StringComparison.OrdinalIgnoreCase)); // if no user or the forward address points to a user, fail if (user == null || users.FirstOrDefault(u => u.MailAddress.Address.Equals(user.ForwardAddress.Address, StringComparison.Ordinal)) != null) { await writer.WriteLineAsync($"500 invalid command - user not found"); await writer.FlushAsync(); } // setup forward headers MailboxAddress forwardToAddress = (user.ForwardAddress ?? globalForwardAddress); if (forwardToAddress == null) { await writer.WriteLineAsync($"500 invalid command - user not found 2"); await writer.FlushAsync(); } else { string forwardDomain = forwardToAddress.Address.Substring(forwardToAddress.Address.IndexOf('@') + 1); // create new object to forward on MailFromResult newResult = new MailFromResult { BackingFile = result.BackingFile, From = user.MailAddress, ToAddresses = new Dictionary <string, IEnumerable <MailboxAddress> > { { forwardDomain, new List <MailboxAddress> { forwardToAddress } } } }; // forward the message on and clear the forward headers MailDemonLog.Info("Forwarding message, from: {0}, to: {1}, forward: {2}", result.From, address, forwardToAddress); result.BackingFile = null; // we took ownership of the file SendMail(writer, newResult, endPoint, true, (prepMsg) => { prepMsg.Subject = $"FW from {result.From}: {prepMsg.Subject}"; prepMsg.Cc.Clear(); prepMsg.Bcc.Clear(); }).GetAwaiter(); return(true); // only forward to the first valid address } } } } finally { result.Dispose(); } return(true); }
/// <summary> /// Get all local ip addresses (non alloc version) /// </summary> /// <param name="targetList">result list</param> /// <param name="addrType">type of address (IPv4, IPv6 or both)</param> public static void GetLocalIpList(List <string> targetList, LocalAddrType addrType) { bool ipv4 = (addrType & LocalAddrType.IPv4) == LocalAddrType.IPv4; bool ipv6 = (addrType & LocalAddrType.IPv6) == LocalAddrType.IPv6; try { foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { //Skip loopback and disabled network interfaces if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback || ni.OperationalStatus != OperationalStatus.Up) { continue; } var ipProps = ni.GetIPProperties(); //Skip address without gateway if (ipProps.GatewayAddresses.Count == 0) { continue; } foreach (UnicastIPAddressInformation ip in ipProps.UnicastAddresses) { var address = ip.Address; if ((ipv4 && address.AddressFamily == AddressFamily.InterNetwork) || (ipv6 && address.AddressFamily == AddressFamily.InterNetworkV6)) { targetList.Add(address.ToString()); } } } } catch { //ignored } //Fallback mode (unity android) if (targetList.Count == 0) { #if NETCORE var hostTask = Dns.GetHostEntryAsync(Dns.GetHostName()); hostTask.Wait(); var host = hostTask.Result; #else var host = Dns.GetHostEntry(Dns.GetHostName()); #endif foreach (IPAddress ip in host.AddressList) { if ((ipv4 && ip.AddressFamily == AddressFamily.InterNetwork) || (ipv6 && ip.AddressFamily == AddressFamily.InterNetworkV6)) { targetList.Add(ip.ToString()); } } } if (targetList.Count == 0) { if (ipv4) { targetList.Add("127.0.0.1"); } if (ipv6) { targetList.Add("::1"); } } }
/// <summary> /// Initializes a new instance of the <see cref="ForwardedPortRemote"/> class. /// </summary> /// <param name="boundHost">The bound host.</param> /// <param name="boundPort">The bound port.</param> /// <param name="host">The host.</param> /// <param name="port">The port.</param> public ForwardedPortRemote(string boundHost, uint boundPort, string host, uint port) : this(Dns.GetHostEntryAsync(boundHost).Result.AddressList[0], boundPort, Dns.GetHostEntryAsync(host).Result.AddressList[0], port) { }
public void Resolve() { _hostname = Dns.GetHostEntryAsync(Destination.Address).ContinueWith <string>((t) => t.IsFaulted ? null : t.Result.HostName); }
/// <summary> /// Given a string that should identify an endpoint-address, resolve it to an actual IP address /// and set the Address property to a valid corresponding value. /// </summary> /// <param name="name">the endpoint-address to resolve</param> /// <param name="ip4Only">whether the address must be only-IPv4</param> /// <exception cref="InvalidException">The name must contain the colon delimiter.</exception> /// <exception cref="InvalidException">The specified port must be a valid nonzero integer.</exception> /// <exception cref="InvalidException">Must be able to find the IP-address.</exception> public void Resolve(string name, bool ip4Only) { // Find the ':' at end that separates address from the port number. int delimiter = name.LastIndexOf(':'); if (delimiter < 0) { throw new InvalidException(string.Format("TcpAddress.Resolve, delimiter ({0}) must be non-negative.", delimiter)); } // Separate the address/port. string addrStr = name.Substring(0, delimiter); string portStr = name.Substring(delimiter + 1); // Remove square brackets around the address, if any. if (addrStr.Length >= 2 && addrStr[0] == '[' && addrStr[addrStr.Length - 1] == ']') { addrStr = addrStr.Substring(1, addrStr.Length - 2); } // Get the port-number (or zero for auto-selection of a port). int port; // Allow 0 specifically, to detect invalid port error in atoi if not if (portStr == "*" || portStr == "0") { // Resolve wildcard to 0 to allow auto-selection of port port = 0; } else { // Parse the port number (0 is not a valid port). port = Convert.ToInt32(portStr); if (port == 0) { throw new InvalidException(string.Format("TcpAddress.Resolve, port ({0}) must be a valid nonzero integer.", portStr)); } } IPAddress ipAddress; // Interpret * as Any. if (addrStr == "*") { ipAddress = ip4Only ? IPAddress.Any : IPAddress.IPv6Any; } else if (!IPAddress.TryParse(addrStr, out ipAddress)) { #if NETSTANDARD1_3 || UAP var availableAddresses = Dns.GetHostEntryAsync(addrStr).Result.AddressList; #else var availableAddresses = Dns.GetHostEntry(addrStr).AddressList; #endif ipAddress = ip4Only ? availableAddresses.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork) : availableAddresses.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork || ip.AddressFamily == AddressFamily.InterNetworkV6); if (ipAddress == null) { throw new InvalidException(string.Format("TcpAddress.Resolve, unable to find an IP address for {0}", name)); } } Address = new IPEndPoint(ipAddress, port); }
public async Task <List <ActionResult> > CheckDNS(ILog log, string domain, bool?useProxyAPI = null, bool includeIPCheck = true) { var results = new List <ActionResult>(); log.Information("CheckDNS: performing DNS checks. This option can be disabled in Settings if required."); if (string.IsNullOrEmpty(domain)) { results.Add(new ActionResult { IsSuccess = false, Message = "CheckDNS: Cannot check null or empty DNS name." }); log.Error(results.Last().Message); return(results); } // if validation proxy enabled, DNS for the domain being validated is checked via our // remote API rather than directly on the servers bool useProxy = useProxyAPI ?? _enableValidationProxyAPI; if (useProxy) { // TODO: update proxy and implement proxy check here return (ok, message); } // check dns resolves to IP if (includeIPCheck) { try { log.Information($"Checking DNS name resolves to IP: {domain}"); var result = await Dns.GetHostEntryAsync(domain); // this throws SocketException for bad DNS results.Add(new ActionResult { IsSuccess = true, Message = $"CheckDNS: '{domain}' resolved to an IP Address {result.AddressList[0].ToString()}. " }); } catch { results.Add(new ActionResult { IsSuccess = false, Message = $"CheckDNS: '{domain}' failed to resolve to an IP Address. " }); log.Error(results.Last().Message); return(results); } } DnsMessage caa_query = null; DomainName dn = null; try { // check CAA dn = DomainName.Parse(domain); caa_query = DnsClient.Default.Resolve(dn, RecordType.CAA); } catch (Exception exp) { log.Error(exp, $"'{domain}' DNS error resolving CAA : {exp.Message}"); } if (caa_query == null || caa_query.ReturnCode != ReturnCode.NoError) { // dns lookup failed results.Add(new ActionResult { IsSuccess = false, Message = $"CheckDNS: '{domain}' failed to parse or resolve CAA. " }); log.Error(results.Last().Message); return(results); } if (caa_query.AnswerRecords.Where(r => r is CAARecord).Count() > 0) { // dns returned at least 1 CAA record, check for validity if (!caa_query.AnswerRecords.Where(r => r is CAARecord).Cast <CAARecord>() .Any(r => (r.Tag == "issue" || r.Tag == "issuewild") && r.Value == "letsencrypt.org")) { // there were no CAA records of "[flag] [tag] [value]" where [tag] = issue | // issuewild and [value] = letsencrypt.org // see: https://letsencrypt.org/docs/caa/ results.Add(new ActionResult { IsSuccess = false, Message = $"CheckDNS: '{domain}' DNS CAA verification failed - existing CAA record prevent issuance for letsencrypt.org CA." }); log.Warning(results.Last().Message); return(results); } } // now either there were no CAA records returned (i.e. CAA is not configured) or the CAA // records are correctly configured // check DNSSEC var dnssec = new DnsSecRecursiveDnsResolver(); try { log.Information("Checking DNSSEC resolution"); var res = await dnssec.ResolveSecureAsync <ARecord>(dn); var isOk = res.ValidationResult != DnsSecValidationResult.Bogus; if (isOk) { results.Add(new ActionResult { IsSuccess = true, Message = $"CheckDNS: '{domain}' DNSSEC Check OK - Validation Result: {res.ValidationResult.ToString()}" }); } else { results.Add(new ActionResult { IsSuccess = isOk, Message = $"CheckDNS: '{domain}'DNSSEC Check Failed - Validation Result: {res.ValidationResult.ToString()}" }); } } catch (DnsSecValidationException exp) { // invalid dnssec results.Add(new ActionResult { IsSuccess = false, Message = $"CheckDNS: '{domain}'DNSSEC Check Failed - {exp.Message}" }); log.Warning(results.Last().Message); } catch (Exception exp) { // domain failed to resolve from this machine results.Add(new ActionResult { IsSuccess = false, Message = $"CheckDNS: '{domain}' DNS error resolving DnsSecRecursiveDnsResolver - {exp.Message}" }); } return(results); }
/// <summary> /// Populates the list with devices connected on LAN /// </summary> /// <param name="view">UI controls</param> /// <param name="InterfaceFriendlyName"></param> public static void StartScan(IView view, string InterfaceFriendlyName) { #region initialization if (capturedevice != null) { GatewayCalled = false; BackgroundScanDisabled = true; capturedevice.StopCapture(); capturedevice.Close(); capturedevice = null; } else { ClientList = new Dictionary <IPAddress, PhysicalAddress>(); Main.Devices = new ConcurrentDictionary <IPAddress, Device>(); } #endregion //Get list of interfaces CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance; //crucial for reflection on any network changes capturedevicelist.Refresh(); capturedevice = (LibPcapLiveDevice)(from devicex in capturedevicelist where ((LibPcapLiveDevice)devicex).Interface.FriendlyName == InterfaceFriendlyName select devicex).ToList()[0]; //open device in promiscuous mode with 1000ms timeout capturedevice.Open(DeviceModes.Promiscuous, 1000); //Arp filter capturedevice.Filter = "arp"; IPAddress myipaddress = AppConfiguration.LocalIp; //Probe for active devices on the network if (DiscoveryTimer == null) { StartDescoveryTimer(); } #region Retrieving ARP packets floating around and find out the sender's IP and MAC //Scan duration long scanduration = 10000; RawCapture rawcapture = null; //Main scanning task ScannerTask = Task.Run(() => { try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (stopwatch.ElapsedMilliseconds <= scanduration) { if (capturedevice.GetNextPacket(out PacketCapture packetCapture) != GetPacketStatus.PacketRead) { continue; } rawcapture = packetCapture.GetPacket(); Packet packet = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data); ArpPacket ArpPacket = packet.Extract <ArpPacket>(); if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize)) { ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress); string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress); string ip = ArpPacket.SenderProtocolAddress.ToString(); var device = new Device { IP = ArpPacket.SenderProtocolAddress, MAC = PhysicalAddress.Parse(mac.Replace(":", "")), DeviceName = "Resolving", ManName = "Getting information...", DeviceStatus = "Online" }; //Add device to UI list view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); })); //Add device to main device list _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device); //Get hostname and mac vendor for the current device _ = Task.Run(async() => { try { #region Get Hostname IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip); device.DeviceName = hostEntry?.HostName ?? ip; #endregion #region Get MacVendor var Name = VendorAPI.GetVendorInfo(mac); device.ManName = (Name is null) ? "" : Name.data.organization_name; #endregion view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); })); } catch (Exception ex) { try { if (ex is SocketException) { var Name = VendorAPI.GetVendorInfo(mac); device.ManName = (Name is null) ? "" : Name.data.organization_name; view.ListView1.BeginInvoke(new Action(() => { device.DeviceName = ip; view.ListView1.UpdateObject(device); })); } else { view.MainForm.BeginInvoke( new Action(() => { device.DeviceName = ip; device.ManName = "Error"; view.ListView1.UpdateObject(device); })); } } catch { } } }); } int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100); view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning " + percentageprogress + "%")); } stopwatch.Stop(); view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = ClientList.Count.ToString() + " device(s) found")); //Initial scanning is over now we start the background scan. Main.OperationIsInProgress = false; //Start passive monitoring BackgroundScanStart(view); } catch { //Show an error in the UI in case something went wrong try { view.MainForm.BeginInvoke(new Action(() => { view.StatusLabel.Text = "Error occurred"; view.PictureBox.Image = Properties.Resources.color_error; })); } catch { } //Swallow exception when the user closes the app during the scan operation } }); #endregion }
/// <summary> /// Gets called by the logic of the <see cref="CommandAttribute" />. /// </summary> private async Task <int> OnExecuteAsync() { if (UseIpV6) { UseIpV4 = false; } if (Endless) { Repeats = int.MaxValue; } Console.WriteLine($"Starting pinging host {Host} on {ResolvedProtocol} port(s) {PortRange} {(Endless ? "infinite" : Repeats.ToString())} times:"); var reachablePorts = 0; var closedPorts = 0; var hostIp = "-"; if (ResvoleAddress) { // we have to perform address resolution var entry = await Dns.GetHostEntryAsync(Host); if (entry.AddressList.Any()) { var target = UseIpV4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6; hostIp = entry.AddressList.FirstOrDefault(he => he.AddressFamily == target)?.ToString() ?? "?"; } } // start the process var currentPack = 0; for (var i = 0; i < Repeats; ++i) { var allPortsOpen = true; foreach (var port in Ports) { try { var portOpen = NetworkUtil.IsPortOpened(Host, port, Timeout, UseUdp); allPortsOpen &= portOpen; reachablePorts += portOpen ? 1 : 0; closedPorts += portOpen ? 0 : 1; var printResult = portOpen ? "OPEN" : "CLOSED"; if (Detailed && !portOpen) { printResult += $" ({NetworkUtil.LastCheckResult.ToString()})"; } Console.Write("#{0,4} -> Pinging host {1} (IP:{2}) on {5} port {3} with timeout {4}: ", ++currentPack, Host, hostIp, port, Timeout, ResolvedProtocol); Console.ForegroundColor = portOpen ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed; Console.WriteLine(printResult); Console.ResetColor(); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"#{++currentPack,4} Error pinging host {Host}: {ex.Message}"); Console.ResetColor(); } } if (!AutoStop || !allPortsOpen) { if (WaitTime > 0) { await Task.Delay(WaitTime); } } else { break; } } Console.WriteLine("Finished pinging host {0} (IP:{1}). {2} pings sent ({3} OPEN, {4} CLOSED)", Host, hostIp, currentPack, reachablePorts, closedPorts); if (ReportFailedOnExit) { // return error level 1 if all pings where closed and 0 if any of them was open return(reachablePorts > 0 ? 0 : 1); } if (ReportSucceededOnExit) { // return the amount of opened pings as the error level return(reachablePorts); } return(0); }