HIGH dns cache poisoningaspnet

Dns Cache Poisoning in Aspnet

How Dns Cache Poisoning Manifests in Aspnet

DNS cache poisoning in ASP.NET applications typically occurs when the framework or application code relies on DNS resolution without proper validation or timeout controls. This vulnerability allows attackers to redirect traffic by poisoning DNS caches, potentially leading to man-in-the-middle attacks, credential theft, or data exfiltration.

In ASP.NET, DNS cache poisoning can manifest through several specific pathways:

  • HttpClient default behavior: ASP.NET's HttpClient uses the default .NET DNS resolver, which caches DNS results for 60 seconds by default. If an attacker poisons the DNS cache during this window, all subsequent requests from the application will be redirected.
  • System.Net.Dns.GetHostEntry: This synchronous method caches DNS results indefinitely unless explicitly configured otherwise, making it particularly vulnerable to long-term poisoning.
  • ServicePointManager settings: ASP.NET applications that don't configure ServicePointManager.DnsRefreshTimeout leave themselves exposed to cached DNS responses.
  • External service calls: When ASP.NET applications call external APIs, payment processors, or OAuth providers, poisoned DNS responses can redirect these calls to malicious endpoints.

The attack typically unfolds as follows: An attacker compromises a DNS server or uses a man-in-the-middle position to inject false DNS records. When the ASP.NET application resolves a domain name, it receives the poisoned response. For the next 60 seconds (or indefinitely if ServicePointManager isn't configured), all requests to that domain are sent to the attacker's server.

Real-world impact includes: intercepting OAuth redirects during authentication flows, redirecting payment processing to fake endpoints, or exfiltrating API keys through malicious endpoints that log all incoming requests.

Aspnet-Specific Detection

Detecting DNS cache poisoning vulnerabilities in ASP.NET requires examining both configuration and runtime behavior. Here are specific detection methods:

Configuration Analysis: Check your web.config and application startup code for these indicators:

<system.net>
  <settings>
    <!-- Vulnerable: default 60-second cache -->
    <dns refreshTimeout="60000" />
  </settings>
</system.net>

Code Review: Look for these vulnerable patterns in your ASP.NET codebase:

// Vulnerable: uses default caching
var ip = System.Net.Dns.GetHostEntry("api.example.com");

// Vulnerable: HttpClient with default settings
var client = new HttpClient();
var response = await client.GetAsync("https://api.example.com/data");

Runtime Monitoring: Monitor for unusual network behavior:

  • Sudden IP address changes for frequently accessed domains
  • Unexpected SSL certificate warnings from known services
  • Unusual response times or content from external APIs

middleBrick Scanning: The middleBrick scanner specifically tests for DNS-related vulnerabilities in ASP.NET applications. It examines:

  • DNS resolution configurations in web.config
  • HttpClient usage patterns that may be vulnerable to cache poisoning
  • External service integrations and their DNS handling
  • ServicePointManager configurations

When you scan an ASP.NET API endpoint with middleBrick, it performs black-box testing to identify these vulnerabilities without requiring access to your source code. The scanner tests the unauthenticated attack surface and provides a security risk score with specific findings about DNS-related weaknesses.

Network-level Detection: Use network monitoring tools to detect DNS anomalies:

# Monitor DNS queries from your ASP.NET app
# Look for unexpected IP addresses or rapid changes
tcpdump -i eth0 port 53 or port 853

Aspnet-Specific Remediation

Securing ASP.NET applications against DNS cache poisoning requires both configuration changes and code-level fixes. Here are specific remediation strategies:

Configuration-based Fixes: Modify your web.config to reduce DNS caching time:

<system.net>
  <settings>
    <!-- Reduced to 5 seconds for better security -->
    <dns refreshTimeout="5000" />
  </settings>
</system.net>

Code-based Solutions: Implement DNS caching controls in your application code:

// Option 1: Use HttpClient with DNS refresh
var handler = new HttpClientHandler();
handler.DnsRefreshTimeout = TimeSpan.FromSeconds(5);

var client = new HttpClient(handler);
var response = await client.GetAsync("https://api.example.com");

// Option 2: Clear DNS cache programmatically
public static class DnsCache
{
    public static void ClearHostEntryCache()
    {
        var cache = typeof(System.Net.Dns)
            .GetField("hostNameCache", BindingFlags.NonPublic | BindingFlags.Static)
            .GetValue(null);
        
        var entries = cache.GetType()
            .GetField("entries", BindingFlags.NonPublic | BindingFlags.Instance)
            .GetValue(cache);
            
        var table = entries.GetType()
            .GetMethod("Clear")
            .Invoke(entries, null);
    }
}

ServicePointManager Configuration: Set global DNS refresh timeout:

using System.Net;

// Set DNS refresh timeout to 5 seconds
ServicePointManager.DnsRefreshTimeout = 5000;

// Also consider setting expect 100-continue
ServicePointManager.Expect100Continue = false;

External Service Security: When calling external services, implement certificate pinning and use HTTPS with strict validation:

// Example: Certificate pinning for external API calls
public class PinnedCertificateHttpClientHandler : HttpClientHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var certSubject = "CN=api.example.com"; // Expected certificate
        var chain = new X509Chain();
        
        var asyncCallback = new ServicePointAsyncCallback((sp, req, c, s, e) =>
        {
            var sslPolicyErrors = (SslPolicyErrors)e;
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                throw new Exception("SSL certificate error");
            }
        });
        
        request.Headers.Add("Host", "api.example.com");
        return await base.SendAsync(request, cancellationToken);
    }
}

Monitoring and Alerting: Implement monitoring to detect potential DNS poisoning attempts:

// Log DNS resolution changes
public class SecureHttpClient : HttpClient
{
    private readonly ILogger _logger;
    private readonly string _expectedHost;
    private readonly string _expectedIP;
    
    public SecureHttpClient(ILogger logger, string expectedHost, string expectedIP)
    {
        _logger = logger;
        _expectedHost = expectedHost;
        _expectedIP = expectedIP;
    }
    
    public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var host = request.RequestUri.Host;
        var ip = await GetHostIPAddress(host);
        
        if (ip != _expectedIP)
        {
            _logger.LogWarning($"DNS resolution changed for {host}: {ip} (expected: {_expectedIP})");
            throw new Exception("DNS resolution mismatch detected");
        }
        
        return await base.SendAsync(request, cancellationToken);
    }
}

Frequently Asked Questions

How does DNS cache poisoning differ from DNS spoofing?

DNS cache poisoning is a specific attack technique that involves injecting false DNS records into a DNS resolver's cache, causing it to return incorrect IP addresses for a period of time. DNS spoofing is a broader term that encompasses various techniques to provide false DNS responses, including cache poisoning, but also on-path attacks and response forgery. In ASP.NET applications, cache poisoning is particularly concerning because the framework's default DNS caching behavior can maintain the poisoned state for up to 60 seconds, giving attackers a window to intercept traffic.

Can middleBrick detect DNS cache poisoning vulnerabilities in my ASP.NET application?

Yes, middleBrick performs black-box scanning that can identify DNS-related vulnerabilities in ASP.NET applications. The scanner examines your API's unauthenticated attack surface and tests for weaknesses including DNS resolution configurations, external service integrations, and caching behaviors. It provides a security risk score (A-F) with specific findings about DNS vulnerabilities, along with remediation guidance. The scan takes 5-15 seconds and requires no credentials or agents—just submit your API URL to receive a comprehensive report.