Tuesday, January 15, 2013

Rewrite DNS Request with Fiddler

Today one of my colleagues had a situation where they needed a piece of software to communicate with a test webservice. However, we could not find a way to configure the software to use a custom webservice url. So enters Fiddler into the picture. When you want a url, say sub.domain.com, to end up sending the request to sub-test.domain.com, you can use a custom rule in Fiddler. This is at a higher level than the HOSTS file, by actually re-writing the request to a different domain name before the DNS translation and request are even made - just changing the DNS routing with HOSTS file may not work because of host header rules on the server side.

To accomplish this, open Fiddler, and navigate to the Rules menu -> Customize Rules. It should open the file customRules.js in your default editor (probably Notepad). You'll see that this file contains some default rules out-of-the-box. Also, there are some example rules given in comments that allow you to highlight certain requests, or modify any part of the request/response cycle, which of itself is a very powerful feature.

We are interested in adding a rule to OnBeforeRequest. Find the function call for OnBeforeRequest in about the middle of the file, and drop down to the end of the method. We will add a rule like this:

if (oSession.HostnameIs("sub.domain.com")) {
    oSession.hostname = "sub-test.domain.com";
}


This says that when the domain name "sub.domain.com" is encountered in a request, then the request hostname should be rewritten to "sub-test.domain.com". Since this occurs in the OnBeforeRequest event, the rewriting occurs even before the request is made, so the DNS translation applies to the new domain name instead. The server can't tell the difference, and thinks it's just a request for sub-test.domain.com, which makes for a very clean redirect. Then the response comes back into Fiddler, and back to the calling software, which doesn't know that its request was rewritten.

Hope this helps. Happy programming! :)

No comments:

Post a Comment