Channels ▼


Detecting Man in the Middle Attacks with DNS

Some people are apathetic about security, preferring to accept risks rather than expend energy or resources in self defense. Such is the case when it comes to the Man In The Middle threat and its enabler, DNS. Everyone knows that DNS lacks security features, and its use makes every endpoint on the network vulnerable to a variety of attacks. The conventional solution to this problem is Secure Sockets Layer (SSL) or some mix of symmetric and asymmetric cryptography. Secure servers get assigned asymmetric key pairs, or some shared secret key, and everyone who wishes to communicate in confidence with a particular server takes special care to verify the identity of the server by matching the public key offered by the server against the public key believed to be authentic and valid for that server. The problem with these solutions is that they typically fail to provide trustworthy authentication of the identity of the server. Even if the desired encryption is accomplished properly, there is simply no telling with whom you’re actually communicating. This is due primarily to bad implementations that attempt to automate trust, rather than being caused by cryptographic flaws in algorithms.

SSL offers particularly ill-conceived server authentication for most users and in most applications. First, nobody bothers to make a note of the public key assigned to a particular third-party server and verify it each time communications with that server are initiated. Anyone who engages in sensitive SSL-encrypted communications without personally verifying the public key offered as authentication by the server loses the very security they think they are gaining by placing blind trust in unknown third-party businesses and systems administrators. And importantly, when the owner of a secure server changes public keys, rarely do they bother to tell anyone. This makes it impossible to differentiate a well-executed Man in The Middle (MITM) attack from a planned system administration change. A technical means of restricting SSL connections to only servers that offer predetermined, trusted public keys was shown for .NET in the September 2003 issue of Windows Developer Network (

Other than the news media and security mailing lists, no channel of reliable and secure communication exists to publicize system administration changes that result in new cryptographic keys. I’ve never seen anyone publish their latest SSL certificate so that security-conscious users will know what to look for when authenticating the trusted server in the future. In the absence of such a channel, there is no way to alert users when it is discovered that a server’s private key has been stolen and is being used to mount attacks. Without this communications channel, the people who most urgently need to know when a key is compromised either won’t get the message in time or they won’t understand the steps to take to revoke trust in a compromised key. It’s easy to see that computer security belongs only to those who care about it enough to put effort into it. If product vendors would stop keeping their source code secret, we could free ourselves of this dumb-down effect, and do something about security ourselves.

Our willingness to rely on and trust DNS for ‘vanity addressing’ is fundamentally to blame for some of our problems. The client-side bug in Windows’ SSL server authentication (see Microsoft Knowledge Base article Q329115 Certificate Validation Flaw Could Enable Identity Spoofing) allowed anyone in possession of a valid SSL certificate to use that certificate as an intermediate Certificate Authority (CA) for the purpose of issuing arbitrary SSL certificates for any Fully Qualified Domain Name (FQDN). This condition gives anyone the ability to successfully exploit end users’ misplaced trust in DNS. It is truly the worst-case-scenario failure for security features that incorporate DNS domains for vanity and commercial trademark reasons. It isn’t even a hypothetical failure. Microsoft’s implementation of SSL failed to provide any server authentication for years until one smart programmer named Mike Benham noticed the flaw and said something about it (see

Speaking from personal experience as somebody who has created commercial web sites that obliged end users to risk trusting DNS, I’ve put considerable effort into protections and countermeasures that may help to detect MITM attacks that exploit DNS insecurity. Under normal circumstances, without including additional communication steps such as telephone calls or cryptographic token generators that can establish a new session identifier or server authentication token that the end user can use to authenticate with and verify the identity of a web server, end users’ web browser requests can always be hijacked completely without our knowledge. When our users’ client requests are diverted in their entirety to a network node that is under an attacker’s control, the only detection mechanism possible is a report from an end user that our site has been defaced or hijacked. We can create automated client browser farms that poll our servers periodically and report what they see. A few third-party services have been created along these lines, though most of them do not seem to stick around very long nor do they focus on security. Rather than scanning for evidence of spoofing attacks, defacement, or DNS hijacking, these services have typically focused on monitoring for DoS conditions and other service outages.

There are several attack scenarios that pose special problems for end-user security when outright hijacking of client requests occurs, such as the display of a web site that looks exactly like the authentic one, which is in fact indistinguishable from the authentic site because the attacker has redirected the client through tampering with DNS so that even the URL matches that of the authentic site. Many web sites allow end users to type in credentials on a Web page that is not SSL-secured, with a FORM set to POST to an https:// address. The end user has no way to know where the HTML FORM is going to POST, and sees no reason to doubt the authenticity of the unencrypted Web page, so they make the mistake of trusting the credentials FORM based only on the DNS lookup that occurred to direct their Web browser to the attacker’s server. There are a number of things the attacker can do after capturing the user’s credentials, such as display an innocent-looking error message and then reverse the DNS tampering. A little JavaScript or some written instructions that cause the user to close the browser window and restart flushes the previous DNS lookup from cache and when the end user tries again they reach the authentic web site, unaware that their credentials were just intercepted. Have you ever been taken by this exploit? If you’ve ever seen an error message when trying to login to a password protected web site, and you didn’t view the source of the Web page, make a note of the IP address of the server you’ve just contacted, save a copy of the server’s SSL certificate for future reference, or performed other real-time forensic logging and analysis of the cause of the error message, then the honest answer is you really don’t know.

At any time prior to Mike Benham’s August 5, 2002 disclosure of the authentication flaw (Q329115) in Microsoft’s SSL code did you make use of Internet Explorer to communicate with SSL-secured web sites? Unless you personally verified the SSL certificate offered by the server or have some forensic log of your Internet usage from the time period in question, you can’t possibly know whether or not you have been the victim of a MITM attack that used a self-issued SSL certificate signed by an invalid intermediate CA that Internet Explorer trusted improperly.

Practice Paranoia

The ease with which hijacking attacks can be mounted, whether they are achieved through TCP/IP routing or spoofing techniques, or whether they rely on DNS poisoning, spoofing, or penetration of DNS server security (either authoritative nameservers for a domain or recursive or cache-only DNS servers that distribute lookup services to the edge of the network) makes the hijacking style attack less interesting than the MITM style attack. To summarize bluntly, the end user has no hope of security, and should be given no expectation of it, either, unless they educate themselves and practice paranoid information security countermeasures. Since the end user won’t even be sending requests to your servers in the hijacking scenario, there’s really nothing you can do about this threat either, except complain that the computer industry in your country doesn’t really care about security so you’re moving to Bermuda.

Many MITM attacks, however, can be detected. The reason is that these attacks necessitate that the ‘Man’ in the middle actually be in the middle with respect to request processing. The setup for a MITM attack is identical to a hijacking attack, except that the authentic server is needed by the attacker to give the end user access to the expected computing services or resources. The end user has no clue that they are communicating through an unauthorized third-party proxy server. In many ways the client-side proxy server farms operated by certain ISPs (e.g., AOL, MSN, etc.) function precisely the way that any malicious MITM would function, except they presumably don’t eavesdrop on the communications they facilitate. The existence of client-side proxy farms significantly complicates detection of unauthorized MITM proxies, but enough talk, let’s get on with the source code for the MITM detection countermeasure. The source code shown below works with ASP.NET under IIS but the concept can be adapted to any server environment and platform.

The MITM detection technique I call “DNS Pooling” works by forcing the client to send requests to multiple domains in order to enable the server to compare and match the remote IP address of each client connection. If the client’s IP address is the same in every request, then your IIS box is able to deduce that DNS resolution for the domains has not been poisoned or hijacked from the perspective of that particular client. The key feature of this countermeasure is utilizing a pool of domains and obtaining DNS hosting from a different ISP for each domain. To bypass this security countermeasure, a malicious man in the middle has to filter every response from IIS to modify absolute URLs that don’t reference the hijacked domain—DNS hijacking is no longer a viable option as a means to insert a MITM undetected by IIS. The attacker will then have to act as a MITM for those requests, too, and perform address translation to map the modified URLs back to the originals for requests it initiates to those servers in order to retrieve content that the user expects. Even if the MITM hijacks every domain in the domain pool, IIS can still detect the attack and automatically lock out the malicious proxy server by IP address.

This countermeasure works because of the way that changes to DNS propagate out in waves from the authoritative nameservers to subordinate DNS servers that only cache lookup results. Provided that the domains in the domain pool are used by end users to access live web sites, and provided that there is enough traffic to those domains, each request made by an end user for content from a server located at one of the domains creates a ping of the DNS health of the servers at the other domains. If a MITM hijacks one of the domains and redirects requests for content from that domain to a malicious proxy server, the authentic server will be able to detect that the IP address for the request relayed by the proxy server is different than the IP address used by the authentic client to make the other requests to the other domains that have not been hijacked. There are several variations to this defense, and they all require the server to keep track of and match client IP addresses for requests across multiple domains. The simplest variation of this defense uses only two domains and a simple dynamic URL that is generated by the server and given to the client to request. The client can be given the dynamic URL as a hyperlink, as part of an <img> tag, or as a frame in a frameset—whatever makes the most sense for the application. The dynamic URL points at the second domain, not the one that the Web browser was directed to in its request for the page.

A dynamic URL is necessary to decrease the likelihood that an authorized friendly proxy server between the client and server will serve the URL out of cache when the client requests it. To simplify deployment of this defense, the server that generates the dynamic URL can embed the client’s IP address, or an encoded form of it, in the URL path. The server must also process the response dynamically so that it can parse out the encoded IP address and match it against the IP address from which the request arrived at the server. If a malicious MITM relays the request for the dynamic URL from the client, the MITM will expose its IP address to IIS. The simple fact that the client IP address is different in the request to the dynamic URL than it was in the request to the initial URL is proof that two network nodes were involved in making the request rather than just one.

Automated Detection

The following code demonstrates a dynamic URL generator written in C# for use in ASP.NET, implemented as a static class method, and its corresponding parser module that singles out MITM attackers by detecting multiple IP address mismatches originating from the same IP address. To keep the code simple so that it makes sense easily, the dynamic URL is constructed by appending the client’s IP address to ‘http://FQDN/dynamic/’ exclusive of the dots (periods) in the dotted quad IP address and giving the resulting URL a .jpg file extension. Replace FQDN with a fully qualified domain name by which your IIS box is also accessible, but be sure to use a domain other than the one that serves the Web application. Do the same thing in reverse to deploy this same countermeasure as part of a Web application served from the FQDN so that the two domains depend on each other for DNS hijacking MITM automated detection.

This design variation is only the simplest of the potential embodiments of this automated DNS hijacking MITM countermeasure. It doesn’t provide a defense against a MITM that serves requests for .jpg files out of cache instead of relaying them on to the authentic HTTP server, but it demonstrates the countermeasure concept so that you can enhance the defense with your own server-side security policy. This minimal countermeasure design, as shown, does provide a defense against a MITM attack that has not itself been designed to detect and circumvent this variation of the countermeasure by selectively relaying requests from the client to the authentic server and cleansing client requests of any identifying dynamic elements. To eliminate all possible attacker circumvention of this automated DNS hijacking countermeasure requires a more complex server-side awareness of the countermeasure and its role in securing client sessions, including a security policy that says the server will not allow a client session to proceed until the dynamic URL issued to the client gets requested. In this case the only way for the attacker to circumvent this countermeasure is to hide, which means the attacker is forced to attack by hijack rather than MITM.

using System;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Collections;
namespace MITMCounterMeasure {
public class MITMCounterMeasureModule : System.Web.IHttpModule {
SortedList KnownClients = new SortedList(131072);
SortedList MITMSuspects = new SortedList(10240);
public void Init(HttpApplication context) {
context.AuthorizeRequest += new EventHandler(this.MITMDetect); }
public void Dispose() {}
public static String GenerateDynamicURL(String ClientIPAddress) {
String sURL = "http://FQDN/dynamic/";
sURL = sURL + ClientIPAddress.Replace(".",null) + ".jpg";
return(sURL); }
public void MITMDetect(object sender,EventArgs e) {
HttpApplication app = (HttpApplication)sender;
try { String addr = app.Request.UserHostAddress;
addr = addr.Replace(".",null);
if(MITMSuspects.Contains(addr)) {
throw(new Exception("MITM Suspect: Request Denied")); }
String urlpath = app.Request.Url.AbsolutePath;
int i = urlpath.IndexOf("/dynamic/");
if(i > -1) {
i = i + 9;
String s = urlpath.Substring(i,urlpath.IndexOf(".")-i);
String v = null;
if(!s.Equals(addr)) {
if(KnownClients.Contains(addr)) {
v = (String)KnownClients.GetByIndex(KnownClients.IndexOfKey(addr));
if(!v.Equals(s)) {
throw(new Exception("Second IP address mismatch different from first 
mismatch: MITM suspect identified"));
else {
// send data to client; in this example the response is a JPEG image
catch(Exception ex) {
app.Response.Write("<html><body><h1>Error Processing 
app.CompleteRequest(); }

This code verifies that the client IP address matches the address encoded in the URL as an unauthorized proxy server detection countermeasure. This is the simplest of the possible multiple-domain anti-DNS-poisoning countermeasures enabled by virtue of the fact that changes to DNS cache always propagate unevenly from different authoritative DNS servers for different domains. Even if a DNS hijacker takes over the authoritative DNS servers for each domain used to accomplish this countermeasure, the attacker is unable to guarantee that the DNS poisoning will spread evenly throughout the network of subordinate DNS servers. That is, there will always be a period of time during which certain DNS servers on the network contain a mix of authentic DNS information for one or more of the hijacked domains and poisoned information for one or more of the hijacked domains. This time window represents an opportunity to detect the DNS hijacking and defend IIS against it. The amount of time in this window can be influenced, though not controlled precisely, through the Time To Live (TTL) setting in each domain’s authoritative DNS server.

ASP.NET provides an improved architecture for layering-in IIS code modules that participate in HTTP request processing. ASP.NET layered code modules are meant to replace the legacy ISAPI architecture, rescue IIS developers and IIS administrators from DLL Hell, and provide a solution that eliminates the difficulty of writing secure code in C/C++. The C# code shown in this section to implement the simplest potential DNS hijacking MITM countermeasure relies on the ASP.NET IHttpModule interface. It only works if you set up a file mapping for .jpg files in the web site application configuration that instructs IIS to use the ASP.NET script engine to process requests for all JPEG image files. When you build the code using the C# compiler, you will typically assign the code a strong name using the .NET Strong Name Utility (SN.EXE) and Assembly Linker (AL.EXE) and you must also deploy the IHttpModule to an ASP.NET-enabled server by modifying the machine.config file in the Microsoft.NET CONFIGURATION directory. Add the namespace and class name for the MITMCounterMeasureModule to the list of HttpModules as shown:

< httpModules> < add name="MITMCounterMeasure"
< /httpModules>

A single IP address mismatch may be caused by an end user with a dynamic IP address whose IP address changes, but more than one mismatch relayed to IIS from the same IP address indicates, as shown in the parser source code, the presence of an unauthorized MITM. This means that the malicious MITM can hijack one client undetected but the second hijacking triggers detection and the automated countermeasure. If you’re worried about dialup users who use the same DHCP address pool ending up with the same IP address one after another in sequence, such that this source code would trigger a MITM defense against the second innocent end user whose dynamic IP address changed while using your server, you can increase the number of hijackings permitted per IP address. Alternately, you could implement a more comprehensive variation of this MITM countermeasure that keeps track of client sessions and authentication events in addition to IP addresses and uses extra information gathered about the context of the client request to avoid locking out any end users inappropriately.

Friend or Foe

Worthy of note here is the fact that you know a MITM attack may be occurring when authentication credentials for more than one user account are provided from the same IP address. The only legitimate explanation for this is that all of the authentic users whose credentials were relayed to your IIS box from the same IP address rely on the same proxy/firewall or DHCP server to access the Internet. In this case the MITM is authorized on behalf of the users to function as a MITM and SSL-secured connections are trustworthy because the MITM simply relays encrypted data to and from the clients it services. There are other ways to add context-sensitive meaning to a series of requests that can be made to relate to one another across domains or over time. Developing new security techniques along these lines would be certain to yield workable real-world solutions if not for the fact that MSN, AOL, and other ISPs really don’t care about security, either. If they did, they would never have built and deployed client-side transparent proxy farms that look exactly like any other malicious MITM from the perspectives of both the client and our servers.

Since we already place all of our eggs in one shopping basket (made possible by VeriSign, RSA Security, and Microsoft), obscure the technical details of security from end users just because public keys and IP addresses have more digits than your average telephone number, and force users to accept the risk of using DNS without bothering to educate them about these risks, we have needlessly deprived ourselves and the public of meaningful security. We are losing the war on complexity because the illusion of security is beneficial to business interests that can’t be bothered to provide us with answers to questions such as “what reason do we have to feel safe?” and “how do we restore that feeling when something happens that takes it from us?"

Microsoft states that the SQL Slammer and Blaster security patches were released prior to the date of the exploits. But these worms were just the first self-replicating code launched as an attack against the affected open ports on Windows boxes. Malicious code to exploit the vulnerabilities was available to the public well in advance of these worms, yet it is the worms that Microsoft focuses on as though they were the only exploits. “Zero-day” threats that hit Windows boxes, especially such attacks that exploit flaws that are successfully kept secret for long periods of time, are the real reason we all care about information security. Microsoft makes it seem as though the only thing we have to worry about is the minor inconvenience caused by DoS of our network bandwidth when an otherwise-harmless worm infects our Windows boxes and tries to make a billion copies of itself by attacking other hosts. This is a limited interpretation of the information security threat. We have to ask ourselves if we should have confidence in a company that still thinks that DoS conditions caused by silly worms are the security threats that matter the most.

Jason Coombs works as forensic analyst and expert witness in court cases involving digital evidence. Information security and network programming are his areas of special expertise. He can be reached at [email protected].

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.