Example #1
0
        public void FilterAndInject(Session oSession)
        {
            Debug.Log("FilterAndInject: MatchRule check!" + oSession.fullUrl);
            // response content type is text/html
            if (bGlobalEnabled && oSession.oResponse.headers.ExistsAndContains("Content-Type", "text/html"))
            {
                Debug.Log("FilterAndInject: MatchRule check!");
                // request url is match the user's config rules
                if(this.MatchRule(oSession))
                {
                    oSession.utilDecodeResponse();
                    oSession.utilReplaceOnceInResponse(@"<head>", @"<head><script>" + sScriptText + "</script>", false);

                    // script tag add crossorigin 
                    oSession.utilReplaceInResponse(@"<script", @"<script crossorigin ");

                    oSession.oResponse.headers["Cache-Control"] = "no-cache";
                    oSession.oResponse.headers["Content-Length"] = oSession.responseBodyBytes.Length.ToString();
                }
            }

           // javascript request, add cross domain header
           if (oSession.fullUrl.Contains(".js"))
           {
               if (oSession.oResponse.headers["Access-Control-Allow-Origin"] == "")
               {
                   oSession.oResponse.headers["Access-Control-Allow-Origin"] = "*";
               }
           }
        }
Example #2
0
        private void GetAnswersFromResponse(Session session)
        {
            session.utilDecodeResponse();

            var responseString = System.Text.Encoding.UTF8.GetString(session.ResponseBody);

            try
            {
                var cheatInfo = JsonConvert.DeserializeObject<CheatInfo>(responseString);
                if (cheatInfo.session_elements.Count == 0) return;

                _userControl.AppendText(string.Empty);
                _userControl.ResetCount();

                foreach (var element in cheatInfo.session_elements)
                {
                    if (element.form_tokens.Count(t => t.options.Count > 0) > 0) _userControl.AppendText(element.form_tokens.First(f => f.options.Count > 0).options.First(o => o.correct).display_value);
                    else if (element.options.Count > 0) _userControl.AppendText(string.Join(" / ", element.options.Where(o => o.correct).Select(o => o.sentence)));
                    else if (!string.IsNullOrEmpty(element.translation)) _userControl.AppendText(element.translation);
                    else if (!string.IsNullOrEmpty(element.text)) _userControl.AppendText(element.text);
                    else if (element.correct_solutions.Count > 0) _userControl.AppendText(element.correct_solutions[0]);
                    else _userControl.AppendText(string.Empty);
                }
            }
            finally
            {
            }
        }
Example #3
0
        private void GetHintsFromResponse(Session session)
        {
            session.utilDecodeResponse();

            var responseString = System.Text.Encoding.UTF8.GetString(session.ResponseBody);
            var regexStart = new Regex(@"^/\*\*/jQuery[0-9]{20}_[0-9]{10,15}\(");
            responseString = regexStart.Replace(responseString, string.Empty);
            var regexEnd = new Regex(@"\);$");
            responseString = regexEnd.Replace(responseString, string.Empty);

            try
            {
                var hintInfo = JsonConvert.DeserializeObject<DuoHint>(responseString);
                var hintString = string.Empty;
                foreach(var token in hintInfo.tokens.Where(t => t.hint_table != null).OrderBy(t => t.index))
                {
                    foreach(var row in token.hint_table.rows.Where(r => r.cells.Count > 0))
                    {
                        hintString += string.Join(", ", row.cells.Where(c => !string.IsNullOrEmpty(c.hint)).Select(c => c.hint.Trim()));
                        hintString += ", ";
                    }
                }

                _userControl.AppendText("\r\n" + hintString);
            }
            finally { }
        }
Example #4
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);
            }
        }
Example #5
0
 public static Session ToNekoxySession(this Fiddler.Session session)
 {
     session.utilDecodeResponse();
     return(new Session
     {
         Request = new HttpRequest(session.GenerateRequestLine(), session.RequestHeaders.GenerateHeaders(), session.RequestBody),
         Response = new HttpResponse(session.GenerateStatusLine(), session.ResponseHeaders.GenerateHeaders(), session.ResponseBody)
     });
 }
Example #6
0
 private void FiddlerApplication_BeforeResponse(Fiddler.Session oS)
 {
     if (oS.oFlags.ContainsKey("dax_id"))
     {
         oS.utilDecodeResponse();
         oS.SaveResponseBody(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "DaXCaps", oS.oFlags["dax_id"] + "_DaX_" + oS.RequestHeaders["Range"].Substring("bytes=".Length) + "_XaD_" + oS.SuggestedFilename));
         oS.ResponseBody = null;
         GC.Collect();
     }
 }
Example #7
0
        static void BeforeResponse(Fiddler.Session session)
        {
            if (session.url.Contains("gateway.vocabgo.com"))
            {
                if (session.url.Contains("StartAnswer") || session.url.Contains("SubmitAnswerAndSave") || session.url.Contains("SkipAnswer") || session.url.Contains("SubmitAnswerAndReturn"))
                {
                    if (!session.utilDecodeResponse())
                    {
                        Console.WriteLine("Could not decode response! URL: " + session.url);
                        return;
                    }

                    Console.WriteLine("");
                    Console.WriteLine("===================================================================");
                    Console.WriteLine("===================================================================");

                    dynamic json = JsonConvert.DeserializeObject(System.Text.Encoding.UTF8.GetString(session.responseBodyBytes));

                    if (json.code.Value != 1)
                    {
                        Console.WriteLine("返回代码: " + json.code.Value);
                        Console.WriteLine("返回信息: " + json.msg.Value);
                        return;
                    }

                    if (use_api)
                    {
                        var client = new RestClient("http://cidaren.mcol.cc/q.php");
                        client.Timeout = -1;
                        var request = new RestRequest(Method.POST);
                        request.AddHeader("Content-Type", "application/json");
                        request.AddParameter(
                            "application/json",
                            "{\"code\": true,\"content\": \"" + json.data.stem.content + "\",\"remark\": \"" + json.data.stem.remark + "\",\"mode\": " + json.data.topic_mode + "}",
                            ParameterType.RequestBody
                            );
                        var     response = client.Execute(request).Content;
                        dynamic answer   = JsonConvert.DeserializeObject(response);
                        if (answer.Property("answer") != null && answer.answer.Count > 0)
                        {
                            Console.WriteLine("已在题库中找到该题目答案!");
                            Console.WriteLine("题目:");
                            Console.WriteLine("    " + answer.content);
                            Console.WriteLine("答案:");
                            Console.WriteLine("    " + answer.answer[0][0]);
                            return;
                        }

                        Console.WriteLine("题目中没有该题目答案, 转为辅助模式");
                    }

                    SwitchQuestionType(json);
                }
            }
        }
 private static void FiddlerApplication_BeforeResponse(Session oSession)
 {
     if (modifierOn && oSession.fullUrl.IndexOf("/kcs/resources/swf/ships/") >= 0)
     {
         var tmp1 = oSession.fullUrl.Split('/');
         var tmp2 = tmp1.Last().Split('.');
         if (tmp2.Length >= 1)
         {
             if (data.ContainsKey(tmp2[0]))
             {
                 oSession.utilDecodeResponse();
                 oSession.ResponseBody = File.ReadAllBytes(data[tmp2[0]]);
                 oSession.oResponse.headers.HTTPResponseCode = 200;
                 oSession.oResponse.headers.HTTPResponseStatus = "200 OK";
             }
         }
     }
 }
Example #9
0
        private static void TranslateSession(Fiddler.Session sess)
        {
            var handler = AfterSessionComplete;

            if (handler == null)
            {
                return;
            }

            if (sess.RequestMethod == "CONNECT")
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(sess.RequestMethod))
            {
                return;
            }

            sess.utilDecodeRequest();
            sess.utilDecodeResponse();

            handler(new Session(sess));
        }
Example #10
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);
        }
        static void ForceOverrideStylesheet(Session rpSession)
        {
            rpSession.utilDecodeResponse();
            rpSession.utilReplaceInResponse("</head>", @"<style type=""text/css"">
html { touch-action: none }

body {
    margin: 0;
    overflow: hidden;
}

#ntg-recommend, #dmm-ntgnavi-renew { display: none !important; }

#game_frame {
    position: fixed;
    left: 50%;
    top: -16px;
    margin-left: -450px;
    z-index: 255;
}
</style></head>");
        }
    public void AutoTamperResponseBefore(Session oSession)
    {
        if (/*oSession.oResponse.headers.ExistsAndContains("Content-Type", "application/x-shockwave-flash")*/true) {
            String path = oSession.host + oSession.PathAndQuery;

            //path = path.Substring(0, path.IndexOf('?'));
            path = path
                .Replace("/", "\\")
                .Replace("?", "-\\")
                .Replace("&", "\\")
                .Replace(":" , "%3A")
                .Replace("*" , "%2A")
                .Replace("\"", "%22")
                .Replace("<" , "%3C")
                .Replace(">" , "%3E")
                .Replace("|" , "%7C");
            path = "C:\\Temp\\FiddlerCapture\\" + path;

            while (path.Contains("\\\\"))
                path = path.Replace("\\\\", "\\ \\");

            string[] segments = path.Split('\\');
            for (int j=0; j<segments.Length; j++)
                for (int i=200; i<segments[j].Length; i+=200)
                    segments[j] = segments[j].Substring(0, i) + '\\' + segments[j].Substring(i);
            path = String.Join("\\", segments);

            for (int i=0; i<path.Length; i++)
                if (path[i]=='\\' && Win32File.Exists(path.Substring(0, i)))
                {
                    string dirName = path.Substring(0, i);
                    string tempFileName = dirName+".temp-index";
                    Win32File.Move(dirName, tempFileName);
                    Win32Directory.CreateDirectory(dirName);
                    Win32File.Move(tempFileName, dirName+"\\index");
                }

            try {
                if (Win32Directory.Exists(path))
                    path = path + "\\";
            } catch(Exception e) { throw new Exception("Directory.Exists failure: " + path, e); }

            if (path[path.Length-1]=='\\')
                path = path + "index";

            //String dir = Path.GetDirectoryName(path);
            String dir = path.Substring(0, path.LastIndexOf('\\'));

            try {
                //if (!Directory.Exists(dir))
                //	Directory.CreateDirectory(dir);
                Win32Directory.CreateDirectory(dir);
            } catch(Exception e) { throw new Exception("Directory.CreateDirectory failure: " + dir, e); }

            oSession.utilDecodeResponse();

            //oSession.SaveResponseBody(path);
            byte[] data = oSession.responseBodyBytes;
            FileStream s;
            try {
                s = Win32File.Open(path, FileMode.Create);
            } catch(Exception e) { throw new Exception("Open failure: " + path, e); }
            try {
                s.Write(data, 0, data.Length);
            } catch(Exception e) { throw new Exception("Write failure: " + path, e); }
            try {
                s.Close();
            } catch(Exception e) { throw new Exception("Close failure: " + path, e); }
        }
    }
Example #13
0
    private void processRuleForSession(Session oSession, String ruleStr)
    {
        oSession.utilDecodeResponse();
        // check 304
        if (oSession.responseCode.ToString() == "304")
        {
            if (MessageBox.Show("This request session's ResponseCode is 304, means no data responded!\nContinue to Edit?", "Fedit Warning:",
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) return;
        }

        // check encode type
        FiddlerApplication.Log.LogString(oSession.GetResponseBodyEncoding().ToString());

        String tmp_filetype;
        if (fileType.ContainsKey(oSession.oResponse.MIMEType.ToString()))
        {
            tmp_filetype = (String)fileType[oSession.oResponse.MIMEType.ToString()];
        }
        else
        {
            Stack<string> ext = new Stack<string>(oSession.fullUrl.Split(new string[] { "." }, StringSplitOptions.None));
            tmp_filetype = "." + Regex.Replace(ext.Pop(), @"([a-zA-Z\d]+?)[^a-zA-Z\d].+", "$1");
        }
        String escaped_url = System.Uri.EscapeDataString(oSession.fullUrl);
        String tmp_filename = escaped_url.Substring(0, escaped_url.Length < 150 ? escaped_url.Length : 150) + tmp_filetype;
        String fedit_file = fedit_path + "\\" + tmp_filename;
        FiddlerApplication.Log.LogString("Saving url \"" + oSession.fullUrl + "\" to temp file \"" + fedit_file + "\"");
        if (oSession.oResponse.headers.ToString().ToLower().IndexOf("content-encoding:") >= 0)
        {
            // if encoded, decode it
            File.WriteAllBytes(fedit_file, oSession.responseBodyBytes);
        }
        else
        {
            // else load bytes
            File.WriteAllBytes(fedit_file, oSession.responseBodyBytes);
        }
        FiddlerApplication.Log.LogString(tmp_filename);
        // add AotuResponse rule
        if (tmp_rules.ContainsKey(oSession.fullUrl))
        {
            FiddlerApplication.oAutoResponder.RemoveRule((Fiddler.ResponderRule)tmp_rules[oSession.fullUrl]);
        }
        else
        {
            tmp_rules.Add(oSession.fullUrl, "");
        }
        tmp_rules[oSession.fullUrl] = (Fiddler.ResponderRule)FiddlerApplication.oAutoResponder.AddRule((ruleStr==""||ruleStr==null)?"EXACT:" + oSession.fullUrl:ruleStr, fedit_file, true);
        if(!FiddlerApplication.oAutoResponder.IsEnabled)
            MessageBox.Show("Notice! AutoResponder is not enabled! Please enable this.");

        FiddlerApplication.Log.LogString("Open file \"" + fedit_file + "\"");
        // edit file with default editor
        if (editor_setting.ContainsKey(tmp_filetype))
        {
            System.Diagnostics.Process.Start(editor_setting[tmp_filetype].ToString(), "\"" + fedit_file + "\"");
        }
        else
        {
            System.Diagnostics.Process.Start(editor_setting["default"].ToString(), "\"" + fedit_file + "\"");
        }
        FiddlerApplication.Log.LogString(fedit_file);
    }
        public CacheItem(Session session, string dir)
        {
            Url = session.fullUrl;
            try
            {
                Uri uri = new Uri(session.fullUrl);
                this.CheckState = System.Windows.Forms.CheckState.Checked;
                PathAndQuery = uri.PathAndQuery;
                ImageIndex = session.ViewItem.ImageIndex;
                Local = FileUtil.ReserveUriLocal(uri, dir, session.oResponse.MIMEType);
                ResponseHeaders = new List<CacheHeader>();
                    // new NameValueCollection();// new Dictionary<string, string>();
                Creation = DateTime.Now;
                Host = uri.Host;
                session.utilDecodeResponse();
                Length = session.responseBodyBytes.LongLength;
                foreach (Fiddler.HTTPHeaderItem item in session.oResponse.headers)
                {
                    ResponseHeaders.Add(new CacheHeader() { Name = item.Name, Value = item.Value });
                    //ResponseHeaders[item.Name] = item.Value;
                }

                FileInfo fi = new FileInfo(Local);
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }

                File.WriteAllBytes(Local, session.responseBodyBytes);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            
        }
Example #15
0
        public void AutoTamperResponseBefore(Session oSession)
        {
            if (!IsEnabled || !EnableAutoReload)
            {
                return;
            }

            var fullString = oSession.fullUrl.ToLower();

            foreach (var profile in _enabledProfiles)
            {
                if (fullString.Contains(profile.RemoteUrl.ToLower()))
                {
                    oSession.utilDecodeResponse();
                    bool replaced = oSession.utilReplaceInResponse("</body>", string.Format(
                        @"<script type='text/javascript'>window.__IMPOSTER = {{ profileId: '{0}' }};</script>
                          <script type='text/javascript' src='imposter.js'></script>
                          </body>", profile.ProfileId));

                    break;
                }
            }
        }
Example #16
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;
                }
            }
        }
        public void DoRewrite(Session oSession)
        {
            DebugProjectModule project;
            project = CurrentProject;

            if (project.HTMLPageURLs.Contains(oSession.fullUrl))
            {
                if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html"))
                {
                    Encoding oEnc = Utilities.getResponseBodyEncoding(oSession);
                    oSession.utilDecodeResponse();
                    var oBody = oEnc.GetString(oSession.responseBodyBytes);

                    JObject json = new JObject();
                    json["url"] = oSession.fullUrl;
                    json["html"] = oBody;
                    string result = this.PostJSONToServer(json, htmlRewriteCgi);
                    //TODO: parse result to json
                    JObject jsResult = JsonConvert.DeserializeObject(result) as JObject;
                    if (jsResult["error"] == null)
                    {
                        string body = jsResult["html"].Value<string>().Replace(__SERVER_URL__, this.serverURL);
                        if (body != null)
                        {
                            oSession.responseBodyBytes = oEnc.GetBytes(body);
                            oSession.oResponse.headers["Content-Length"] = oSession.responseBodyBytes.LongLength.ToString();
                            oSession["ui-backcolor"] = "LightBlue";
                        }
                    }
                    return;
                }
            }
            if (project.JSFileURLs.Contains(oSession.fullUrl))
            {
                if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "javascript"))
                {
                    Encoding oEnc = Utilities.getResponseBodyEncoding(oSession);
                    oSession.utilDecodeResponse();
                    var oBody = oEnc.GetString(oSession.responseBodyBytes);

                    JObject json = new JObject();
                    json["url"] = oSession.fullUrl;
                    json["js"] = oBody;
                    string result = this.PostJSONToServer(json, jsRewriteCgi);
                    JObject jsResult = JsonConvert.DeserializeObject(result) as JObject;
                    if (jsResult["error"] == null)
                    {
                        string js = jsResult["js"].Value<string>();
                        if (js != null)
                        {
                            oSession.responseBodyBytes = oEnc.GetBytes(js);
                            oSession.oResponse.headers["Content-Length"] = oSession.responseBodyBytes.LongLength.ToString();
                            oSession["ui-backcolor"] = "LightBlue";
                        }
                    }
                    return;

                }
            }
            if (project.JSFilename==oSession.fullUrl)
            {
                Encoding oEnc = Utilities.getResponseBodyEncoding(oSession);
                oSession.utilDecodeResponse();
                string oBody = oEnc.GetString(oSession.responseBodyBytes);
                oBody = oBody.Replace(__SERVER_URL__, this.serverURL);
                oSession.responseBodyBytes = oEnc.GetBytes(oBody);
                oSession.oResponse.headers["Content-Length"] = oSession.responseBodyBytes.LongLength.ToString();
                oSession["ui-backcolor"] = "LightBlue";

            }
        }