コード例 #1
0
ファイル: Diagnostic.cs プロジェクト: MasterDevs/yavc
        private string SaveSessions(string deviceName)
        {
            var thisProcId = System.Diagnostics.Process.GetCurrentProcess().Id;

            var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), string.Format("Results for {0}.saz", deviceName));

            SAZFormat.WriteSessionArchive(fileName,
                                          oAllSessions.Where(s => s.LocalProcessID == thisProcId).ToArray(), string.Empty, false);

            return(fileName);
        }
コード例 #2
0
        static void Main(string[] args)
        {
            // Currently, FiddlerCore uses one threadpool thread per active request. Due to how the .NET
            // threadpool growth algorithm works, performance can be improved by uncommenting the following
            // lines to set the minimum quantity of threads in the pool.

            /*
             *  int iProcCount = Environment.ProcessorCount;
             *  int iMinWorkerThreads = Math.Max(16, 6 * iProcCount);
             *  int iMinIOThreads = iProcCount;
             *  ThreadPool.SetMinThreads(iMinWorkerThreads, iMinIOThreads);
             */

            List <Fiddler.Session> oAllSessions = new List <Fiddler.Session>();

            #region AttachEventListeners
            //
            // It is important to understand that FiddlerCore calls event handlers on session-handling
            // background threads.  If you need to properly synchronize to the UI-thread (say, because
            // you're adding the sessions to a list view) you must call .Invoke on a delegate on the
            // window handle.
            //
            // If you are writing to a non-threadsafe data structure (e.g. List<t>) you must
            // use a Monitor or other mechanism to ensure safety.
            //

            // Simply echo notifications to the console.  Because Fiddler.CONFIG.QuietMode=true
            // by default, we must handle notifying the user ourselves.
            Fiddler.FiddlerApplication.OnNotification  += delegate(object sender, NotificationEventArgs oNEA) { Console.WriteLine("** NotifyUser: "******"** LogString: " + oLEA.LogString); };

            Fiddler.FiddlerApplication.BeforeRequest += delegate(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;
                Monitor.Enter(oAllSessions);
                oAllSessions.Add(oS);
                Monitor.Exit(oAllSessions);
                oS["X-AutoAuth"] = "(default)";

                /* If the request is going to our secure endpoint, we'll echo back the response.
                 *
                 * Note: This BeforeRequest is getting called for both our main proxy tunnel AND our secure endpoint,
                 * so we have to look at which Fiddler port the client connected to (pipeClient.LocalPort) to determine whether this request
                 * was sent to secure endpoint, or was merely sent to the main proxy tunnel (e.g. a CONNECT) in order to *reach* the secure endpoint.
                 *
                 * As a result of this, if you run the demo and visit https://localhost:7777 in your browser, you'll see
                 *
                 * Session list contains...
                 *
                 *  1 CONNECT http://localhost:7777
                 *  200                                         <-- CONNECT tunnel sent to the main proxy tunnel, port 8877
                 *
                 *  2 GET https://localhost:7777/
                 *  200 text/html                               <-- GET request decrypted on the main proxy tunnel, port 8877
                 *
                 *  3 GET https://localhost:7777/
                 *  200 text/html                               <-- GET request received by the secure endpoint, port 7777
                 */

                if ((oS.oRequest.pipeClient.LocalPort == iSecureEndpointPort) && (oS.hostname == sSecureEndpointHostname))
                {
                    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 + ":" + iSecureEndpointPort.ToString() + " received. Your request was:<br /><plaintext>" + oS.oRequest.headers.ToString());
                }
            };

            /*
             *  // The following event allows you to examine every response buffer read by Fiddler. Note that this isn't useful for the vast majority of
             *  // applications because the raw buffer is nearly useless; it's not decompressed, it includes both headers and body bytes, etc.
             *  //
             *  // This event is only useful for a handful of applications which need access to a raw, unprocessed byte-stream
             *  Fiddler.FiddlerApplication.OnReadResponseBuffer += new EventHandler<RawReadEventArgs>(FiddlerApplication_OnReadResponseBuffer);
             */

            /*
             * Fiddler.FiddlerApplication.BeforeResponse += delegate(Fiddler.Session oS) {
             *  // Console.WriteLine("{0}:HTTP {1} for {2}", oS.id, oS.responseCode, oS.fullUrl);
             *
             *  // Uncomment the following two statements to decompress/unchunk the
             *  // HTTP response and subsequently modify any HTTP responses to replace
             *  // instances of the word "Microsoft" with "Bayden". You MUST also
             *  // set bBufferResponse = true inside the beforeREQUEST method above.
             *  //
             *  //oS.utilDecodeResponse(); oS.utilReplaceInResponse("Microsoft", "Bayden");
             * };*/

            Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
            {
                //Console.WriteLine("Finished session:\t" + oS.fullUrl);
                Console.Title = ("Session list contains: " + oAllSessions.Count.ToString() + " sessions");
            };

            // Tell the system console to handle CTRL+C by calling our method that
            // gracefully shuts down the FiddlerCore.
            //
            // Note, this doesn't handle the case where the user closes the window with the close button.
            // See http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx for info on that...
            //
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            #endregion AttachEventListeners

            string sSAZInfo = "NoSAZ";
#if SAZ_SUPPORT
            // If this demo was compiled with a SAZ-Transcoder, then the following lines will load the
            // Transcoders into the available transcoders. You can load other types of Transcoders from
            // a different assembly if you'd like, using the ImportTranscoders(string AssemblyPath) overload.
            // See https://www.fiddler2.com/dl/FiddlerCore-BasicFormats.zip for an example.
            //
            if (!FiddlerApplication.oTranscoders.ImportTranscoders(Assembly.GetExecutingAssembly()))
            {
                Console.WriteLine("This assembly was not compiled with a SAZ-exporter");
            }
            else
            {
                sSAZInfo = SAZFormat.GetZipLibraryInfo();
            }
#endif

            Console.WriteLine(String.Format("Starting {0} ({1})...", Fiddler.FiddlerApplication.GetVersionString(), sSAZInfo));

            // For the purposes of this demo, we'll forbid connections to HTTPS
            // sites that use invalid certificates. Change this from the default only
            // if you know EXACTLY what that implies.
            Fiddler.CONFIG.IgnoreServerCertErrors = false;

            // ... but you can allow a specific (even invalid) certificate by implementing and assigning a callback...
            // FiddlerApplication.OnValidateServerCertificate += new System.EventHandler<ValidateServerCertificateEventArgs>(CheckCert);

            FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

            // For forward-compatibility with updated FiddlerCore libraries, it is strongly recommended that you
            // start with the DEFAULT options and manually disable specific unwanted options.
            FiddlerCoreStartupFlags oFCSF = FiddlerCoreStartupFlags.Default;

            // E.g. If you want to add a flag, start with the .Default and "OR" the new flag on:
            // oFCSF = (oFCSF | FiddlerCoreStartupFlags.CaptureFTP);

            // ... or if you don't want a flag in the defaults, "and not" it out:
            // Uncomment the next line if you don't want FiddlerCore to act as the system proxy
            // oFCSF = (oFCSF & ~FiddlerCoreStartupFlags.RegisterAsSystemProxy);

            // *******************************
            // Important HTTPS Decryption Info
            // *******************************
            // When FiddlerCoreStartupFlags.DecryptSSL is enabled, you must include either
            //
            //     MakeCert.exe
            //
            // *or*
            //
            //     CertMaker.dll
            //     BCMakeCert.dll
            //
            // ... in the folder where your executable and FiddlerCore.dll live. These files
            // are needed to generate the self-signed certificates used to man-in-the-middle
            // secure traffic. MakeCert.exe uses Windows APIs to generate certificates which
            // are stored in the user's \Personal\ Certificates store. These certificates are
            // NOT compatible with iOS devices which require specific fields in the certificate
            // which are not set by MakeCert.exe.
            //
            // In contrast, CertMaker.dll uses the BouncyCastle C# library (BCMakeCert.dll) to
            // generate new certificates from scratch. These certificates are stored in memory
            // only, and are compatible with iOS devices.

            // Uncomment the next line if you don't want to decrypt SSL traffic.
            // oFCSF = (oFCSF & ~FiddlerCoreStartupFlags.DecryptSSL);

            // NOTE: In the next line, you can pass 0 for the port (instead of 8877) to have FiddlerCore auto-select an available port
            int iPort = 8877;
            Fiddler.FiddlerApplication.Startup(iPort, oFCSF);

            FiddlerApplication.Log.LogFormat("Created endpoint listening on port {0}", iPort);

            FiddlerApplication.Log.LogFormat("Starting with settings: [{0}]", oFCSF);
            FiddlerApplication.Log.LogFormat("Gateway: {0}", CONFIG.UpstreamGateway.ToString());

            Console.WriteLine("Hit CTRL+C to end session.");

            // We'll also create a HTTPS listener, useful for when FiddlerCore is masquerading as a HTTPS server
            // instead of acting as a normal CERN-style proxy server.
            oSecureEndpoint = FiddlerApplication.CreateProxyEndpoint(iSecureEndpointPort, true, sSecureEndpointHostname);
            if (null != oSecureEndpoint)
            {
                FiddlerApplication.Log.LogFormat("Created secure endpoint listening on port {0}, using a HTTPS certificate for '{1}'", iSecureEndpointPort, sSecureEndpointHostname);
            }

            bool bDone = false;
            do
            {
                Console.WriteLine("\nEnter a command [C=Clear; L=List; G=Collect Garbage; W=write SAZ; R=read SAZ;\n\tS=Toggle Forgetful Streaming; T=Trust Root Certificate; Q=Quit]:");
                Console.Write(">");
                ConsoleKeyInfo cki = Console.ReadKey();
                Console.WriteLine();
                switch (cki.KeyChar)
                {
                case 'c':
                    Monitor.Enter(oAllSessions);
                    oAllSessions.Clear();
                    Monitor.Exit(oAllSessions);
                    WriteCommandResponse("Clear...");
                    FiddlerApplication.Log.LogString("Cleared session list.");
                    break;

                case 'd':
                    FiddlerApplication.Log.LogString("FiddlerApplication::Shutdown.");
                    FiddlerApplication.Shutdown();
                    break;

                case 'l':
                    WriteSessionList(oAllSessions);
                    break;

                case 'g':
                    Console.WriteLine("Working Set:\t" + Environment.WorkingSet.ToString("n0"));
                    Console.WriteLine("Begin GC...");
                    GC.Collect();
                    Console.WriteLine("GC Done.\nWorking Set:\t" + Environment.WorkingSet.ToString("n0"));
                    break;

                case 'q':
                    bDone = true;
                    DoQuit();
                    break;

                case 'r':
#if SAZ_SUPPORT
                    ReadSessions(oAllSessions);
#else
                    WriteCommandResponse("This demo was compiled without SAZ_SUPPORT defined");
#endif
                    break;

                case 'w':
#if SAZ_SUPPORT
                    if (oAllSessions.Count > 0)
                    {
                        SaveSessionsToDesktop(oAllSessions);
                    }
                    else
                    {
                        WriteCommandResponse("No sessions have been captured");
                    }
#else
                    WriteCommandResponse("This demo was compiled without SAZ_SUPPORT defined");
#endif
                    break;

                case 't':
                    try
                    {
                        WriteCommandResponse("Result: " + CertMaker.trustRootCert().ToString());
                    }
                    catch (Exception eX)
                    {
                        WriteCommandResponse("Failed: " + eX.ToString());
                    }
                    break;

                // Forgetful streaming
                case 's':
                    bool bForgetful = !FiddlerApplication.Prefs.GetBoolPref("fiddler.network.streaming.ForgetStreamedData", false);
                    FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.ForgetStreamedData", bForgetful);
                    Console.WriteLine(bForgetful ? "FiddlerCore will immediately dump streaming response data." : "FiddlerCore will keep a copy of streamed response data.");
                    break;
                }
            } while (!bDone);
        }
コード例 #3
0
        public ProxyDump()
        {
            // List holding all sessions
            oAllSessions = new List <Fiddler.Session>();
            // List for single dumped session
            oSingleSession = new List <Fiddler.Session>();

            int _counter = 0;

            try
            {
                if (!Directory.Exists(ResponsePath))
                {
                    Directory.CreateDirectory(ResponsePath);
                }
            }
            catch (Exception ex)
            {
                WriteCommandResponse("Error while creating directory: " + ResponsePath + Environment.NewLine + ex);
            }

            WriteCommandResponse("ProxyDump [Alpha] 2018 by phono");


            //Load URIFilter
            LoadURIFilter();

            LoadResponseFile();

            #region AttachEventListeners
            //
            // It is important to understand that FiddlerCore calls event handlers on session-handling
            // background threads.  If you need to properly synchronize to the UI-thread (say, because
            // you're adding the sessions to a list view) you must call .Invoke on a delegate on the
            // window handle.
            //
            // If you are writing to a non-threadsafe data structure (e.g. List<t>) you must
            // use a Monitor or other mechanism to ensure safety.
            //

            // Simply echo notifications to the console.  Because Fiddler.CONFIG.QuietMode=true
            // by default, we must handle notifying the user ourselves.
            if (fiddlermessages && !HandlerRegistered)
            {
                Fiddler.FiddlerApplication.OnNotification  += delegate(object sender, NotificationEventArgs oNEA) { Console.WriteLine("** NotifyUser: "******"**NotifyUser: "******"** LogString: " + oLEA.LogString); WriteCommandResponse("**LogString: " + oLEA.LogString); };
            }

            if (!HandlerRegistered)
            {
                Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
                {
                    HandlerRegistered = true;

                    // 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;
                    Monitor.Enter(oAllSessions);
                    oAllSessions.Add(oS);
                    Monitor.Exit(oAllSessions);

                    #region OwnCode
                    if (connectionmessages)
                    {
                        Console.Write(String.Format("{0} {1} {2}\n{3} {4}\n\n", oS.id, oS.oRequest.headers.HTTPMethod, Ellipsize(oS.fullUrl, 60), oS.responseCode, oS.oResponse.MIMEType));
                    }
                    WriteCommandResponse(String.Format("{0} {1} {2}\n{3} {4}\n\n", oS.id, oS.oRequest.headers.HTTPMethod, Ellipsize(oS.fullUrl, 60), oS.responseCode, oS.oResponse.MIMEType));

                    //string URIFilterFilePath = "responses/urifilter.txt";
                    // Declare new List.
                    List <string> lines = new List <string>();

                    if (URIFilterList != null && URIFilterList.Count > 0)
                    {
                        lines.AddRange(URIFilterList);
                    }

                    foreach (string s in lines)
                    {
                        if (DebugMessages)
                        {
                            WriteCommandResponse("Filter is active: " + filteractive);
                        }
                        if (DebugMessages)
                        {
                            WriteCommandResponse("oS.uriContains(s): " + oS.uriContains(s) + " " + oS.url);
                        }
                        if (oS.uriContains(s) && filteractive)
                        {
                            WriteCommandResponse("INTERCEPTED CALL TO: " + Environment.NewLine);
                            WriteCommandResponse(String.Format("{0} {1} {2}\n{3} {4}\n\n", oS.id, oS.oRequest.headers.HTTPMethod, Ellipsize(oS.fullUrl, 60), oS.responseCode, oS.oResponse.MIMEType));


                            // if DumpMode add Session and directly save it and clear it to only write a single session for each file
                            if (DumpMode)
                            {
                                Monitor.Enter(oSingleSession);
                                oSingleSession.Add(oS);
                                Monitor.Exit(oSingleSession);
                            }

                            if (DebugMessages)
                            {
                                WriteCommandResponse("DumpMode is active: " + DumpMode);
                            }
                            if (!DumpMode)
                            {
                                //Send SINGLE RESPONSE

                                oS.utilCreateResponseAndBypassServer();

                                // Inside your main object, create a list to hold the sessions
                                // This generic list type requires your source file includes #using System.Collections.Generic.
                                List <Fiddler.Session> ReplaySessions = new List <Fiddler.Session>();
                                Session[] ReplaySession;

                                TranscoderTuple oImporter = FiddlerApplication.oTranscoders.GetImporter("SAZ");
                                if (null != oImporter && CurrentResponseFile != null)
                                {
                                    Dictionary <string, object> dictOptions = new Dictionary <string, object>();
                                    dictOptions.Add("Filename", CurrentResponseFile);

                                    ReplaySession = FiddlerApplication.DoImport("SAZ", false, dictOptions, null);

                                    if ((ReplaySession != null) && (ReplaySession.Length > 0))
                                    {
                                        ReplaySessions.AddRange(ReplaySession);

                                        oS.responseBodyBytes = ReplaySession[0].responseBodyBytes;
                                        oS.oResponse.headers = (HTTPResponseHeaders)ReplaySession[0].oResponse.headers.Clone();

                                        string shortResponseBody = System.Text.Encoding.UTF8.GetString(ReplaySession[0].responseBodyBytes).Substring(0, 100);
                                        WriteCommandResponse(ReplaySession[0].oResponse.headers.ToString());
                                        WriteCommandResponse(shortResponseBody + " ...");
                                        WriteCommandResponse("Loaded: " + ReplaySession.Length + " sessions.");
                                    }
                                }
                                else if (CurrentResponseFile == null)
                                {
                                    WriteCommandResponse("Error: no recorded sessions found");
                                }
                            }//END if (!DumpMode)
                        }
                    }
                    #endregion OwnCode



                    /* If the request is going to our secure endpoint, we'll echo back the response.
                     *
                     * Note: This BeforeRequest is getting called for both our main proxy tunnel AND our secure endpoint,
                     * so we have to look at which Fiddler port the client connected to (pipeClient.LocalPort) to determine whether this request
                     * was sent to secure endpoint, or was merely sent to the main proxy tunnel (e.g. a CONNECT) in order to *reach* the secure endpoint.
                     *
                     * As a result of this, if you run the demo and visit https://localhost:7777 in your browser, you'll see
                     *
                     * Session list contains...
                     *
                     *  1 CONNECT http://localhost:7777
                     *  200                                         <-- CONNECT tunnel sent to the main proxy tunnel, port 8877
                     *
                     *  2 GET https://localhost:7777/
                     *  200 text/html                               <-- GET request decrypted on the main proxy tunnel, port 8877
                     *
                     *  3 GET https://localhost:7777/
                     *  200 text/html                               <-- GET request received by the secure endpoint, port 7777
                     */

                    if ((oS.oRequest.pipeClient.LocalPort == iSecureEndpointPort) && (oS.hostname == sSecureEndpointHostname))
                    {
                        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 + ":" + iSecureEndpointPort.ToString() + " received. Your request was:<br /><plaintext>" + oS.oRequest.headers.ToString());
                    }
                }; // END before Request
            }

            /*
             *  // The following event allows you to examine every response buffer read by Fiddler. Note that this isn't useful for the vast majority of
             *  // applications because the raw buffer is nearly useless; it's not decompressed, it includes both headers and body bytes, etc.
             *  //
             *  // This event is only useful for a handful of applications which need access to a raw, unprocessed byte-stream
             *  Fiddler.FiddlerApplication.OnReadResponseBuffer += new EventHandler<RawReadEventArgs>(FiddlerApplication_OnReadResponseBuffer);
             */

            /*
             * Fiddler.FiddlerApplication.BeforeResponse += delegate(Fiddler.Session oS) {
             *  // Console.WriteLine("{0}:HTTP {1} for {2}", oS.id, oS.responseCode, oS.fullUrl);
             *
             *  // Uncomment the following two statements to decompress/unchunk the
             *  // HTTP response and subsequently modify any HTTP responses to replace
             *  // instances of the word "Microsoft" with "Bayden". You MUST also
             *  // set bBufferResponse = true inside the beforeREQUEST method above.
             *  //
             *  //oS.utilDecodeResponse(); oS.utilReplaceInResponse("Microsoft", "Bayden");
             * };*/

            Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
            {
                //Console.WriteLine("Finished session:\t" + oS.fullUrl);
                if (bUpdateTitle)
                {
                    try
                    {
                        Console.Title = ("Session list contains: " + oAllSessions.Count.ToString() + " sessions");
                    }
                    catch (Exception ex)
                    {
                        //not running in console
                    }
                }

                // if DumpMode add Session and directly save it and clear it to only write a single session for each file
                if (DumpMode)
                {
                    if (SplitSessionsFiles)
                    {
                        WriteSessionList(oSingleSession);

                        if (oSingleSession.Count > 0)
                        {
                            //SaveSessionsToDesktop(oSingleSession);
                            SaveSessionsToDumpFolder(oSingleSession);
                        }
                        else
                        {
                            WriteCommandResponse("No sessions have been captured");
                        }

                        Monitor.Enter(oSingleSession);
                        oSingleSession.Clear();
                        Monitor.Exit(oSingleSession);
                    }

                    //test dump all sessions
                    SaveSessionsToDumpFolder(oAllSessions, true);
                }
            };

            // Tell the system console to handle CTRL+C by calling our method that
            // gracefully shuts down the FiddlerCore.
            //
            // Note, this doesn't handle the case where the user closes the window with the close button.
            // See http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx for info on that...
            //
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            #endregion AttachEventListeners

            string sSAZInfo = "NoSAZ";
#if SAZ_SUPPORT
            // If this demo was compiled with a SAZ-Transcoder, then the following lines will load the
            // Transcoders into the available transcoders. You can load other types of Transcoders from
            // a different assembly if you'd like, using the ImportTranscoders(string AssemblyPath) overload.
            // See https://www.fiddler2.com/dl/FiddlerCore-BasicFormats.zip for an example.
            //
            if (!FiddlerApplication.oTranscoders.ImportTranscoders(Assembly.GetExecutingAssembly()))
            {
                Console.WriteLine("This assembly was not compiled with a SAZ-exporter");
            }
            else
            {
                sSAZInfo = SAZFormat.GetZipLibraryInfo();
            }
#endif

            if (fiddlermessages)
            {
                Console.WriteLine(String.Format("Starting {0} ({1})...", Fiddler.FiddlerApplication.GetVersionString(), sSAZInfo));
            }

            // For the purposes of this demo, we'll forbid connections to HTTPS
            // sites that use invalid certificates. Change this from the default only
            // if you know EXACTLY what that implies.
            Fiddler.CONFIG.IgnoreServerCertErrors = true;

            // ... but you can allow a specific (even invalid) certificate by implementing and assigning a callback...
            // FiddlerApplication.OverrideServerCertificateValidation += new OverrideCertificatePolicyHandler(FiddlerApplication_OverrideServerCertificateValidation);

            FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

            // For forward-compatibility with updated FiddlerCore libraries, it is strongly recommended that you
            // start with the DEFAULT options and manually disable specific unwanted options.
            //FiddlerCoreStartupFlags oFCSF = FiddlerCoreStartupFlags.Default;
            // E.g. uncomment the next line if you don't want FiddlerCore to act as the system proxy
            FCSF = (FCSF & ~FiddlerCoreStartupFlags.RegisterAsSystemProxy);
            // or uncomment the next line if you don't want to decrypt SSL traffic.
            //FCSF = (FCSF & ~FiddlerCoreStartupFlags.DecryptSSL);

            //Start(oFCSF);

            /*
             * // Console App
             *
             * bool bDone = false;
             * do
             * {
             *  Console.WriteLine("\nEnter a command [C=Clear; L=List; d=Toggle Connection Messages;\n\tF=Toggle Filters; G=Collect Garbage; H=Toggle ResponseSessionFile;\n\tI=Toggle Infomessages; J=Toggle DumpMode; W=write SAZ; R=read SAZ;\n\tS=Toggle Forgetful Streaming; T=Toggle Title Counter; Q=Quit]:");
             *  Console.Write(">");
             *  ConsoleKeyInfo cki = Console.ReadKey();
             *  Console.WriteLine();
             *  switch (cki.KeyChar)
             *  {
             *      case 'c':
             *          Monitor.Enter(oAllSessions);
             *          oAllSessions.Clear();
             *          Monitor.Exit(oAllSessions);
             *          WriteCommandResponse("Clear...");
             *          FiddlerApplication.Log.LogString("Cleared session list.");
             *          break;
             *
             *      case 'l':
             *          WriteSessionList(oAllSessions);
             *          break;
             *
             *      case 'd':
             *          connectionmessages = !connectionmessages;
             *          WriteCommandResponse("Show Connection Messages: " + connectionmessages);
             *          break;
             *
             *      case 'f':
             *          filteractive = !filteractive;
             *          WriteCommandResponse("Filters active: " + filteractive);
             *          break;
             *
             *      case 'h':
             *          actualSAZfile = _SAZfiles[_counter++ % _SAZfiles.Length];
             *          WriteCommandResponse("Using for AutoResponse: " + actualSAZfile);
             *          break;
             *
             *      case 'i':
             *          fiddlermessages = !fiddlermessages;
             *          WriteCommandResponse("Show Infomessages: " + fiddlermessages);
             *          break;
             *
             *      case 'j':
             *          DumpMode = !DumpMode;
             *          WriteCommandResponse("DumpMode active: " + DumpMode);
             *          break;
             *
             *      case 'g':
             *          Console.WriteLine("Working Set:\t" + Environment.WorkingSet.ToString("n0"));
             *          Console.WriteLine("Begin GC...");
             *          GC.Collect();
             *          Console.WriteLine("GC Done.\nWorking Set:\t" + Environment.WorkingSet.ToString("n0"));
             *          break;
             *
             *      case 'q':
             *          bDone = true;
             *          DoQuit();
             *          break;
             *
             *      case 'r':
             #if SAZ_SUPPORT
             *          ReadSessions(oAllSessions);
             #else
             *          WriteCommandResponse("This demo was compiled without SAZ_SUPPORT defined");
             #endif
             *          break;
             *
             *      case 'w':
             #if SAZ_SUPPORT
             *          if (oAllSessions.Count > 0)
             *          {
             *              SaveSessionsToDesktop(oAllSessions);
             *          }
             *          else
             *          {
             *              WriteCommandResponse("No sessions have been captured");
             *          }
             #else
             *          WriteCommandResponse("This demo was compiled without SAZ_SUPPORT defined");
             #endif
             *          break;
             *
             *      case 't':
             *          bUpdateTitle = !bUpdateTitle;
             *          Console.Title = (bUpdateTitle) ? "Title bar will update with request count..." :
             *              "Title bar update suppressed...";
             *          break;
             *
             *      // Forgetful streaming
             *      case 's':
             *          bool bForgetful = !FiddlerApplication.Prefs.GetBoolPref("fiddler.network.streaming.ForgetStreamedData", false);
             *          FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.ForgetStreamedData", bForgetful);
             *          Console.WriteLine(bForgetful ? "FiddlerCore will immediately dump streaming response data." : "FiddlerCore will keep a copy of streamed response data.");
             *          break;
             *
             *  }
             * } while (!bDone);
             */
        }
コード例 #4
0
        static void Main(string[] args)
        {
            WriteHelp("Current hosts in system is :");
            Config.LoadHosts();//print hosts lists

            //Config.AddHost("211.82.8.7", "c.com", "test", false,false);
            Config.SetConfig();//init to set config

            List <Fiddler.Session> oAllSessions = new List <Fiddler.Session>();

            //if (args.Length == 0){
            //Config.DomainFilter =  "renren.com";
            //}
            if (args.Length == 1)
            {
                Application.EnableVisualStyles();
                Application.Run(new Form1());
            }
            if (args.Length == 2)
            {
                Config.Port         = int.Parse(args[0]);
                Config.DomainFilter = args[1];
            }
            #region AttachEventListeners
            //
            // It is important to understand that FiddlerCore calls event handlers on session-handling
            // background threads.  If you need to properly synchronize to the UI-thread (say, because
            // you're adding the sessions to a list view) you must call .Invoke on a delegate on the
            // window handle.
            //
            // If you are writing to a non-threadsafe data structure (e.g. List<t>) you must
            // use a Monitor or other mechanism to ensure safety.
            //

            // Simply echo notifications to the console.  Because Fiddler.CONFIG.QuietMode=true
            // by default, we must handle notifying the user ourselves.

            /*
             * Fiddler.FiddlerApplication.OnNotification += delegate(object sender, NotificationEventArgs oNEA)
             * {
             *  WriteLog("** NotifyUser: "******"** LogString: " + oLEA.LogString);
             * };*/

            Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
            {
                if (oS.host.EndsWith(Config.DomainFilter))
                {
                    //Console.WriteLine("Before request for:\t" + Ellipsize(oS.fullUrl,60));


                    // 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;
                    Monitor.Enter(oAllSessions);
                    oAllSessions.Add(oS);
                    Monitor.Exit(oAllSessions);
                }
                ;

                // All requests for subdomain.example.com should be directed to the development server at 123.125.44.242
                if (oS.host.StartsWith("localhost"))
                {
                    oS.bypassGateway     = true;              // Prevent this request from going through an upstream proxy
                    oS["x-overrideHost"] = "123.125.44.242";  // DNS name or IP address of target server
                }

                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());
                }
            };

            /*
             *  // The following event allows you to examine every response buffer read by Fiddler. Note that this isn't useful for the vast majority of
             *  // applications because the raw buffer is nearly useless; it's not decompressed, it includes both headers and body bytes, etc.
             *  //
             *  // This event is only useful for a handful of applications which need access to a raw, unprocessed byte-stream
             *  Fiddler.FiddlerApplication.OnReadResponseBuffer += new EventHandler<RawReadEventArgs>(FiddlerApplication_OnReadResponseBuffer);
             */


            Fiddler.FiddlerApplication.BeforeResponse += delegate(Fiddler.Session oS) {
                // Console.WriteLine("{0}:HTTP {1} for {2}", oS.id, oS.responseCode, oS.fullUrl);

                // Uncomment the following two statements to decompress/unchunk the
                // HTTP response and subsequently modify any HTTP responses to replace
                // instances of the word "Microsoft" with "Bayden". You MUST also
                // set bBufferResponse = true inside the beforeREQUEST method above.
                //
                //oS.utilDecodeResponse(); oS.utilReplaceInResponse("Microsoft", "Bayden");
            };

            Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
            {
                //Console.WriteLine("Finished session:\t" + oS.fullUrl);
                if (bUpdateTitle)
                {
                    Console.Title = ("Session list contains: " + oAllSessions.Count.ToString() + " sessions");
                }
#if SAZ_SUPPORT
                if (oAllSessions.Count > Config.MaxLogLength)
                {
                    //save log
                    //MySession.SaveSessionsTo(oAllSessions,@"log\");
                    //clear mem
                    Monitor.Enter(oAllSessions);
                    oAllSessions.Clear();
                    Monitor.Exit(oAllSessions);
                }
                ;
#endif
            };

            // Tell the system console to handle CTRL+C by calling our method that
            // gracefully shuts down the FiddlerCore.
            //
            // Note, this doesn't handle the case where the user closes the window with the close button.
            // See http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx for info on that...
            //
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            #endregion AttachEventListeners

            string sSAZInfo = "NoSAZ";
#if SAZ_SUPPORT
            // If this demo was compiled with a SAZ-Transcoder, then the following lines will load the
            // Transcoders into the available transcoders. You can load other types of Transcoders from
            // a different assembly if you'd like, using the ImportTranscoders(string AssemblyPath) overload.
            // See https://www.fiddler2.com/dl/FiddlerCore-BasicFormats.zip for an example.
            //
            if (!FiddlerApplication.oTranscoders.ImportTranscoders(Assembly.GetExecutingAssembly()))
            {
                Console.WriteLine("This assembly was not compiled with a SAZ-exporter");
            }
            else
            {
                sSAZInfo = SAZFormat.GetZipLibraryInfo();
            }
#endif

            //Console.WriteLine(String.Format("Starting {0} ({1})...", Fiddler.FiddlerApplication.GetVersionString(), sSAZInfo));

            // For the purposes of this demo, we'll forbid connections to HTTPS
            // sites that use invalid certificates
            Fiddler.CONFIG.IgnoreServerCertErrors = true;

            // but we can allow a specific (even invalid) certificate by implementing and assigning a callback...
            // FiddlerApplication.OverrideServerCertificateValidation += new OverrideCertificatePolicyHandler(FiddlerApplication_OverrideServerCertificateValidation);

            // Because we've chosen to decrypt HTTPS traffic, makecert.exe must
            // be present in the Application folder.

            FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

            Fiddler.FiddlerApplication.Startup(Config.Port, FiddlerCoreStartupFlags.Default);
            FiddlerApplication.Log.LogString("Using Gateway: " + ((CONFIG.bForwardToGateway) ? "TRUE" : "FALSE"));

            Console.WriteLine("Hit CTRL+C to end session.");

            oSecureEndpoint = null;
            oSecureEndpoint = FiddlerApplication.CreateProxyEndpoint(7777, true, sSecureEndpointHostname);
            if (null != oSecureEndpoint)
            {
                FiddlerApplication.Log.LogString("Created secure end point listening on port 7777, using a HTTPS certificate for '" + sSecureEndpointHostname + "'");
            }
            if (Config.DomainFilter == "")
            {
                //WriteTest("Listening in the port "+Port+" for all domains");
                WriteTest("Listening in the port ");
                WriteWarning("\b" + Config.Port);
                WriteTest(" for all domains");
            }
            else
            {
                WriteTest("Listening in the port ");
                WriteWarning("" + Config.Port);
                WriteTest(" for domain:");
                WriteWarning("" + Config.DomainFilter);
            }

            //XNMD.F.Show("test");
            //begin xss detect when start
            ualoader = new UALoader();
            Console.WriteLine("starting xss detect.....\nuse your ie or chrome to browser your web page\n");
            ualoader.OnLoad();
            bool mDone = false;

            do
            {
                WriteHelp("\nCommand:\n[d=Domain config;c=Clear cache; L=List session;  q=Quit;g=Collect Garbage;\nh=Hosts config; w=Write SAZ;r=reload SAZ; s=Toggle Forgetful Streaming; t=Toggle Title Counter;e=encode tool;]:");
                Console.Write("main>");
                ConsoleKeyInfo cki = Console.ReadKey();
                Console.WriteLine();
                switch (cki.KeyChar)
                {
                case 'c':
                    Monitor.Enter(oAllSessions);
                    oAllSessions.Clear();
                    Monitor.Exit(oAllSessions);
                    WriteCommandResponse("Clear...");
                    FiddlerApplication.Log.LogString("Cleared session list.");
                    break;

                case 'd':
                    if (Config.DomainFilter == "")
                    {
                        WriteTest("capture all domain\n");
                    }
                    else
                    {
                        WriteTest("domain is :" + Config.DomainFilter + "\n");
                    }
                    Console.Write("input new domain:\n");
                    Config.DomainFilter = Console.ReadLine();
                    if (Config.DomainFilter == "")
                    {
                        WriteTest("capture all domain\n");
                    }
                    else
                    {
                        WriteTest("domain is :" + Config.DomainFilter + "\n");
                    }
                    Config.Conf["configuration"]["domain"].InnerText = Config.DomainFilter;
                    break;

                case 'l':
                    MySession.WriteSessionList(oAllSessions);
                    break;

                case 'g':
                    Console.WriteLine("Working Set:\t" + Environment.WorkingSet.ToString("n0"));
                    Console.WriteLine("Begin GC...");
                    GC.Collect();
                    Console.WriteLine("GC Done.\nWorking Set:\t" + Environment.WorkingSet.ToString("n0"));
                    break;

                case 'h':
                    WriteHelp("set hosts");

                    Application.EnableVisualStyles();
                    //Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                    break;

                case 'q':
                    mDone = true;
                    Config.Conf.Save(Config.strConfFileName);

                    break;

                case 'r':
#if SAZ_SUPPORT
                    MySession.ReadSessions(oAllSessions);
#else
                    WriteCommandResponse("This demo was compiled without SAZ_SUPPORT defined");
#endif
                    break;

                case 'w':
#if SAZ_SUPPORT
                    if (oAllSessions.Count > 0)
                    {
                        MySession.SaveSessionsTo(oAllSessions, @"log\");
                        Monitor.Enter(oAllSessions);
                        oAllSessions.Clear();
                        Monitor.Exit(oAllSessions);
                    }
                    else
                    {
                        WriteCommandResponse("No sessions have been captured");
                    }
#else
                    WriteCommandResponse("This demo was compiled without SAZ_SUPPORT defined");
#endif
                    break;

                case 't':
                    bUpdateTitle  = !bUpdateTitle;
                    Console.Title = (bUpdateTitle) ? "Title bar will update with request count..." :
                                    "Title bar update suppressed...";
                    break;


                // Forgetful streaming
                case 's':
                    bool bForgetful = !FiddlerApplication.Prefs.GetBoolPref("fiddler.network.streaming.ForgetStreamedData", false);
                    FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.ForgetStreamedData", bForgetful);
                    Console.WriteLine(bForgetful ? "FiddlerCore will immediately dump streaming response data." : "FiddlerCore will keep a copy of streamed response data.");
                    break;

                case 'e':
                    frmTextWizard wizard = new frmTextWizard();
                    //wizard.Show();
                    Application.Run(wizard);
                    break;

                    //case 'x':

                    //    ualoader = new UALoader();
                    //    Console.WriteLine("starting xss detect.....");
                    //    ualoader.OnLoad();
                    //    //ualoader.OnBeforeUnload();
                    //    break;

                    /*
                     * case 'p':
                     *  bool pDone = false;
                     *  do
                     *  {
                     *      WriteHelp("\nCommand [M|Q=Back to Main;X=XSS detect;#todo:R=Record a login;S=Scan;");
                     *      Console.Write("Penetest>");
                     *      ConsoleKeyInfo pki = Console.ReadKey();
                     *      Console.WriteLine();
                     *      switch(pki.KeyChar)
                     *      {
                     *          case 'm':
                     *              //back to main
                     *              pDone = true;
                     *              break;
                     *          case 'q':
                     *              //back to main
                     *              pDone = true;
                     *              break;
                     *          //case 'r':
                     *          //    string url = Interaction.InputBox("请输入登录入口", "录制登录过程", "http://www.renren.com", 100, 100);
                     *          //    //string html = LoginRecord.browser("http://wap.renren.com");
                     *          //    //WriteWarning("html:"+html);
                     *          //    //LoginRecord.msgbox("hello");
                     *          //    LoginRecord.Browser(url);
                     *          //    break;
                     *
                     *          case 'x':
                     *
                     *              ualoader = new UALoader();
                     *              Console.WriteLine("starting xss detect.....");
                     *              ualoader.OnLoad();
                     *              //ualoader.OnBeforeUnload();
                     *              break;
                     *
                     *
                     *      }
                     *  } while (!pDone);
                     *  break;
                     */
                }//end switch
            } while (!mDone);

            DoQuit();
        }
コード例 #5
0
        static void Main(string[] args)
        {
            List <Fiddler.Session> oAllSessions = new List <Fiddler.Session>();

            #region AttachEventListeners
            //
            // It is important to understand that FiddlerCore calls event handlers on session-handling
            // background threads.  If you need to properly synchronize to the UI-thread (say, because
            // you're adding the sessions to a list view) you must call .Invoke on a delegate on the
            // window handle.
            //
            // If you are writing to a non-threadsafe data structure (e.g. List<t>) you must
            // use a Monitor or other mechanism to ensure safety.
            //

            // Simply echo notifications to the console.  Because Fiddler.CONFIG.QuietMode=true
            // by default, we must handle notifying the user ourselves.
            Fiddler.FiddlerApplication.OnNotification  += delegate(object sender, NotificationEventArgs oNEA) { Console.WriteLine("** NotifyUser: "******"** LogString: " + oLEA.LogString); };

            Fiddler.FiddlerApplication.BeforeRequest += delegate(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;
                Monitor.Enter(oAllSessions);
                oAllSessions.Add(oS);
                Monitor.Exit(oAllSessions);
            };

            /*
             *  // The following event allows you to examine every response buffer read by Fiddler. Note that this isn't useful for the vast majority of
             *  // applications because the raw buffer is nearly useless; it's not decompressed, it includes both headers and body bytes, etc.
             *  //
             *  // This event is only useful for a handful of applications which need access to a raw, unprocessed byte-stream
             *  Fiddler.FiddlerApplication.OnReadResponseBuffer += new EventHandler<RawReadEventArgs>(FiddlerApplication_OnReadResponseBuffer);
             */

            /*
             * Fiddler.FiddlerApplication.BeforeResponse += delegate(Fiddler.Session oS) {
             *  // Console.WriteLine("{0}:HTTP {1} for {2}", oS.id, oS.responseCode, oS.fullUrl);
             *
             *  // Uncomment the following two statements to decompress/unchunk the
             *  // HTTP response and subsequently modify any HTTP responses to replace
             *  // instances of the word "Microsoft" with "Bayden". You MUST also
             *  // set bBufferResponse = true inside the beforeREQUEST method above.
             *  //
             *  //oS.utilDecodeResponse(); oS.utilReplaceInResponse("Microsoft", "Bayden");
             * };*/

            Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
            {
                //Console.WriteLine("Finished session:\t" + oS.fullUrl);
                if (bUpdateTitle)
                {
                    Console.Title = ("Session list contains: " + oAllSessions.Count.ToString() + " sessions");
                }
            };

            // Tell the system console to handle CTRL+C by calling our method that
            // gracefully shuts down the FiddlerCore.
            //
            // Note, this doesn't handle the case where the user closes the window with the close button.
            // See http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx for info on that...
            //
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            #endregion AttachEventListeners

            string sSAZInfo = "NoSAZ";
#if SAZ_SUPPORT
            if (!FiddlerApplication.oTranscoders.ImportTranscoders(Assembly.GetExecutingAssembly().Location))
            {
                Console.WriteLine("This assembly was not compiled with a SAZ-exporter");
            }
            else
            {
                sSAZInfo = SAZFormat.GetZipLibraryInfo();
            }
#endif

            Console.WriteLine(String.Format("Starting {0} ({1})...", Fiddler.FiddlerApplication.GetVersionString(), sSAZInfo));

            // For the purposes of this demo, we'll forbid connections to HTTPS
            // sites that use invalid certificates
            Fiddler.CONFIG.IgnoreServerCertErrors = false;

            // but we can allow a specific (even invalid) certificate by implementing and assigning a callback...
            // FiddlerApplication.OverrideServerCertificateValidation += new OverrideCertificatePolicyHandler(FiddlerApplication_OverrideServerCertificateValidation);

            // Because we've chosen to decrypt HTTPS traffic, makecert.exe must
            // be present in the Application folder.

            FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

            Fiddler.FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.Default);
            FiddlerApplication.Log.LogString("Using Gateway: " + ((CONFIG.bForwardToGateway) ? "TRUE" : "FALSE"));

            Console.WriteLine("Hit CTRL+C to end session.");

            bool bDone = false;
            do
            {
                Console.WriteLine("\nEnter a command [C=Clear; L=List; G=Collect Garbage; W=write SAZ; R=read SAZ;\n\tS=Toggle Forgetful Streaming; T=Toggle Title Counter; Q=Quit]:");
                Console.Write(">");
                ConsoleKeyInfo cki = Console.ReadKey();
                Console.WriteLine();
                switch (cki.KeyChar)
                {
                case 'c':
                    Monitor.Enter(oAllSessions);
                    oAllSessions.Clear();
                    Monitor.Exit(oAllSessions);
                    WriteCommandResponse("Clear...");
                    FiddlerApplication.Log.LogString("Cleared session list.");
                    break;

                case 'l':
                    WriteSessionList(oAllSessions);
                    break;

                case 'g':
                    Console.WriteLine("Working Set:\t" + Environment.WorkingSet.ToString("n0"));
                    Console.WriteLine("Begin GC...");
                    GC.Collect();
                    Console.WriteLine("GC Done.\nWorking Set:\t" + Environment.WorkingSet.ToString("n0"));
                    break;

                case 'q':
                    bDone = true;
                    DoQuit();
                    break;

                case 'r':
#if SAZ_SUPPORT
                    ReadSessions(oAllSessions);
#else
                    WriteCommandResponse("This demo was compiled without SAZ_SUPPORT defined");
#endif
                    break;

                case 'w':
#if SAZ_SUPPORT
                    if (oAllSessions.Count > 0)
                    {
                        SaveSessionsToDesktop(oAllSessions);
                    }
                    else
                    {
                        WriteCommandResponse("No sessions have been captured");
                    }
#else
                    WriteCommandResponse("This demo was compiled without SAZ_SUPPORT defined");
#endif
                    break;

                case 't':
                    bUpdateTitle  = !bUpdateTitle;
                    Console.Title = (bUpdateTitle) ? "Title bar will update with request count..." :
                                    "Title bar update suppressed...";
                    break;

                // Forgetful streaming
                case 's':
                    bool bForgetful = !FiddlerApplication.Prefs.GetBoolPref("fiddler.network.streaming.ForgetStreamedData", false);
                    FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.ForgetStreamedData", bForgetful);
                    Console.WriteLine(bForgetful ? "FiddlerCore will immediately dump streaming response data." : "FiddlerCore will keep a copy of streamed response data.");
                    break;
                }
            } while (!bDone);
        }