Fiddler如何自动修改请求和响应包

Charles的Map功能可以将某个请求进行重定向,用重定向的内容响应请求的内容。这个功能非常方便。在抓包过程当中,有时候为了调试方便,需要将线上的服务定位到内网。比如我们线上的服务器域名为 api.example.com,而内网的用于调试的服务器域名为 test.neiwang.com,那么就需要将所有域名 api.example.com替换为 test.neiwang.com,就可以使用charles的这个功能,但是charles是收费软件,使用破解版又可能不安全,所以我们需要用一款免费抓包工具来代替,fiddler就是个不错的选择。但是fiddler并没有map功能,不过没关系,我们可以通过编写脚本来实现这个功能。
Fiddler菜单中,Rules->Custon Rules,或按Ctrl+R键,编辑ScriptEditor代码文件,在OnBeforeRequest函数(static function OnBeforeRequest(oSession: Session))里面加上几句代码:
端口不同:

if (oSession.host.ToLower=="https://api.example.com:8080") {
    oSession.host="http://test.neiwang.com:9090";
}

端口相同:

if (oSession.HostnameIs("www.bayden.com")) {
  oSession.hostname="test.bayden.com";
}


拓展开来,如果我们需要修改请求和响应信息,应该怎么编写代码呢?
1.增加请求头:

oSession.oRequest["NewHeaderName"] = "New header value";

2.将请求的某个页面替换为同一个站点的不同页面

if (oSession.PathAndQuery=="/version1.css") {
  oSession.PathAndQuery="/version2.css";
}

3.将请求的某个页面替换为不同站点的页面

if (oSession.url=="www.example.com/live.js") {
  oSession.url = "dev.example.com/workinprogress.js";
}


修改响应:static function OnBeforeResponse(oSession: Session)
1.删除响应头

oSession.oResponse.headers.Remove("Set-Cookie");

2.解压缩和unchunk一个HTTP响应

// Remove any compression or chunking from the response in order to make it easier to manipulate
oSession.utilDecodeResponse();

3.在响应的HTML中搜索关键词(不区分大小写)

if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "text/html") && oSession.utilFindInResponse("searchfor", false)>-1){
  oSession["ui-color"] = "red";
}

4.搜索和替换HTML内容

if (oSession.HostnameIs("www.bayden.com") && oSession.oResponse.headers.ExistsAndContains("Content-Type","text/html")){
  oSession.utilDecodeResponse();
  oSession.utilReplaceInResponse('<b>','<u>');
}

5.移除所有div标签和标签中的内容

// If content-type is HTML, then remove all DIV tags
if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html")){
  // Remove any compression or chunking
  oSession.utilDecodeResponse();
  var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);

  // Replace all instances of the DIV tag with an empty string
  var oRegEx = /<div[^>]*>(.*?)<\/div>/gi;
  oBody = oBody.replace(oRegEx, "");

  // Set the response body to the div-less string
  oSession.utilSetResponseBody(oBody);
}

参考链接

https://www.jianshu.com/p/775f83e45a02

https://docs.telerik.com/fiddler/knowledgebase/fiddlerscript/modifyrequestorresponse

posted @ 2019-07-06 14:41  bamb00  阅读(7278)  评论(1编辑  收藏  举报