1. 程式人生 > >Fiddler如何自動修改請求和響應包

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/modifyrequestorresp