Esempio n. 1
0
        public void AutoTamperResponseBefore(Fiddler.Session oSession)
        {
            if (_cfg.Enabled)
            {
                var rspFilePath = _hookSvce.GetResponseFile(oSession);
                if (!string.IsNullOrEmpty(rspFilePath))
                {
                    var info = File.ReadAllText(rspFilePath);
                    oSession.utilSetResponseBody(info);
                }
            }
            //         if (oSession.responseBodyBytes?.Length < 1)
            //             return;
            //if (Config.Instance.Enabled)
            //{
            //	oSession.fullUrl



            //	string fmtedText = null;
            //	try
            //	{

            //	}
            //	catch (Exception ex)
            //	{
            //		FiddlerApplication.Log.LogString($"格式化 {oSession.fullUrl} 时异常 \r\n{ex.ToString()}");
            //	}
            //	finally
            //	{
            //		oSession.utilSetResponseBody(fmtedText);
            //	}
            //}
        }
Esempio n. 2
0
        private void FiddlerApplication_BeforeResponse(Fiddler.Session sess)
        {
            if (sess.RequestMethod == "CONNECT")
            {
                return;
            }

            if (sess.url.Contains("10.26.2.20") == false)
            {
                return;
            }

            if (sess.url.Contains("ico"))
            {
                return;
            }


            sess.utilDecodeResponse();
            var strHtmlUTF8 = System.Text.Encoding.UTF8.GetString(sess.responseBodyBytes);

            if (strHtmlUTF8 != "")
            {
                string newR = strHtmlUTF8.Replace("b", "啦啦啦啦啦大爷的吼吼");
                sess.utilSetResponseBody(newR);
            }
        }
Esempio n. 3
0
        private void FiddlerApplication_BeforeResponse(Session oSession)
        {
            if (!set.CacheEnabled) return;

            if (oSession.PathAndQuery.StartsWith("/kcsapi/api_start2") && Settings.Current.HackEnabled)
            {
                jsonData = oSession.GetResponseBodyAsString();
                ModifyData.Items.ForEach(x => setModifiedData(x));
                oSession.utilSetResponseBody(jsonData);
            }
        }
        public static void BeforeRequest(Session oS)
        {
            var file = oS.url.Replace('/', '_').Split('?').First();
            var method = oS.HTTPMethodIs("GET") ? "GET"
                             : oS.HTTPMethodIs("POST") ? "POST"
                                   : oS.HTTPMethodIs("PUT") ? "PUT" : null;
            oS.utilCreateResponseAndBypassServer();
            var lines = File.ReadAllLines("./Api/Data/" + method + " " + file + ".txt");
            oS.oResponse.headers = Parser.ParseResponse(lines.First());
            oS.oResponse.headers.Add("Content-Type", "application/json");

            oS.utilSetResponseBody(String.Join(Environment.NewLine, lines.Skip(2).ToArray()));
        }
Esempio n. 5
0
        public void AutoTamperResponseBefore(Session oSession)
        {
            if (oSession.uriContains("luoqi/fun/option.php"))
            {
                string xx = oSession.url;
                string[] requestPar = xx.Split(new char[2] {'?','&'});

                foreach (string i in requestPar)
                {
                    if(i.ToString().Contains("guid="))
                    {
                        guid = i.ToString().Substring(i.ToString().IndexOf("=") + 1);
                    }
                }
                oSession.utilSetResponseBody("irv=200|sign=" + this.Sign(oSession, prize.Text, guid) + "|couponw=asdafas" + "|prize=" + prize.Text);
            }
        }
Esempio n. 6
0
        private static void BeforeRequestCallback(Fiddler.Session oS)
        {
            // In order to enable response tampering, buffering mode must
            // be enabled; this allows FiddlerCore to permit modification of
            // the response in the BeforeResponse handler rather than streaming
            // the response to the client as the response comes in.
            oS.bBufferResponse = true;

            if ((oS.hostname == sSecureEndpointHostname) && (oS.port == 7777))
            {
                oS.utilCreateResponseAndBypassServer();
                oS.oResponse.headers.HTTPResponseStatus = "200 Ok";
                oS.oResponse["Content-Type"]            = "text/html; charset=UTF-8";
                oS.oResponse["Cache-Control"]           = "private, max-age=0";
                oS.utilSetResponseBody("<html><body>Request for https://" + sSecureEndpointHostname + ":7777 received. Your request was:<br /><plaintext>" + oS.oRequest.headers.ToString());
            }
        }
Esempio n. 7
0
        /// <summary>
        ///	This is where the hack happens
        /// </summary>
        /// <param name="oS"></param>
        static void OnBeforeRequest(Fiddler.Session oS)
        {
            // Console.WriteLine("Before request for:\t" + oS.fullUrl);
            // In order to enable response tampering, buffering mode MUST
            // be enabled; this allows FiddlerCore to permit modification of
            // the response in the BeforeResponse handler rather than streaming
            // the response to the client as the response comes in.
            oS.bBufferResponse = false;

            if (oS.fullUrl.StartsWith("https://wpflights.trafficmanager.net/RestUpdateProvisioningService.svc/UpdateChoices?"))
            {
                oS.utilCreateResponseAndBypassServer();
                oS.oResponse.headers.SetStatus(200, "Ok");
                oS.oResponse["Content-Type"]  = "application/xml; charset=utf-8";
                oS.oResponse["Cache-Control"] = "private, max-age=0";
                // Read the XML config.
                oS.utilSetResponseBody(File.ReadAllText("WPFlights.xml"));
                FiddlerApplication.Log.LogFormat("Sending custom Flighting Response");
            }
        }
Esempio n. 8
0
        private void FiddlerApplication_BeforeRequest(Session oSession)
        {
            if (!set.CacheEnabled) return;

            if (oSession.PathAndQuery.StartsWith("/kcsapi/api_req_furniture/music_play") && set.HackMusicRequestEnabled)
            {
                oSession.utilCreateResponseAndBypassServer();
                oSession.oResponse.headers.Add("Content-Type", "text/plain");
                oSession.utilSetResponseBody(@"svdata={""api_result"":1,""api_result_msg"":""\u6210\u529f"",""api_data"":{""api_coin"":" + fcoin.ToString() + @"}}");
            }
            else if (oSession.PathAndQuery.StartsWith("/kcsapi/api_get_member/picture_book") && set.HackBookEnabled)
            {
                oSession.utilCreateResponseAndBypassServer();
                oSession.oResponse.headers.Add("Content-Type", "text/plain");

                int type = 1; // 1: 舰娘图鉴, 2: 装备图鉴
                int no = 1;   // 页数
                var param = oSession.GetRequestBodyAsString().Split('&');
                foreach (var p in param)
                {
                    var kv = p.Split('=');
                    if (kv[0] == "api%5Ftype")
                    {
                        type = int.Parse(kv[1]);
                    }
                    else if (kv[0] == "api%5Fno")
                    {
                        no = int.Parse(kv[1]);
                    }
                }

                if (type == 1)
                {
                    oSession.utilSetResponseBody("svdata=" + ShipBookData.Generate(initData, no * 70 - 69, no * 70).ToJsonString());
                }
                else
                {
                    oSession.utilSetResponseBody("svdata=" + EquipmentBookData.Generate(initData, no * 50 - 49, no * 50).ToJsonString());
                }
            }
        }
Esempio n. 9
0
        public void FiddlerApplicationOnBeforeResponse(Session oSession)
        {
            if (oSession.RequestMethod != "GET")
                return;

            var oBody = oSession.GetResponseBodyAsString();
            var responseLower = oBody.ToLower();
            var clientScore = _clientDetectors.Count(clientDetector => responseLower.Contains(clientDetector));

            if (clientScore < (_clientDetectors.Length/2)) return;

            var clientParser = new ClientParser(_manager, oSession.GetResponseBodyAsString());
            if (clientParser.Parse())
            {
                oSession.utilDecodeResponse();

                SetStatus($"Found server details. {clientParser.IpAddress}:{clientParser.Port}", Color.Green);

                if(!_manager.ManualHotel)
                    _manager.StartServer(clientParser.IpAddress, clientParser.Port);
                else
                    _manager.StartServer(IPAddress.Parse(""), 30000);

                oBody = oBody.Replace(clientParser.OFlashVars["connection.info.host"], $"\"{(clientParser.Base64Host ? StringToBase64(_manager.ServerIpAddress.ToString()) : _manager.ServerIpAddress.ToString())}\"");
                oBody = oBody.Replace(clientParser.OFlashVars["connection.info.port"], $"\"{(clientParser.Base64Port ? StringToBase64(_manager.ServerPort.ToString()) : _manager.ServerPort.ToString())}\"");
                oBody = oBody.Replace(clientParser.OFlashVars["client.starting"], "\"RetroImpact has been injected, loading hotel..\"");

                oBody = Regex.Replace(oBody, "<audio id=\"player\" src=\"(.*?)\" autoplay=\"true\"></audio>", ""); // Get rid of a stupid radio #np

                oSession.utilSetResponseBody(oBody);

                _manager.StopIntercept();
            }
            else
                SetStatus(clientParser.ErrorMessage, Color.Red);
        }
Esempio n. 10
0
        private static void BeforeResponseCallback(Fiddler.Session oSession)
        {
            string url = oSession.url.ToLower();

            foreach (ReplaceMapEntry entry in replaceMap)
            {
                if (url.Contains(entry.sourcePath))
                {
                    string replacementFile = string.Empty;
                    if (!entry.sourcePath.EndsWith("/"))
                    {
                        replacementFile = entry.destinationPath;
                    }
                    else
                    {
                        if (url.Contains(".js") ||
                            url.Contains(".css") ||
                            url.Contains(".png") ||
                            url.Contains(".html") ||
                            url.Contains(".htm"))
                        {
                            int startIndex = url.IndexOf(entry.sourcePath);
                            startIndex     += entry.sourcePath.Length;
                            replacementFile = url.Substring(startIndex, (url.Length - startIndex));

                            int queryParam = replacementFile.IndexOf("?");
                            if (queryParam > 0)
                            {
                                replacementFile = replacementFile.Substring(0, queryParam);
                            }

                            replacementFile = replacementFile.Replace("/", "\\");
                            replacementFile = entry.destinationPath + replacementFile;
                        }
                    }

                    if (!string.IsNullOrEmpty(replacementFile))
                    {
                        try
                        {
                            if (oSession.bHasResponse)
                            {
                                if (replacementFile.EndsWith(".png"))
                                {
                                    byte[] buffer = File.ReadAllBytes(replacementFile);
                                    if (buffer != null && buffer.Length > 0)
                                    {
                                        oSession.responseBodyBytes           = buffer;
                                        oSession.oResponse["Content-Length"] = buffer.Length.ToString();
                                        oSession.oResponse["Content-Type"]   = "image/png";

                                        Util.PrintMessage("Replaced " + replacementFile);
                                    }
                                    else
                                    {
                                        throw (new Exception());
                                    }
                                }
                                else //for text files
                                {
                                    string buffer = File.ReadAllText(replacementFile);
                                    if (buffer != null && buffer.Length > 0)
                                    {
                                        oSession.utilDecodeResponse();
                                        oSession.utilSetResponseBody(buffer);
                                        oSession.responseCode = 200;

                                        if (replacementFile.EndsWith(".js"))
                                        {
                                            oSession.oResponse.headers.Add("Content-Type", "application/x-javascript");
                                        }
                                        else if (replacementFile.EndsWith(".css"))
                                        {
                                            oSession.oResponse.headers.Add("Content-Type", "text/css");
                                        }
                                        else if (replacementFile.EndsWith(".html") || replacementFile.EndsWith(".htm"))
                                        {
                                            oSession.oResponse.headers.Add("Content-Type", "text/html");
                                        }

                                        Util.PrintMessage("Replaced " + replacementFile);
                                    }
                                    else
                                    {
                                        throw (new Exception());
                                    }
                                }
                            }
                            else
                            {
                                Util.PrintMessage("Waiting for response");
                            }
                        }
                        catch (Exception ex)
                        {
                            Util.PrintError("Could not replace file " + replacementFile + ". Error: " + ex.Message);
                        }
                    }

                    break;
                }
            }
        }
Esempio n. 11
0
        private void FiddlerApplication_BeforeResponse(Session oSession) {

            if (oSession.PathAndQuery.StartsWith("/kcs/")) {
                string filePath = Utility.Config.Instance.CacheFolder + oSession.getFilePath();

                if (oSession.responseCode == 304) {

                    // code 304, 文件沒有修改, 使用本地文件
                    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) {

                        oSession.bBufferResponse = true;
                        oSession.ResponseBody = File.ReadAllBytes(filePath);
                        oSession.oResponse.headers.HTTPResponseCode = 200;
                        oSession.oResponse.headers.HTTPResponseStatus = "200 OK";
                        oSession.oResponse.headers["Last-Modified"] = oSession.oRequest.headers["If-Modified-Since"];
                        oSession.oResponse.headers["Accept-Ranges"] = "bytes";
                        oSession.oResponse.headers.Remove("If-Modified-Since");
                        oSession.oRequest.headers.Remove("If-Modified-Since");
                        if (filePath.EndsWith(".swf"))
                            oSession.oResponse.headers["Content-Type"] = "application/x-shockwave-flash";

                        Utility.Logger.Add("Response > [304, 返回本地]" + filePath);
                    }
                } else if (oSession.responseCode == 200) {

                    // code 200, 更新緩存紀錄 
                    Cache.UpdataCache(oSession.PathAndQuery);

                    if (File.Exists(filePath)) {
                        string resBody = oSession.GetResponseBodyAsString();
                        string cacheBody = File.ReadAllText(filePath);

                        // 比對緩存 
                        if (resBody.Equals(cacheBody)) {

                            Utility.Logger.Add("Response > [200, 檔案相同]" + filePath);
                        } else {

                            if (Utility.Config.Instance.AutoBackupCache) {
                                // 保存舊緩存 
                                int index = filePath.LastIndexOf('.');
                                if (index > 0) {
                                    string iPath = filePath.Substring(0, index);
                                    string iType = filePath.Substring(index);   // .swf

                                    DateTime dateNow = DateTime.Now;
                                    string dateTime = (dateNow.Year % 100).ToString() + dateNow.Month.ToString("00") + dateNow.Day.ToString("00");
                                    string newFilePath = iPath + "_" + dateTime + iType;

                                    File.Move(filePath, newFilePath);
                                }
                            }
                            
                        try {
                            oSession.SaveResponseBody(filePath);
                        } catch (Exception ex) {
                            DateTime dateNow = DateTime.Now;
                            string dateTime = dateNow.Year.ToString() + dateNow.Month.ToString("00") + dateNow.Day.ToString("00") + "_" +
                                dateNow.Hour.ToString("00") + dateNow.Minute.ToString("00") + dateNow.Second.ToString("00");

                            Utility.Logger.CmdLog("dateTime: ");
                            Utility.Logger.CmdLog(ex.ToString());
                        }

                            Utility.Logger.Add("Response > [200, 更新緩存]" + filePath);
                        }
                        // code 200, 更新時間 
                        GMTHelper._SaveModifiedTime(filePath, oSession.oResponse.headers["Last-Modified"]);

                    } else {
                        // 儲存快取並設置時間 
                        try {
                            oSession.SaveResponseBody(filePath);
                        } catch (Exception ex) {
                            DateTime dateNow = DateTime.Now;
                            string dateTime = dateNow.Year.ToString() + dateNow.Month.ToString("00") + dateNow.Day.ToString("00") + "_" +
                                dateNow.Hour.ToString("00") + dateNow.Minute.ToString("00") + dateNow.Second.ToString("00");

                            Utility.Logger.CmdLog("dateTime: ");
                            Utility.Logger.CmdLog(ex.ToString());
                        }
                        GMTHelper._SaveModifiedTime(filePath, oSession.oResponse.headers["Last-Modified"]);
                        Utility.Logger.Add("Response > [200, 建立緩存]" + filePath);
                    }
                }

                // 魔改 
                if (filePath.Contains(@"kcs\resources\swf\ships\")) {

                    string fileName = filePath.getFileName();
                    if (CosManager.Instance.IsPaired(fileName)) {
                        Utility.Logger.Add("IsPaired > " + fileName);
                        //filePath = filePath.Replace(fileName, CosManager.Instance.GetPair(fileName));
                        filePath = Utility.Config.Instance.CostumeFolder + @"\" + CosManager.Instance.GetPair(fileName) + ".swf";
                        oSession.ResponseBody = File.ReadAllBytes(filePath);
                    }
                }


            } else if (oSession.PathAndQuery.StartsWith("/kcsapi/")) {

                string url = oSession.PathAndQuery;
                string body = oSession.GetResponseBodyAsString();

                Utility.Logger.Add("Response > " + url);

                try {
                    // 非同期で書き出し処理するので取っておく
                    // stringはイミュータブルなのでOK
                    Task.Run((Action)(() => { SaveResponse(url, body); }));
                } catch (Exception ex) {
                    Utility.ErrorReporter.SendErrorReport(ex, "通信内容保存失败。");
                }

                // api修改 
                if (oSession.bBufferResponse) {
                    Utility.Logger.Add("Response > LoadDynamicJson( " + url + " )");
                    string newbody = LoadDynamicJson(url, body);
                    if (newbody != null) {
                            oSession.utilSetResponseBody(newbody);
                    }
                }

            }
        }
Esempio n. 12
0
        private static void OnResponse(Session s)
        {
            s.bBufferResponse = true;
            int responseStatusCode = s.responseCode;
            string responseContentType = s.ResponseHeaders["Content-Type"].Trim().ToLower();
            string url = s.fullUrl;

            if (responseStatusCode == 200)
            {
                // Most APIs are returned in text/plain but serach songs page is returned in JSON. Don't forget this!
                if (responseContentType.Contains("text/plain") || responseContentType.Contains("application/json"))
                {
                    if (Configuration.Verbose)
                    {
                        Console.WriteLine($"Accessing URL {url}");
                    }
                    // It should include album / playlist / artist / search pages.
                    if (url.Contains("/eapi/v3/song/detail/") || url.Contains("/eapi/v1/album/") || url.Contains("/eapi/v3/playlist/detail") ||
                        url.Contains("/eapi/batch") || url.Contains("/eapi/cloudsearch/pc") || url.Contains("/eapi/v1/artist") ||
                        url.Contains("/eapi/v1/search/get"))
                    {
                        string modified = ModifyDetailApi(s.GetResponseBodyAsString());
                        s.utilSetResponseBody(modified);
                    }
                    // This is called when player tries to get the URL for a song.
                    else if (url.Contains("/eapi/song/enhance/player/url"))
                    {
                        string bitrate = GetPlaybackBitrate(s.GetResponseBodyAsString());
                        // Whatever current playback bitrate is, it's overriden.
                        if (!string.IsNullOrEmpty(Configuration.ForcePlaybackBitrate))
                        {
                            bitrate = Configuration.ForcePlaybackBitrate;
                            Console.WriteLine($"Plackback bitrate is forced set to {bitrate}");
                        }
                        // We receive a wrong bitrate...
                        else if (bitrate == "0")
                        {
                            bitrate = string.IsNullOrEmpty(Configuration.ForcePlaybackBitrate) ? "320000" : Configuration.ForcePlaybackBitrate;
                            Console.WriteLine($"Plackback bitrate is forced set to {bitrate} as the given bitrate is not valid.");
                        }
                        else if (bitrate != Configuration.PlaybackBitrate)
                        {
                            Console.WriteLine($"Plackback bitrate is switched to {bitrate} from {Configuration.PlaybackBitrate}");
                        }
                        Configuration.PlaybackBitrate = bitrate;
                        Configuration.PlaybackQuality = ParseBitrate(Configuration.ForcePlaybackBitrate);

                        string modified = ModifyPlayerApi(s.GetResponseBodyAsString());
                        s.utilSetResponseBody(modified);
                    }
                    // When we try to download a song, the API tells whether it exceeds the limit. Of course no!
                    else if (url.Contains("/eapi/song/download/limit"))
                    {
                        string modified = ModifyDownloadLimitApi();
                        s.utilSetResponseBody(modified);
                    }
                    // Similar to the player URL API, but used for download.
                    else if (url.Contains("/eapi/song/enhance/download/url"))
                    {
                        string bitrate = GetDownloadBitrate(s.GetResponseBodyAsString());

                        // Whatever current download bitrate is, it's overriden.
                        if (!string.IsNullOrEmpty(Configuration.ForceDownloadBitrate))
                        {
                            bitrate = Configuration.ForceDownloadBitrate;
                            Console.WriteLine($"Download bitrate is forced set to {bitrate}");
                        }
                        // We receive a wrong bitrate...
                        else if (bitrate == "0")
                        {
                            bitrate = string.IsNullOrEmpty(Configuration.ForceDownloadBitrate) ? "320000" : Configuration.ForceDownloadBitrate;
                            Console.WriteLine($"Download bitrate is forced set to {bitrate} as the given bitrate is not valid.");
                        }
                        else if (bitrate != Configuration.DownloadBitrate)
                        {
                            Console.WriteLine($"Download bitrate is switched to {bitrate} from {Configuration.DownloadBitrate}");
                        }
                        Configuration.DownloadBitrate = bitrate;
                        Configuration.DownloadQuality = ParseBitrate(bitrate);

                        string modified = ModifyDownloadApi(s.GetResponseBodyAsString());
                        s.utilSetResponseBody(modified);
                    }
                }
            }
        }
        static void FiddlerApplication_BeforeResponse(Session rpSession)
        {
            var rSession = rpSession.Tag as NetworkSession;
            if (rSession != null)
            {
                if (rSession.State == NetworkSessionState.Requested)
                    rSession.State = NetworkSessionState.Responsed;

                var rApiSession = rSession as ApiSession;
                if (rApiSession != null)
                {
                    rApiSession.ResponseBodyString = rpSession.GetResponseBodyAsString();
                    ApiParserManager.Instance.Process(rApiSession);
                }

                var rResourceSession = rSession as ResourceSession;
                if (rResourceSession != null)
                    CacheService.Instance.ProcessResponse(rResourceSession, rpSession);

                if (rpSession.PathAndQuery == "/gadget/js/kcs_flash.js")
                {
                    var rScript = rpSession.GetResponseBodyAsString();
                    var rModified = false;

                    var rQuality = Preference.Current.Browser.Flash.Quality;
                    if (rQuality != FlashQuality.Default)
                    {
                        rScript = r_FlashQualityRegex.Replace(rScript, $"$1{rQuality}$2");
                        rModified = true;
                    }

                    var rRenderMode = Preference.Current.Browser.Flash.RenderMode;
                    if (rRenderMode != FlashRenderMode.Default)
                    {
                        rScript = r_FlashRenderModeRegex.Replace(rScript, $"$1{rRenderMode}$2");
                        rModified = true;
                    }

                    if (rModified)
                        rpSession.utilSetResponseBody(rScript);
                }

                if (rSession.FullUrl == GameConstants.GamePageUrl)
                {
                    ForceOverrideStylesheet(rpSession);

                    var rSource = rpSession.GetResponseBodyAsString();
                    rSource = r_SuppressReloadConfirmation.Replace(rSource, "false");

                    rpSession.utilSetResponseBody(rSource);
                }

                if (rpSession.oResponse.headers.Any(rHeader => rHeader.Name == "Content-Range"))
                    System.Diagnostics.Debugger.Break();
            }
        }
Esempio n. 14
0
        private static void OnResponse(Session s)
        {
            string responseContentType = s.ResponseHeaders["Content-Type"].Trim().ToLower();
            string path = s.PathAndQuery;

            // API part
            // Most APIs are returned in text/plain but searching songs page is returned in JSON. Don't forget this!
            if (s.responseCode == 200 && (responseContentType.Contains("text/plain") || responseContentType.Contains("application/json")))
            {
                LogEntry($"Accessing URL {s.fullUrl}");

                // It should include album / playlist / artist / search pages.
                if (path.StartsWith("/eapi/v3/song/detail/") || path.StartsWith("/eapi/v1/album/") ||
                    path.StartsWith("/eapi/v3/playlist/detail") ||
                    path.StartsWith("/eapi/batch") || path.StartsWith("/eapi/cloudsearch/pc") ||
                    path.StartsWith("/eapi/v1/artist") ||
                    path.StartsWith("/eapi/v1/search/get") || path.StartsWith("/eapi/song/enhance/privilege") ||
                    path.StartsWith("/eapi/v1/discovery/new/songs") || path.StartsWith("/eapi/v1/play/record"))
                {
                    string modified = ModifyDetailApi(s.GetResponseBodyAsString());
                    s.utilSetResponseBody(modified);
                }
                // This is called when player tries to get the URL for a song.
                else if (path.StartsWith("/eapi/song/enhance/player/url"))
                {
                    // If the song URL is returned properly, or the returned quality is higher than the forced quality, we do not override the song URL.
                    // This is designed as premium users may require lossless audio file.
                    if (GetPlayResponseCode(s.GetResponseBodyAsString()) != "200" ||
                        (Config.ForcePlaybackQuality &&
                         int.Parse(GetPlaybackBitrateFromApi(s.GetResponseBodyAsString())) <
                         int.Parse(ConvertQuality(Config.PlaybackQuality, "Bitrate"))))
                    {
                        string bitrate = GetPlaybackBitrateFromApi(s.GetResponseBodyAsString());
                        // Whatever current playback bitrate is, it's overriden.
                        if (Config.ForcePlaybackQuality)
                        {
                            bitrate = ConvertQuality(Config.PlaybackQuality, "Bitrate");
                            LogEntry($"Playback bitrate is forced set to {bitrate}");
                        }
                        // We receive a wrong bitrate...
                        else if (bitrate == "0")
                        {
                            bitrate = Config.ForcePlaybackQuality
                                ? ConvertQuality(Config.PlaybackQuality, "Bitrate")
                                : "320000";
                            LogEntry(
                                $"Playback bitrate is restored to {bitrate} as the given bitrate is not valid.");
                        }
                        // If we received an unexpected bitrate...
                        else if (bitrate != ConvertQuality(Config.PlaybackQuality, "Bitrate"))
                        {
                            LogEntry(
                                $"Playback bitrate is switched to {bitrate} from {ConvertQuality(Config.PlaybackQuality, "Bitrate")}");
                        }
                        Config.PlaybackQuality = ConvertQuality(bitrate, "Full");
                        string modified = ModifyPlayerApi(s.GetResponseBodyAsString());
                        s.utilSetResponseBody(modified);
                    }
                    else
                    {
                        LogEntry(
                            $"Playback bitrate is not changed. The song URL is {GetPlayResponseUrl(s.GetResponseBodyAsString())}");
                    }
                }

                // When we try to download a song, the API tells whether it exceeds the limit. Of course no!
                else if (path.StartsWith("/eapi/song/download/limit"))
                {
                    string modified = ModifyDownloadLimitApi();
                    s.utilSetResponseBody(modified);
                }

                // Similar to the player URL API, but used for download.
                else if (path.StartsWith("/eapi/song/enhance/download/url"))
                {
                    // If the song URL is returned properly, or the returned quality is higher than the forced quality, we do not override the song URL.
                    // This is designed as premium users may require lossless audio file.
                    if (GetDownloadResponseCode(s.GetResponseBodyAsString()) != "200" ||
                        (Config.ForceDownloadQuality &&
                         int.Parse(GetDownloadBitrate(s.GetResponseBodyAsString())) <
                         int.Parse(ConvertQuality(Config.DownloadQuality, "Bitrate"))))
                    {
                        string bitrate = GetDownloadBitrate(s.GetResponseBodyAsString());

                        // Whatever current download bitrate is, it's overriden.
                        if (Config.ForceDownloadQuality)
                        {
                            bitrate = ConvertQuality(Config.DownloadQuality, "Bitrate");
                            LogEntry($"Download bitrate is forced set to {bitrate}");
                        }
                        // We receive a wrong bitrate...
                        else if (bitrate == "0")
                        {
                            bitrate = Config.ForceDownloadQuality
                                ? ConvertQuality(Config.DownloadQuality, "Bitrate")
                                : "320000";
                            LogEntry(
                                $"Download bitrate is forced set to {bitrate} as the given bitrate is not valid.");
                        }
                        else if (bitrate != ConvertQuality(Config.DownloadQuality, "Bitrate"))
                        {
                            LogEntry(
                                $"Download bitrate is switched to {bitrate} from {ConvertQuality(Config.DownloadQuality, "Bitrate")}");
                        }
                        Config.DownloadQuality = ConvertQuality(bitrate, "Full");

                        string modified = ModifyDownloadApi(s.GetResponseBodyAsString());
                        s.utilSetResponseBody(modified);
                    }
                    else
                    {
                        LogEntry(
                            $"Download bitrate is not changed. The song URL is {GetDownloadResponseUrl(s.GetResponseBodyAsString())}");
                    }
                }
            }
            else
            {
                if (s.responseCode >= 400 && path.Contains(".mp3"))
                {
                    if (Config.ForceIp)
                    {
                        int? ipIndex = null;
                        try
                        {
                            ipIndex = Config.IpAddressList.IndexOf(Config.IpAddress) + 1;
                            if (ipIndex == Config.IpAddressList.Count)
                            {
                                ipIndex = 0;
                            }
                        }
                        catch
                        {
                            if (Config.IpAddressList.Count > 0) ipIndex = 0;
                        }

                        if (ipIndex != null)
                        {
                            Config.IpAddress = Config.IpAddressList[ipIndex.Value];
                        }

                        LogEntry($"Cannot load song, try next IP: {Config.IpAddress}");
                    }
                    else
                    {
                        LogEntry($"This song {s.fullUrl} is not available on the server.");
                    }
                }
            }
        }
        /// <summary>
        /// CreateTableError creates an error response from a table API.
        /// </summary>
        /// <param name="session">The session with which to tamper.</param>
        /// <param name="statusCode">The error code to return</param>
        /// <param name="messageCode">The string name for the error</param>
        /// <param name="message">The long error message to be returned.</param>
        private static void CreateTableError(Session session, int statusCode, string messageCode, string message)
        {
            session.utilCreateResponseAndBypassServer();
            session.oResponse.headers = CreateResponseHeaders(null);
            session.responseCode = statusCode;

            session.utilSetResponseBody(
                TableConstants.GetError(
                    messageCode,
                    string.Format(
                        "{0}\r\nRequestId:{1}\r\nTime:{2}",
                        message,
                        Guid.Empty.ToString(),
                        DateTime.UtcNow.ToString("o"))).ToString());
        }
        private static void EchoEntry(Session session)
        {
            Uri hostName = new Uri(string.Format("http://{0}/", session.oRequest["Host"]));
            Uri tableUrl = new Uri(session.fullUrl);
            string requestString = session.GetRequestBodyAsString();

            string timestamp = DateTime.UtcNow.ToString("o");
            string etag = string.Format("W/\"datetime'{0}'\"", Uri.EscapeDataString(timestamp));

            XElement request = XElement.Parse(requestString);

            request.SetAttributeValue(XNamespace.Xml + "base", hostName.AbsoluteUri);
            request.SetAttributeValue(TableConstants.Metadata + "etag", Uri.EscapeDataString(etag));

            string partitionKey = request.Descendants(TableConstants.OData + "PartitionKey").Single().Value;
            string rowKey = request.Descendants(TableConstants.OData + "RowKey").Single().Value;

            Uri entryUri = new Uri(string.Format(
                "{0}(PartitionKey='{1}',RowKey='{2}')",
                tableUrl.AbsoluteUri,
                Uri.EscapeUriString(partitionKey),
                Uri.EscapeUriString(rowKey)));

            XElement timestampElement = request.Descendants(TableConstants.OData + "Timestamp").Single();
            timestampElement.Value = timestamp;

            XElement updatedElement = request.Descendants(TableConstants.Atom + "updated").Single();
            updatedElement.Value = timestamp;

            XElement idElement = request.Descendants(TableConstants.Atom + "id").Single();
            idElement.Value = entryUri.AbsoluteUri;

            // Add link
            XElement linkElement = new XElement(
                TableConstants.Atom + "link",
                new XAttribute("rel", "edit"),
                new XAttribute("href", entryUri.PathAndQuery.Substring(1)));
            idElement.AddAfterSelf(linkElement);

            // Add category
            string accountName = hostName.Host.Substring(0, hostName.Host.IndexOf('.'));
            string categoryName = accountName + "." + tableUrl.PathAndQuery.Substring(1);
            idElement.AddAfterSelf(TableConstants.GetCategory(categoryName));

            // mark that we're going to tamper with it
            session.utilCreateResponseAndBypassServer();

            session.oResponse.headers = CreateResponseHeaders(entryUri.AbsoluteUri);
            session.oResponse.headers["ETag"] = etag;

            session.responseCode = 201;

            string responseString = request.ToString();
            session.utilSetResponseBody(responseString);
        }
Esempio n. 17
0
        // api 모드 실행
        void runApiMode(Session oSession)
        {
            PLinkApiType data = router(oSession.PathAndQuery);

            if (data == null) {
                oSession.oRequest.pipeClient.End();
            } else {
                SetDiabledCache(oSession);
                // 새로운 응답 만들기
                oSession.utilCreateResponseAndBypassServer();
                oSession.oResponse.headers.HTTPResponseCode = 200;
                oSession.oResponse.headers.HTTPResponseStatus = "200 OK";
                oSession.oResponse.headers["Content-Type"] = data.ContentType;
                SetDiabledCacheAfter(oSession);
                oSession.utilSetResponseBody(data.Body);
            }
        }
        /// <summary>
        /// GetTableWithCode tampers with with the request to return the specific table and a success code.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="statusCode"></param>
        private static void GetTableWithCode(Session session, int statusCode)
        {
            // Find relevant facts about this table creation.
            Uri hostName = new Uri(string.Format("http://{0}/", session.oRequest["Host"]));
            string requestString = session.GetRequestBodyAsString();

            string tableName = null;
            string tableUri = null;
            if (string.IsNullOrEmpty(requestString))
            {
                tableName = tableNameRegex.Match(session.url).Groups[1].Value;
            }
            else
            {
                XElement request = XElement.Parse(requestString);
                tableName = request.Descendants(TableConstants.OData + "TableName").Single().Value;
                tableUri = new Uri(hostName, string.Format("/Tables('{0}')", tableName)).AbsoluteUri;
            }

            // mark that we're going to tamper with it
            session.utilCreateResponseAndBypassServer();

            session.oResponse.headers = CreateResponseHeaders(tableUri);
            session.responseCode = statusCode;

            // Create the response XML
            XElement response = TableConstants.GetEntry(hostName.AbsoluteUri);

            response.Add(new XElement(TableConstants.Atom + "id", session.fullUrl));
            response.Add(new XElement(TableConstants.Title));
            response.Add(new XElement(TableConstants.Atom + "updated", DateTime.UtcNow.ToString("o")));
            response.Add(TableConstants.Author);

            response.Add(TableConstants.GetLink(tableName));

            string accountName = hostName.Host.Substring(0, hostName.Host.IndexOf('.'));
            response.Add(TableConstants.GetCategory(accountName + ".Tables"));

            // Add in the most important part -- the table name.
            response.Add(new XElement(
                TableConstants.Atom + "content",
                new XAttribute("type", "application/xml"),
                new XElement(
                    TableConstants.Metadata + "properties",
                    new XElement(
                        TableConstants.OData + "TableName",
                        tableName))));

            string responseString = response.ToString();
            session.utilSetResponseBody(responseString);
        }
Esempio n. 19
0
 /// <summary>
 /// Gets triggered before the response gets rendered
 /// </summary>
 /// <param name="objSession"></param>
 private void FiddlerApplication_BeforeResponse(Session objSession)
 {
     //Check whether its an inaccessible URL
     if (!_IsAllowedURL)
     {
         String strRequestBody = objSession.GetResponseBodyAsString();
         objSession.utilSetResponseBody("<html><body><h1 style='color:red;'>You are not allowed to view this site.</h1></body></html>");
     }
 }
Esempio n. 20
0
    public void AutoTamperResponseAfter(Session oSession)
    {
        if (!bBlockerEnabled) return;

        if (miFlashAlwaysBlock.Checked && oSession.oResponse.headers.ExistsAndContains("Content-Type", "application/x-shockwave-flash"))
        {
            oSession.responseCode=404;
            oSession.utilSetResponseBody("Fiddler.ContentBlocked");
        }

        if (miAutoTrim.Checked && 0 == (oSession.id % 10))
        {
            FiddlerApplication.UI.TrimSessionList(400);
        }
    }
Esempio n. 21
0
        public void AutoTamperRequestBefore(Session oSession)
        {
            if (!IsEnabled)
            {
                return;
            }

            string fullString = oSession.fullUrl.ToLower();

            if (fullString.EndsWith("imposter.js") && EnableAutoReload)
            {
                oSession.utilCreateResponseAndBypassServer();
                var js = Path.GetFullPath("Scripts\\imposter.js");
                oSession.LoadResponseFromFile(js);
                oSession.ResponseHeaders.Add("x-imposter", js);
            }

            if (fullString.ToLower().Contains("/imposter-poll-for-changes?profileid=") && EnableAutoReload)
            {
                var profileIdIndex = fullString.ToLower().IndexOf("/imposter-poll-for-changes?profileid=");
                var profileIdFragment = fullString.Substring(profileIdIndex + "/imposter-poll-for-changes?profileid=".Length);

                Guid profileId;
                var success = Guid.TryParse(profileIdFragment, out profileId);

                oSession.utilCreateResponseAndBypassServer();
                oSession.ResponseHeaders.Add("x-imposter", "AUTO RELOAD");

                if (success && _enabledProfiles.Any(p => p.ProfileId == profileId && p.HasChanges))
                {
                    oSession.utilSetResponseBody("true");
                    _enabledProfiles.ForEach(p => p.HasChanges = false);
                }
                else
                {
                    oSession.utilSetResponseBody("false");
                }
            }

            foreach (var profile in _enabledProfiles)
            {
                var path = profile.GetFileMatch(fullString);

                if (path == null)
                {
                    continue;
                }

                oSession.utilCreateResponseAndBypassServer();
                oSession.LoadResponseFromFile(path);
                oSession.ResponseHeaders.Add("x-imposter", path);
                if (oSession.ViewItem != null)
                {
                    oSession.ViewItem.BackColor = Color.SkyBlue;
                }
                // Only swap for the first match
                break;
            }
        }
Esempio n. 22
0
 private static void _returnRootCert(Session oS)
 {
     oS.utilCreateResponseAndBypassServer();
     oS.oResponse.headers["Connection"] = "close";
     oS.oResponse.headers["Cache-Control"] = "max-age=0";
     byte[] buffer = CertMaker.getRootCertBytes();
     if (buffer != null)
     {
         oS.oResponse.headers["Content-Type"] = "application/x-x509-ca-cert";
         oS.responseBodyBytes = buffer;
         oS.oResponse.headers["Content-Length"] = oS.responseBodyBytes.Length.ToString();
     }
     else
     {
         oS.responseCode = 0x194;
         oS.oResponse.headers["Content-Type"] = "text/html; charset=UTF-8";
         oS.utilSetResponseBody("No root certificate was found. Have you enabled HTTPS traffic decryption in Fiddler yet?".PadRight(0x200, ' '));
     }
     FiddlerApplication.DoResponseHeadersAvailable(oS);
     oS.ReturnResponse(false);
 }
Esempio n. 23
0
        private void PlaybackSession(Session oS, SessionInfo info)
        {
            try
            {
                string tapeId = info.UserId + "." + info.TapeId;
                Tape tape = _store.Select(tapeId);
                if (tape == null)
                {
                    oS.utilCreateResponseAndBypassServer();
                    oS.responseCode = 404;
                    oS.utilSetResponseBody("Tape not found");
                    return;
                }

                // time to find matching session
                Entry entry = HttpArchiveTranscoder.Export(oS, true);

                Entry matchedEntry = _store.MatchEntry(tapeId, entry);

                if (matchedEntry == null)
                {
                    oS.utilCreateResponseAndBypassServer();
                    oS.responseCode = 404;
                    oS.utilSetResponseBody("Matching entry not found");
                }
                else
                {
                    Session matchedSession = HttpArchiveTranscoder.Import(matchedEntry);
                    oS.utilCreateResponseAndBypassServer();
                    // #TODO: figger me out
                    // odd, fiddler is compressing respose when it is not compressed from server
                    //oS.responseBodyBytes = matchedSession.responseBodyBytes;

                    oS.utilSetResponseBody(matchedEntry.response.content.text);
                    oS.oResponse.headers = (HTTPResponseHeaders)matchedSession.oResponse.headers.Clone();

                    // #TODO: figger me out
                    oS.oResponse.headers["Content-Length"] = matchedEntry.response.content.text.Length.ToString();
                    // #TODO: figger me out
                    oS.oResponse.headers.Remove("Content-Encoding");
                }
            }
            catch
            {
                oS.utilCreateResponseAndBypassServer();
                oS.responseCode = 500;
                oS.utilSetResponseBody("Exception occurred");

                throw;
            }
        }
Esempio n. 24
0
 private void RecordSession(Session oS, SessionInfo info)
 {
     try
     {
         if (_secured)
         {
             Tape tape = _store.Select(info.UserId + "." + info.TapeId);
             if (tape == null)
             {
                 oS.utilCreateResponseAndBypassServer();
                 oS.responseCode = 404;
                 oS.utilSetResponseBody("Tape not found");
                 return;
             }
             if (!tape.OpenForRecording)
             {
                 oS.utilCreateResponseAndBypassServer();
                 oS.responseCode = 412;
                 oS.utilSetResponseBody("Tape is not open for recording");
                 return;
             }
             string ip = GetClientIp(oS);
             if (ip != tape.AllowedIpAddress)
             {
                 oS.utilCreateResponseAndBypassServer();
                 oS.responseCode = 403;
                 oS.utilSetResponseBody("IP " + GetClientIp(oS) + " not allowed to record.");
                 return;
             }
         }
         oS.bBufferResponse = true;
         RecordCache.TryAdd(oS, info);
     }
     catch
     {
         oS.utilCreateResponseAndBypassServer();
         oS.responseCode = 500;
         oS.utilSetResponseBody("Exception occurred");
     }
 }
Esempio n. 25
0
        private void ProcessBeginRequest(Session oS)
        {
            var info = new SessionInfo(oS);

            oS.host = info.Host;
            oS.PathAndQuery = info.PathAndQuery;

            switch (info.Type)
            {
                case SessionType.Record:
                    RecordSession(oS, info);
                    break;

                case SessionType.Playback:
                    PlaybackSession(oS, info);
                    break;
                case SessionType.InvalidMimeType:
                    oS.utilCreateResponseAndBypassServer();
                    oS.responseCode = 500;
                    oS.utilSetResponseBody("Invalid MIME type");

                    break;
                case SessionType.Export:
                    oS.utilCreateResponseAndBypassServer();
                    oS.responseCode = 200;
                    // #TODO: set content-type etc
                    Tape tape = _store.Select(info.UserId + "." + info.TapeId);
                    if (tape == null)
                    {
                        oS.utilCreateResponseAndBypassServer();
                        oS.responseCode = 404;
                        oS.utilSetResponseBody("Tape not found");
                        return;
                    }
                    oS.oResponse.headers["Content-Type"] = "text/json";
                    oS.utilSetResponseBody(JsonConvert.SerializeObject(tape, Formatting.Indented));

                    break;

            }
        }