Esempio n. 1
0
 private CONNECTTunnel(Session oSess, ClientPipe oFrom, ServerPipe oTo)
 {
     this._mySession = oSess;
     this.pipeTunnelClient = oFrom;
     this.pipeTunnelRemote = oTo;
     this._mySession.SetBitFlag(SessionFlags.IsBlindTunnel, true);
 }
Esempio n. 2
0
 private void _CleanupWebSocket()
 {
     this.bIsOpen         = false;
     this.arrRequestBytes = (this.arrResponseBytes = null);
     this.strmServerBytes = null;
     this.strmClientBytes = null;
     if (this.oCP != null)
     {
         this.oCP.End();
     }
     if (this.oSP != null)
     {
         this.oSP.End();
     }
     this.oCP = null;
     this.oSP = null;
     if (this._mySession != null)
     {
         if (this._mySession.oResponse != null && this._mySession.oResponse.headers != null)
         {
             this._mySession.oResponse["EndTime"]       = DateTime.Now.ToString("HH:mm:ss.fff");
             this._mySession.oResponse["ReceivedBytes"] = this._lngIngressByteCount.ToString();
             this._mySession.oResponse["SentBytes"]     = this._lngEgressByteCount.ToString();
         }
         this._mySession.Timers.ServerDoneResponse = (this._mySession.Timers.ClientBeginResponse = (this._mySession.Timers.ClientDoneResponse = DateTime.Now));
         this._mySession = null;
     }
 }
Esempio n. 3
0
        internal static void CreateTunnel(Session oSession, bool bStreamResponse)
        {
            if (oSession == null || oSession.oRequest == null || oSession.oRequest.headers == null || oSession.oRequest.pipeClient == null || oSession.oResponse == null)
            {
                return;
            }
            ClientPipe pipeClient = oSession.oRequest.pipeClient;

            if (pipeClient == null)
            {
                return;
            }
            if (bStreamResponse)
            {
                oSession.oRequest.pipeClient = null;
            }
            ServerPipe pipeServer = oSession.oResponse.pipeServer;

            if (pipeServer == null)
            {
                return;
            }
            if (bStreamResponse)
            {
                oSession.oResponse.pipeServer = null;
            }
            GenericTunnel genericTunnel = new GenericTunnel(oSession, pipeClient, pipeServer, bStreamResponse);

            oSession.__oTunnel = genericTunnel;
            new Thread(new ThreadStart(genericTunnel.RunTunnel))
            {
                IsBackground = true
            }.Start();
        }
Esempio n. 4
0
 private CONNECTTunnel(Session oSess, ClientPipe oFrom, ServerPipe oTo)
 {
     this._mySession       = oSess;
     this.pipeTunnelClient = oFrom;
     this.pipeTunnelRemote = oTo;
     this._mySession.SetBitFlag(SessionFlags.IsBlindTunnel, true);
 }
Esempio n. 5
0
        internal static void CreateTunnel(Session oSession)
        {
            if (oSession == null || oSession.oRequest == null || oSession.oRequest.headers == null || oSession.oRequest.pipeClient == null || oSession.oResponse == null)
            {
                return;
            }
            ClientPipe pipeClient = oSession.oRequest.pipeClient;

            if (pipeClient == null)
            {
                return;
            }
            oSession.oRequest.pipeClient = null;
            ServerPipe pipeServer = oSession.oResponse.pipeServer;

            if (pipeServer == null)
            {
                return;
            }
            oSession.oResponse.pipeServer = null;
            CONNECTTunnel cONNECTTunnel = new CONNECTTunnel(oSession, pipeClient, pipeServer);

            oSession.__oTunnel = cONNECTTunnel;
            new Thread(new ThreadStart(cONNECTTunnel.RunTunnel))
            {
                IsBackground = true
            }.Start();
        }
Esempio n. 6
0
 private GenericTunnel(Session oSess, ClientPipe oFrom, ServerPipe oTo, bool bStreamResponse)
 {
     this._mySession = oSess;
     this.pipeToClient = oFrom;
     this.pipeToRemote = oTo;
     this.bResponseStreamStarted = bStreamResponse;
     this._mySession.SetBitFlag(SessionFlags.IsBlindTunnel, true);
     Trace.WriteLine("[GenericTunnel] For session #" + this._mySession.id.ToString() + " created...");
 }
Esempio n. 7
0
        internal bool ResendRequest()
        {
            bool b = this.pipeServer != null;

            if (!this.ConnectToHost())
            {
                FiddlerApplication.DebugSpew("ConnectToHost returned null. Bailing...");
                this.m_session.SetBitFlag(SessionFlags.ServerPipeReused, b);
                return(false);
            }
            try
            {
                this.pipeServer.IncrementUse(this.m_session.id);
                this.m_session.Timers.ServerConnected = this.pipeServer.dtConnected;
                this._bWasForwarded = this.pipeServer.isConnectedToGateway;
                this.m_session.SetBitFlag(SessionFlags.ServerPipeReused, this.pipeServer.iUseCount > 1);
                this.m_session.SetBitFlag(SessionFlags.SentToGateway, this._bWasForwarded);
                if (!this._bWasForwarded && !this.m_session.isHTTPS)
                {
                    this.m_session.oRequest.headers.RenameHeaderItems("Proxy-Connection", "Connection");
                }
                if (!this.pipeServer.isAuthenticated)
                {
                    string str = this.m_session.oRequest.headers["Authorization"];
                    if ((str != null) && str.StartsWith("N"))
                    {
                        this.pipeServer.MarkAsAuthenticated(this.m_session.LocalProcessID);
                    }
                }
                this.m_session.Timers.FiddlerBeginRequest = DateTime.Now;
                if (this.m_session.oFlags.ContainsKey("request-trickle-delay"))
                {
                    int num = int.Parse(this.m_session.oFlags["request-trickle-delay"]);
                    this.pipeServer.TransmitDelay = num;
                }
                this.pipeServer.Send(this.m_session.oRequest.headers.ToByteArray(true, true, this._bWasForwarded && !this.m_session.isHTTPS));
                this.pipeServer.Send(this.m_session.requestBodyBytes);
            }
            catch (Exception exception)
            {
                if (this.bServerSocketReused && (this.m_session.state != SessionStates.Aborted))
                {
                    this.pipeServer = null;
                    return(this.ResendRequest());
                }
                FiddlerApplication.DebugSpew("ResendRequest() failed: " + exception.Message);
                this.m_session.oRequest.FailSession(0x1f8, "Fiddler - Send Failure", "ResendRequest() failed: " + exception.Message);
                return(false);
            }
            this.m_session.oFlags["x-EgressPort"] = this.pipeServer.LocalPort.ToString();
            if (this.m_session.oFlags.ContainsKey("log-drop-request-body"))
            {
                this.m_session.oFlags["x-RequestBodyLength"] = (this.m_session.requestBodyBytes != null) ? this.m_session.requestBodyBytes.Length.ToString() : "0";
                this.m_session.requestBodyBytes = new byte[0];
            }
            return(true);
        }
Esempio n. 8
0
 private GenericTunnel(Session oSess, ClientPipe oFrom, ServerPipe oTo, bool bStreamResponse)
 {
     this._mySession             = oSess;
     this.pipeToClient           = oFrom;
     this.pipeToRemote           = oTo;
     this.bResponseStreamStarted = bStreamResponse;
     this._mySession.SetBitFlag(SessionFlags.IsBlindTunnel, true);
     Trace.WriteLine("[GenericTunnel] For session #" + this._mySession.Int32_0.ToString() + " created...");
 }
Esempio n. 9
0
 private WebSocket(Session oSess, ClientPipe oFrom, ServerPipe oTo)
 {
     this.sName = "WebSocket #" + oSess.id.ToString();
     this._mySession = oSess;
     this.oCP = oFrom;
     this.oSP = oTo;
     this._mySession.SetBitFlag(SessionFlags.IsWebSocketTunnel, true);
     if (oSess.oFlags.ContainsKey("x-no-parse"))
     {
         this.bParseMessages = false;
     }
 }
Esempio n. 10
0
 private WebSocket(Session oSess, ClientPipe oFrom, ServerPipe oTo)
 {
     this.sName      = "WebSocket #" + oSess.Int32_0.ToString();
     this._mySession = oSess;
     this.oCP        = oFrom;
     this.oSP        = oTo;
     this._mySession.SetBitFlag(SessionFlags.IsWebSocketTunnel, true);
     if (oSess.oFlags.ContainsKey("x-no-parse"))
     {
         this.bParseMessages = false;
     }
 }
Esempio n. 11
0
 internal void PoolOrClosePipe(ServerPipe oPipe)
 {
     if (!CONFIG.bReuseServerSockets)
     {
         oPipe.End();
         return;
     }
     if (oPipe.ReusePolicy != PipeReusePolicy.NoReuse)
     {
         if (oPipe.ReusePolicy != PipeReusePolicy.MarriedToClientPipe)
         {
             if (this.lngLastPoolPurge > oPipe.dtConnected.Ticks)
             {
                 oPipe.End();
                 return;
             }
             if (oPipe.sPoolKey != null && oPipe.sPoolKey.Length >= 2)
             {
                 oPipe.ulLastPooled = Utilities.GetTickCount();
                 Dictionary <string, Stack <ServerPipe> > obj;
                 Monitor.Enter(obj = this.thePool);
                 Stack <ServerPipe> stack;
                 try
                 {
                     if (!this.thePool.TryGetValue(oPipe.sPoolKey, out stack))
                     {
                         stack = new Stack <ServerPipe>();
                         this.thePool.Add(oPipe.sPoolKey, stack);
                     }
                 }
                 finally
                 {
                     Monitor.Exit(obj);
                 }
                 Stack <ServerPipe> obj2;
                 Monitor.Enter(obj2 = stack);
                 try
                 {
                     stack.Push(oPipe);
                 }
                 finally
                 {
                     Monitor.Exit(obj2);
                 }
                 return;
             }
             oPipe.End();
             return;
         }
     }
     oPipe.End();
 }
Esempio n. 12
0
        internal ServerPipe TakePipe(string sPoolKey, int iPID, int HackiForSession)
        {
            if (!CONFIG.bReuseServerSockets)
            {
                return(null);
            }
            Dictionary <string, Stack <ServerPipe> > obj;

            Monitor.Enter(obj = this.thePool);
            Stack <ServerPipe> stack;

            try
            {
                if ((iPID == 0 || !this.thePool.TryGetValue(string.Format("PID{0}*{1}", iPID, sPoolKey), out stack) || stack.Count < 1) && (!this.thePool.TryGetValue(sPoolKey, out stack) || stack.Count < 1))
                {
                    ServerPipe result = null;
                    return(result);
                }
            }
            finally
            {
                Monitor.Exit(obj);
            }
            Stack <ServerPipe> obj2;

            Monitor.Enter(obj2 = stack);
            ServerPipe result2;

            try
            {
                if (stack.Count == 0)
                {
                    ServerPipe result = null;
                    return(result);
                }
                result2 = stack.Pop();
            }
            catch (Exception eX)
            {
                FiddlerApplication.ReportException(eX);
                ServerPipe result = null;
                return(result);
            }
            finally
            {
                Monitor.Exit(obj2);
            }
            return(result2);
        }
Esempio n. 13
0
 internal void Initialize(bool bAlloc)
 {
     if (bAlloc)
     {
         this.m_responseData = new MemoryStream(0x4000);
     }
     else
     {
         this.m_responseData = null;
     }
     this._lngLeakedOffset        = this._iBodySeekProgress = this.iEntityBodyOffset = 0;
     this._lngLastChunkInfoOffset = -1L;
     this.m_inHeaders             = null;
     this._bLeakedHeaders         = false;
     this.pipeServer     = null;
     this._bWasForwarded = false;
     this.m_session.SetBitFlag(SessionFlags.ServerPipeReused, false);
 }
Esempio n. 14
0
        internal string GetServerCertChain()
        {
            if (this._ServerCertChain != null)
            {
                return(this._ServerCertChain);
            }
            if (this._httpsStream == null)
            {
                return(string.Empty);
            }
            string result;

            try
            {
                X509Certificate2 x509Certificate = new X509Certificate2(this._httpsStream.RemoteCertificate);
                if (x509Certificate == null)
                {
                    result = string.Empty;
                }
                else
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    X509Chain     x509Chain     = new X509Chain();
                    x509Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                    x509Chain.Build(x509Certificate);
                    for (int i = x509Chain.ChainElements.Count - 1; i >= 1; i--)
                    {
                        stringBuilder.Append(ServerPipe.SummarizeCert(x509Chain.ChainElements[i].Certificate));
                        stringBuilder.Append(" > ");
                    }
                    if (x509Chain.ChainElements.Count > 0)
                    {
                        stringBuilder.AppendFormat("{0} [{1}]", ServerPipe.SummarizeCert(x509Chain.ChainElements[0].Certificate), x509Chain.ChainElements[0].Certificate.SerialNumber);
                    }
                    this._ServerCertChain = stringBuilder.ToString();
                    result = stringBuilder.ToString();
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return(result);
        }
Esempio n. 15
0
 private void WaitForCompletion()
 {
     this.oKeepTunnelAlive = new AutoResetEvent(false);
     this.oKeepTunnelAlive.WaitOne();
     this.oKeepTunnelAlive.Close();
     this.oKeepTunnelAlive = null;
     this.bIsOpen          = false;
     this.arrRequestBytes  = (this.arrResponseBytes = null);
     this.pipeTunnelClient = null;
     this.pipeTunnelRemote = null;
     this.socketClient     = (this.socketRemote = null);
     if (this._mySession.oResponse != null && this._mySession.oResponse.headers != null)
     {
         this._mySession.oResponse.headers["EndTime"]             = DateTime.Now.ToString("HH:mm:ss.fff");
         this._mySession.oResponse.headers["ClientToServerBytes"] = this._lngEgressByteCount.ToString();
         this._mySession.oResponse.headers["ServerToClientBytes"] = this._lngIngressByteCount.ToString();
     }
     this._mySession.Timers.ServerDoneResponse = (this._mySession.Timers.ClientBeginResponse = (this._mySession.Timers.ClientDoneResponse = DateTime.Now));
     this._mySession = null;
 }
Esempio n. 16
0
 internal void EnqueuePipe(ServerPipe oPipe)
 {
     if ((CONFIG.bReuseServerSockets && ((oPipe.sPoolKey != null) && (oPipe.sPoolKey.Length >= 2))) && ((oPipe.ReusePolicy != PipeReusePolicy.MarriedToClientPipe) && (oPipe.ReusePolicy != PipeReusePolicy.NoReuse)))
     {
         Queue <ServerPipe> queue;
         lock (this.thePool)
         {
             if (!this.thePool.TryGetValue(oPipe.sPoolKey, out queue))
             {
                 queue = new Queue <ServerPipe>();
                 this.thePool.Add(oPipe.sPoolKey, queue);
             }
         }
         oPipe.iLastPooled = Environment.TickCount;
         lock (queue)
         {
             queue.Enqueue(oPipe);
         }
     }
 }
Esempio n. 17
0
 internal static void CreateTunnel(Session oSession)
 {
     if (oSession == null || oSession.oRequest == null || oSession.oRequest.headers == null || oSession.oRequest.pipeClient == null)
     {
         return;
     }
     if (oSession.oResponse != null && oSession.oResponse.pipeServer != null)
     {
         ClientPipe pipeClient = oSession.oRequest.pipeClient;
         oSession.oRequest.pipeClient = null;
         ServerPipe pipeServer = oSession.oResponse.pipeServer;
         oSession.oResponse.pipeServer = null;
         WebSocket webSocket = new WebSocket(oSession, pipeClient, pipeServer);
         oSession.__oTunnel = webSocket;
         new Thread(new ThreadStart(webSocket.RunTunnel))
         {
             IsBackground = true
         }.Start();
         return;
     }
 }
Esempio n. 18
0
        private X509Certificate AttachClientCertificate(Session oS, object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
        {
            if (localCertificates.Count > 0)
            {
                this.MarkAsAuthenticated(oS.LocalProcessID);
                oS.oFlags["x-client-cert"] = localCertificates[0].Subject + " Serial#" + localCertificates[0].GetSerialNumberString();
                return(localCertificates[0]);
            }
            if (remoteCertificate == null && acceptableIssuers.Length < 1)
            {
                return(null);
            }
            if (FiddlerApplication.ClientCertificateProvider != null)
            {
                X509Certificate x509Certificate = FiddlerApplication.ClientCertificateProvider(oS, targetHost, localCertificates, remoteCertificate, acceptableIssuers);
                if (x509Certificate != null && CONFIG.bDebugSpew)
                {
                    Trace.WriteLine(string.Format("Session #{0} Attaching client certificate '{1}' when connecting to host '{2}'", oS.Int32_0, x509Certificate.Subject, targetHost));
                }
                return(x509Certificate);
            }
            X509Certificate x509Certificate2 = ServerPipe._GetDefaultCertificate();

            if (x509Certificate2 != null)
            {
                this.MarkAsAuthenticated(oS.LocalProcessID);
                oS.oFlags["x-client-cert"] = x509Certificate2.Subject + " Serial#" + x509Certificate2.GetSerialNumberString();
                return(x509Certificate2);
            }
            if (CONFIG.bShowDefaultClientCertificateNeededPrompt && FiddlerApplication.Prefs.GetBoolPref("fiddler.network.https.clientcertificate.ephemeral.prompt-for-missing", true))
            {
                FiddlerApplication.Prefs.SetBoolPref("fiddler.network.https.clientcertificate.ephemeral.prompt-for-missing", false);
                FiddlerApplication.DoNotifyUser("The server [" + targetHost + "] requests a client certificate.\nPlease save a client certificate using the filename:\n\n" + CONFIG.GetPath("DefaultClientCertificate"), "Client Certificate Requested");
            }
            FiddlerApplication.Log.LogFormat("The server [{0}] requested a client certificate, but no client certificate was available.", new object[]
            {
                targetHost
            });
            return(null);
        }
Esempio n. 19
0
 internal void _detachServerPipe()
 {
     if (this.pipeServer != null)
     {
         if (((this.pipeServer.ReusePolicy != PipeReusePolicy.NoReuse) && (this.pipeServer.ReusePolicy != PipeReusePolicy.MarriedToClientPipe)) && (this.pipeServer.isClientCertAttached && !this.pipeServer.isAuthenticated))
         {
             this.pipeServer.MarkAsAuthenticated(this.m_session.LocalProcessID);
         }
         if ((this.pipeServer.ReusePolicy == PipeReusePolicy.NoReuse) || (this.pipeServer.ReusePolicy == PipeReusePolicy.MarriedToClientPipe))
         {
             if (this.pipeServer.Connected)
             {
                 this.pipeServer.End();
             }
         }
         else
         {
             Proxy.htServerPipePool.EnqueuePipe(this.pipeServer);
         }
         this.pipeServer = null;
     }
 }
Esempio n. 20
0
 private void WaitForCompletion()
 {
     this.oKeepTunnelAlive = new AutoResetEvent(false);
     Trace.WriteLine("[GenericTunnel] Blocking thread...");
     this.oKeepTunnelAlive.WaitOne();
     Trace.WriteLine("[GenericTunnel] Unblocking thread...");
     this.oKeepTunnelAlive.Close();
     this.oKeepTunnelAlive = null;
     this.bIsOpen          = false;
     this.arrRequestBytes  = (this.arrResponseBytes = null);
     this.pipeToClient     = null;
     this.pipeToRemote     = null;
     Trace.WriteLine("[GenericTunnel] Thread for session #" + this._mySession.Int32_0.ToString() + " has died...");
     if (this._mySession.oResponse != null && this._mySession.oResponse.headers != null)
     {
         this._mySession.oResponse.headers["EndTime"]             = DateTime.Now.ToString("HH:mm:ss.fff");
         this._mySession.oResponse.headers["ClientToServerBytes"] = this._lngEgressByteCount.ToString();
         this._mySession.oResponse.headers["ServerToClientBytes"] = this._lngIngressByteCount.ToString();
     }
     this._mySession.Timers.ServerDoneResponse = (this._mySession.Timers.ClientBeginResponse = (this._mySession.Timers.ClientDoneResponse = DateTime.Now));
     this._mySession.state = SessionStates.Done;
     this._mySession       = null;
 }
Esempio n. 21
0
        internal bool SecureExistingConnection(Session oS, string sCertCN, string sClientCertificateFilename, ref int iHandshakeTime)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            bool      result;

            try
            {
                this.sPoolKey = this.sPoolKey.Replace("->http/", "->https/");
                if (this.sPoolKey.EndsWith("->*"))
                {
                    this.sPoolKey = this.sPoolKey.Replace("->*", string.Format("->https/{0}:{1}", oS.hostname, oS.port));
                }
                X509CertificateCollection certificateCollectionFromFile = ServerPipe.GetCertificateCollectionFromFile(sClientCertificateFilename);
                this._httpsStream = new SslStream(new NetworkStream(this._baseSocket, false), false, (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => ServerPipe.ConfirmServerCertificate(oS, sCertCN, certificate, chain, sslPolicyErrors), (object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) => this.AttachClientCertificate(oS, sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers));
                SslProtocols enabledSslProtocols = CONFIG.oAcceptedServerHTTPSProtocols;
                if (oS.oFlags.ContainsKey("x-OverrideSslProtocols"))
                {
                    enabledSslProtocols = Utilities.ParseSSLProtocolString(oS.oFlags["x-OverrideSslProtocols"]);
                }
                this._httpsStream.AuthenticateAsClient(sCertCN, certificateCollectionFromFile, enabledSslProtocols, FiddlerApplication.Prefs.GetBoolPref("fiddler.network.https.checkcertificaterevocation", false));
                iHandshakeTime = (int)stopwatch.ElapsedMilliseconds;
                return(true);
            }
            catch (Exception ex)
            {
                iHandshakeTime = (int)stopwatch.ElapsedMilliseconds;
                FiddlerApplication.DebugSpew(ex.StackTrace + "\n" + ex.Message);
                string text = string.Format("fiddler.network.https> Failed to secure existing connection for {0}. {1}{2}", sCertCN, ex.Message, (ex.InnerException != null) ? (" InnerException: " + ex.InnerException.ToString()) : ".");
                if (oS.responseBodyBytes == null || oS.responseBodyBytes.Length == 0)
                {
                    oS.responseBodyBytes = Encoding.UTF8.GetBytes(text);
                }
                FiddlerApplication.Log.LogString(text);
                result = false;
            }
            return(result);
        }
Esempio n. 22
0
 internal void PoolOrClosePipe(ServerPipe oPipe)
 {
     if (!CONFIG.bReuseServerSockets)
     {
         oPipe.End();
     }
     else if ((oPipe.ReusePolicy == PipeReusePolicy.NoReuse) || (oPipe.ReusePolicy == PipeReusePolicy.MarriedToClientPipe))
     {
         oPipe.End();
     }
     else if (this.lngLastPoolPurge > oPipe.dtConnected.Ticks)
     {
         oPipe.End();
     }
     else if ((oPipe.sPoolKey == null) || (oPipe.sPoolKey.Length < 2))
     {
         oPipe.End();
     }
     else
     {
         Stack<ServerPipe> stack;
         oPipe.ulLastPooled = Utilities.GetTickCount();
         lock (this.thePool)
         {
             if (!this.thePool.TryGetValue(oPipe.sPoolKey, out stack))
             {
                 stack = new Stack<ServerPipe>();
                 this.thePool.Add(oPipe.sPoolKey, stack);
             }
         }
         lock (stack)
         {
             stack.Push(oPipe);
         }
     }
 }
Esempio n. 23
0
 internal void Initialize(bool bAllocatePipeReadBuffer)
 {
     if (bAllocatePipeReadBuffer)
     {
         this.m_responseData = new PipeReadBuffer(false);
     }
     else
     {
         this.m_responseData = null;
     }
     this._lngLeakedOffset = this._iBodySeekProgress = this.iEntityBodyOffset = 0;
     this._lngLastChunkInfoOffset = -1L;
     this.m_inHeaders = null;
     this._bLeakedHeaders = false;
     this.pipeServer = null;
     this._bWasForwarded = false;
     this.m_session.SetBitFlag(SessionFlags.ServerPipeReused, false);
 }
Esempio n. 24
0
 internal void _detachServerPipe()
 {
     if (this.pipeServer != null)
     {
         if (((this.pipeServer.ReusePolicy != PipeReusePolicy.NoReuse) && (this.pipeServer.ReusePolicy != PipeReusePolicy.MarriedToClientPipe)) && (this.pipeServer.isClientCertAttached && !this.pipeServer.isAuthenticated))
         {
             this.pipeServer.MarkAsAuthenticated(this.m_session.LocalProcessID);
         }
         if ((this.pipeServer.ReusePolicy == PipeReusePolicy.NoReuse) || (this.pipeServer.ReusePolicy == PipeReusePolicy.MarriedToClientPipe))
         {
             if (this.pipeServer.Connected)
             {
                 this.pipeServer.End();
             }
         }
         else
         {
             Proxy.htServerPipePool.EnqueuePipe(this.pipeServer);
         }
         this.pipeServer = null;
     }
 }
Esempio n. 25
0
 private bool ConnectToHost()
 {
     IPEndPoint[] pointArray = null;
     string str3;
     string str4;
     IPEndPoint[] pointArray2;
     bool flag3;
     string sHostAndPort = this.m_session.oFlags["x-overrideHost"];
     if (sHostAndPort == null)
     {
         if (this.m_session.HTTPMethodIs("CONNECT"))
         {
             sHostAndPort = this.m_session.PathAndQuery;
         }
         else
         {
             sHostAndPort = this.m_session.host;
         }
     }
     bool flag = false;
     if (this.m_session.oFlags["x-overrideGateway"] != null)
     {
         if (string.Equals("DIRECT", this.m_session.oFlags["x-overrideGateway"], StringComparison.OrdinalIgnoreCase))
         {
             this.m_session.bypassGateway = true;
         }
         else
         {
             string sAllHostAndPorts = this.m_session.oFlags["x-overrideGateway"];
             if (sAllHostAndPorts.StartsWith("socks="))
             {
                 flag = true;
                 sAllHostAndPorts = sAllHostAndPorts.Substring(6);
             }
             pointArray = Utilities.IPEndPointListFromHostPortString(sAllHostAndPorts);
         }
     }
     else if (!this.m_session.bypassGateway)
     {
         int tickCount = Environment.TickCount;
         IPEndPoint point = FiddlerApplication.oProxy.FindGatewayForOrigin(this.m_session.oRequest.headers.UriScheme, sHostAndPort);
         if (point != null)
         {
             pointArray = new IPEndPoint[] { point };
         }
         this.m_session.Timers.GatewayDeterminationTime = Environment.TickCount - tickCount;
     }
     if (pointArray != null)
     {
         this._bWasForwarded = true;
     }
     else if (this.m_session.isFTP)
     {
         this.m_session.oRequest.FailSession(0x1f6, "Fiddler - FTP Connection Failed", "[Fiddler] Fiddler does not support proxying FTP traffic without an upstream HTTP->FTP proxy.");
         return false;
     }
     int iPort = this.m_session.isHTTPS ? 0x1bb : (this.m_session.isFTP ? 0x15 : 80);
     Utilities.CrackHostAndPort(sHostAndPort, out str3, ref iPort);
     if (pointArray != null)
     {
         if (this.m_session.isHTTPS)
         {
             str4 = "GATEWAY:HTTPS:" + str3 + ":" + iPort.ToString();
         }
         else
         {
             str4 = "GW:" + pointArray[0].ToString();
         }
     }
     else
     {
         str4 = (this.m_session.isHTTPS ? "HTTPS:" : "") + str3 + ":" + iPort.ToString();
     }
     if (((this.pipeServer != null) && !this.m_session.oFlags.ContainsKey("X-ServerPipe-Marriage-Trumps-All")) && !this.SIDsMatch(this.m_session.LocalProcessID, str4, this.pipeServer.sPoolKey))
     {
         FiddlerApplication.Log.LogFormat("Detaching server pipe. Had: {0} but needs: {1}", new object[] { this.pipeServer.sPoolKey, str4 });
         this.m_session.oFlags["X-Divorced-ServerPipe"] = string.Format("Had: {0} but needs: {1}", this.pipeServer.sPoolKey, str4);
         this._detachServerPipe();
     }
     if ((this.pipeServer == null) && !this.m_session.oFlags.ContainsKey("X-Bypass-ServerPipe-Reuse-Pool"))
     {
         this.pipeServer = Proxy.htServerPipePool.DequeuePipe(str4, this.m_session.LocalProcessID, this.m_session.id);
     }
     if (this.pipeServer != null)
     {
         StringDictionary dictionary;
         this.m_session.Timers.ServerConnected = this.pipeServer.dtConnected;
         (dictionary = this.m_session.oFlags)["x-serversocket"] = dictionary["x-serversocket"] + "REUSE " + this.pipeServer._sPipeName;
         if ((this.pipeServer.Address != null) && !this.pipeServer.isConnectedToGateway)
         {
             this.m_session.m_hostIP = this.pipeServer.Address.ToString();
             this.m_session.oFlags["x-hostIP"] = this.m_session.m_hostIP;
         }
         if (CONFIG.bDebugSpew)
         {
             FiddlerApplication.DebugSpew(string.Format("Session #{0} ({1} {2}): Reusing {3}\r\n", new object[] { this.m_session.id, this.m_session.oRequest.headers.HTTPMethod, this.m_session.fullUrl, this.pipeServer.ToString() }));
         }
         return true;
     }
     if (pointArray == null)
     {
         if ((iPort < 0) || (iPort > 0xffff))
         {
             this.m_session.oRequest.FailSession(0x1f6, "Fiddler - Invalid Request", "[Fiddler] HTTP Request specified an invalid port number.");
             return false;
         }
         try
         {
             IPAddress[] addressArray = DNSResolver.GetIPAddressList(str3, true, this.m_session.Timers);
             List<IPEndPoint> list = new List<IPEndPoint>();
             foreach (IPAddress address in addressArray)
             {
                 list.Add(new IPEndPoint(address, iPort));
             }
             pointArray2 = list.ToArray();
             goto Label_04DA;
         }
         catch (Exception exception)
         {
             this.m_session.oRequest.FailSession(0x1f6, "Fiddler - DNS Lookup Failed", string.Format("[Fiddler] DNS Lookup for \"{0}\" failed. {1}", Utilities.HtmlEncode(str3), Utilities.DescribeException(exception)));
             return false;
         }
     }
     pointArray2 = pointArray;
     Label_04DA:
     try
     {
         Socket oGWSocket = CreateConnectedSocket(pointArray2, this.m_session);
         if (flag)
         {
             this._bWasForwarded = false;
             FiddlerApplication.Log.LogFormat("Creating SOCKS connection to {0}.", new object[] { this.m_session.hostname });
             bool flag2 = false;
             byte[] buffer = BuildSOCKS4ConnectHandshakeForTarget(str3, iPort);
             oGWSocket.Send(buffer);
             byte[] buffer2 = new byte[0x40];
             int num3 = oGWSocket.Receive(buffer2);
             if (((num3 > 1) && (buffer2[0] == 0)) && (buffer2[1] == 90))
             {
                 this.m_session.SetBitFlag(SessionFlags.SentToSOCKSGateway, true);
                 if (num3 > 7)
                 {
                     string str5 = string.Format("{0}.{1}.{2}.{3}", new object[] { buffer2[4], buffer2[5], buffer2[6], buffer2[7] });
                     this.m_session.m_hostIP = str5;
                     this.m_session.oFlags["x-hostIP"] = str5;
                 }
                 flag2 = true;
             }
             if (!flag2)
             {
                 oGWSocket.Close();
                 oGWSocket = null;
                 throw new InvalidDataException("SOCKS server returned failure");
             }
         }
         if (this.m_session.isHTTPS && this._bWasForwarded)
         {
             if (!SendHTTPCONNECTToGateway(oGWSocket, str3, iPort, this.m_session.oRequest["User-Agent"]))
             {
                 throw new Exception("Upstream Gateway refused requested CONNECT.");
             }
             this.m_session.oFlags["x-CreatedTunnel"] = "Fiddler-Created-A-CONNECT-Tunnel";
         }
         string sPoolingKey = string.Empty;
         if (this.m_session.isHTTPS)
         {
             sPoolingKey = "HTTPS:" + str3 + ":" + iPort.ToString();
         }
         else if (this._bWasForwarded)
         {
             sPoolingKey = "GW:" + pointArray[0].ToString();
         }
         else
         {
             sPoolingKey = str3 + ":" + iPort.ToString();
         }
         this.pipeServer = new ServerPipe(oGWSocket, "ServerPipe#" + this.m_session.id.ToString(), this._bWasForwarded, sPoolingKey);
         if (flag)
         {
             this.pipeServer.isConnectedViaSOCKS = true;
         }
         if (this.m_session.isHTTPS && !this.pipeServer.SecureExistingConnection(this.m_session, str3, this.m_session.oFlags["https-Client-Certificate"], sPoolingKey, ref this.m_session.Timers.HTTPSHandshakeTime))
         {
             throw new Exception("Upstream Gateway refused requested CONNECT.");
         }
         flag3 = true;
     }
     catch (Exception exception2)
     {
         if (this._bWasForwarded)
         {
             this.m_session.oRequest.FailSession(0x1f6, "Fiddler - Gateway Connection Failed", "[Fiddler] Connection to Gateway failed.<BR>Exception Text: " + Utilities.DescribeException(exception2));
         }
         else
         {
             this.m_session.oRequest.FailSession(0x1f6, "Fiddler - Connection Failed", "[Fiddler] Connection to " + Utilities.HtmlEncode(str3) + " failed.<BR>Exception Text: " + Utilities.DescribeException(exception2));
         }
         flag3 = false;
     }
     return flag3;
 }
Esempio n. 26
0
 private void _CleanupWebSocket()
 {
     this.bIsOpen = false;
     this.arrRequestBytes = (byte[]) (this.arrResponseBytes = null);
     this.strmServerBytes = null;
     this.strmClientBytes = null;
     if (this.oCP != null)
     {
         this.oCP.End();
     }
     if (this.oSP != null)
     {
         this.oSP.End();
     }
     this.oCP = null;
     this.oSP = null;
     if (this._mySession != null)
     {
         if ((this._mySession.oResponse != null) && (this._mySession.oResponse.headers != null))
         {
             this._mySession.oResponse["EndTime"] = DateTime.Now.ToString("HH:mm:ss.fff");
             this._mySession.oResponse["ReceivedBytes"] = this._lngIngressByteCount.ToString();
             this._mySession.oResponse["SentBytes"] = this._lngEgressByteCount.ToString();
         }
         this._mySession.Timers.ServerDoneResponse = this._mySession.Timers.ClientBeginResponse = this._mySession.Timers.ClientDoneResponse = DateTime.Now;
         this._mySession = null;
     }
 }
Esempio n. 27
0
        internal void ScavengeCache()
        {
            if (this.thePool.Count < 1)
            {
                return;
            }
            List <ServerPipe> list = new List <ServerPipe>();
            Dictionary <string, Stack <ServerPipe> > obj;

            Monitor.Enter(obj = this.thePool);
            try
            {
                List <string> list2 = new List <string>();
                ulong         num   = Utilities.GetTickCount() - (ulong)PipePool.MSEC_PIPE_POOLED_LIFETIME;
                foreach (KeyValuePair <string, Stack <ServerPipe> > current in this.thePool)
                {
                    Stack <ServerPipe> value = current.Value;
                    Stack <ServerPipe> obj2;
                    Monitor.Enter(obj2 = value);
                    try
                    {
                        if (value.Count > 0)
                        {
                            ServerPipe serverPipe = value.Peek();
                            if (serverPipe.ulLastPooled < num)
                            {
                                list.AddRange(value);
                                value.Clear();
                            }
                            else
                            {
                                if (value.Count > 1)
                                {
                                    ServerPipe[] array = value.ToArray();
                                    if (array[array.Length - 1].ulLastPooled < num)
                                    {
                                        value.Clear();
                                        for (int i = array.Length - 1; i >= 0; i--)
                                        {
                                            if (array[i].ulLastPooled < num)
                                            {
                                                list.Add(array[i]);
                                            }
                                            else
                                            {
                                                value.Push(array[i]);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (value.Count == 0)
                        {
                            list2.Add(current.Key);
                        }
                    }
                    finally
                    {
                        Monitor.Exit(obj2);
                    }
                }
                foreach (string current2 in list2)
                {
                    this.thePool.Remove(current2);
                }
            }
            finally
            {
                Monitor.Exit(obj);
            }
            foreach (BasePipe current3 in list)
            {
                current3.End();
            }
        }
Esempio n. 28
0
        private bool ConnectToHost()
        {
            IPEndPoint point = null;
            string     str2;
            string     str3;

            IPAddress[] addressArray;
            string      sHostAndPort = this.m_session.oFlags["x-overrideHost"];

            if (sHostAndPort == null)
            {
                sHostAndPort = this.m_session.host;
            }
            if (this.m_session.oFlags["x-overrideGateway"] != null)
            {
                if (string.Equals("DIRECT", this.m_session.oFlags["x-overrideGateway"], StringComparison.OrdinalIgnoreCase))
                {
                    this.m_session.bypassGateway = true;
                }
                else
                {
                    point = Utilities.IPEndPointFromHostPortString(this.m_session.oFlags["x-overrideGateway"]);
                }
            }
            else if (!this.m_session.bypassGateway)
            {
                int tickCount = Environment.TickCount;
                point = FiddlerApplication.oProxy.FindGatewayForOrigin(this.m_session.oRequest.headers.UriScheme, sHostAndPort);
                this.m_session.Timers.GatewayDeterminationTime = Environment.TickCount - tickCount;
            }
            if (point != null)
            {
                this._bWasForwarded = true;
            }
            else if (this.m_session.isFTP)
            {
                this.m_session.oRequest.FailSession(0x1f6, "Fiddler - FTP Connection Failed", "[Fiddler] Fiddler does not support proxying FTP traffic without an upstream HTTP->FTP proxy.");
                return(false);
            }
            int iPort = this.m_session.isHTTPS ? 0x1bb : (this.m_session.isFTP ? 0x15 : 80);

            Utilities.CrackHostAndPort(sHostAndPort, out str2, ref iPort);
            if (point != null)
            {
                if (this.m_session.isHTTPS)
                {
                    str3 = "GATEWAY:HTTPS:" + str2 + ":" + iPort.ToString();
                }
                else
                {
                    str3 = "GW:" + point.ToString();
                }
            }
            else
            {
                str3 = (this.m_session.isHTTPS ? "HTTPS:" : "") + str2 + ":" + iPort.ToString();
            }
            if (((this.pipeServer != null) && !this.m_session.oFlags.ContainsKey("X-ServerPipe-Marriage-Trumps-All")) && !this.SIDsMatch(this.m_session.LocalProcessID, str3, this.pipeServer.sPoolKey))
            {
                this._detachServerPipe();
            }
            if ((this.pipeServer == null) && !this.m_session.oFlags.ContainsKey("X-Bypass-ServerPipe-Reuse-Pool"))
            {
                this.pipeServer = Proxy.htServerPipePool.DequeuePipe(str3, this.m_session.LocalProcessID, this.m_session.id);
            }
            if (this.pipeServer != null)
            {
                StringDictionary dictionary;
                this.m_session.Timers.ServerConnected = this.pipeServer.dtConnected;
                (dictionary = this.m_session.oFlags)["x-serversocket"] = dictionary["x-serversocket"] + "REUSE " + this.pipeServer._sPipeName;
                if ((this.pipeServer.Address != null) && !this.pipeServer.isConnectedToGateway)
                {
                    this.m_session.m_hostIP           = this.pipeServer.Address.ToString();
                    this.m_session.oFlags["x-hostIP"] = this.m_session.m_hostIP;
                }
                return(true);
            }
            int port = iPort;

            if (point != null)
            {
                addressArray = new IPAddress[] { point.Address };
                port         = point.Port;
            }
            else
            {
                try
                {
                    addressArray = DNSResolver.GetIPAddressList(str2, true, this.m_session.Timers);
                }
                catch (Exception exception)
                {
                    this.m_session.oRequest.FailSession(0x1f6, "Fiddler - DNS Lookup Failed", "Fiddler: DNS Lookup for " + Utilities.HtmlEncode(str2) + " failed. " + exception.Message);
                    return(false);
                }
                if ((port < 0) || (port > 0xffff))
                {
                    this.m_session.oRequest.FailSession(0x1f6, "Invalid Request", "HTTP Request specified an invalid port number.");
                    return(false);
                }
            }
            try
            {
                this.pipeServer = new ServerPipe("ServerPipe#" + this.m_session.id.ToString(), this._bWasForwarded);
                Socket oSocket = CreateConnectedSocket(addressArray, port, this.m_session);
                if (this._bWasForwarded)
                {
                    if (!this.m_session.isHTTPS)
                    {
                        this.pipeServer.WrapSocketInPipe(this.m_session, oSocket, false, false, str2, this.m_session.oFlags["https-Client-Certificate"], "GW:" + point.ToString(), ref this.m_session.Timers.HTTPSHandshakeTime);
                    }
                    else
                    {
                        this.m_session.oFlags["x-CreatedTunnel"] = "Fiddler-Created-A-CONNECT-Tunnel";
                        this.pipeServer.WrapSocketInPipe(this.m_session, oSocket, true, true, str2, this.m_session.oFlags["https-Client-Certificate"], "HTTPS:" + str2 + ":" + iPort.ToString(), ref this.m_session.Timers.HTTPSHandshakeTime);
                    }
                }
                else
                {
                    this.pipeServer.WrapSocketInPipe(this.m_session, oSocket, this.m_session.isHTTPS, false, str2, this.m_session.oFlags["https-Client-Certificate"], (this.m_session.isHTTPS ? "HTTPS:" : "") + str2 + ":" + iPort.ToString(), ref this.m_session.Timers.HTTPSHandshakeTime);
                }
                return(true);
            }
            catch (Exception exception2)
            {
                if (this._bWasForwarded)
                {
                    this.m_session.oRequest.FailSession(0x1f6, "Fiddler - Gateway Connection Failed", "[Fiddler] Connection to Gateway failed.<BR>Exception Text: " + exception2.Message);
                }
                else
                {
                    this.m_session.oRequest.FailSession(0x1f6, "Fiddler - Connection Failed", "[Fiddler] Connection to " + Utilities.HtmlEncode(str2) + " failed.<BR>Exception Text: " + exception2.Message);
                }
                return(false);
            }
        }
Esempio n. 29
0
        private bool ConnectToHost()
        {
            string str4;
            string str5;
            IPEndPoint[] pointArray2 = null;
            bool flag3;
            string pathAndQuery = this.m_session.oFlags["x-overrideHostName"];
            if (pathAndQuery != null)
            {
                this.m_session.oFlags["x-overrideHost"] = string.Format("{0}:{1}", pathAndQuery, this.m_session.port);
            }
            pathAndQuery = this.m_session.oFlags["x-overrideHost"];
            if (pathAndQuery == null)
            {
                if (this.m_session.HTTPMethodIs("CONNECT"))
                {
                    pathAndQuery = this.m_session.PathAndQuery;
                }
                else
                {
                    pathAndQuery = this.m_session.host;
                }
            }
            bool flag = false;
            IPEndPoint[] pointArray = null;
            if (this.m_session.oFlags["x-overrideGateway"] != null)
            {
                if (!"DIRECT".OICEquals(this.m_session.oFlags["x-overrideGateway"]))
                {
                    string inStr = this.m_session.oFlags["x-overrideGateway"];
                    if (inStr.OICStartsWith("socks="))
                    {
                        flag = true;
                        inStr = inStr.Substring(6);
                    }
                    pointArray = Utilities.IPEndPointListFromHostPortString(inStr);
                    if (flag && (pointArray == null))
                    {
                        this.m_session.oRequest.FailSession(0x1f6, "Fiddler - SOCKS Proxy DNS Lookup Failed", string.Format("[Fiddler] SOCKS DNS Lookup for \"{0}\" failed. {1}", Utilities.HtmlEncode(inStr), NetworkInterface.GetIsNetworkAvailable() ? string.Empty : "The system reports that no network connection is available. \n"));
                        return false;
                    }
                }
                else
                {
                    this.m_session.bypassGateway = true;
                }
            }
            else if (!this.m_session.bypassGateway)
            {
                int tickCount = Environment.TickCount;
                string uriScheme = this.m_session.oRequest.headers.UriScheme;
                if ((uriScheme == "http") && this.m_session.HTTPMethodIs("CONNECT"))
                {
                    uriScheme = "https";
                }
                IPEndPoint point = FiddlerApplication.oProxy.FindGatewayForOrigin(uriScheme, pathAndQuery);
                if (point != null)
                {
                    pointArray = new IPEndPoint[] { point };
                }
                this.m_session.Timers.GatewayDeterminationTime = Environment.TickCount - tickCount;
            }
            if (pointArray != null)
            {
                this._bWasForwarded = true;
            }
            else if (this.m_session.isFTP)
            {
                return true;
            }
            int iPort = this.m_session.isHTTPS ? 0x1bb : (this.m_session.isFTP ? 0x15 : 80);
            Utilities.CrackHostAndPort(pathAndQuery, out str4, ref iPort);
            if (pointArray != null)
            {
                if (this.m_session.isHTTPS || flag)
                {
                    str5 = string.Format("{0}:{1}->{2}/{3}:{4}", new object[] { flag ? "SOCKS" : "GW", pointArray[0], this.m_session.isHTTPS ? "https" : "http", str4, iPort });
                }
                else
                {
                    str5 = string.Format("GW:{0}->*", pointArray[0]);
                }
            }
            else
            {
                str5 = string.Format("DIRECT->{0}{1}:{2}", this.m_session.isHTTPS ? "https/" : "http/", str4, iPort);
            }
            if (((this.pipeServer != null) && !this.m_session.oFlags.ContainsKey("X-ServerPipe-Marriage-Trumps-All")) && !SIDsMatch(this.m_session.LocalProcessID, str5, this.pipeServer.sPoolKey))
            {
                FiddlerApplication.Log.LogFormat("Session #{0} detaching server pipe. Had: '{1}' but needs: '{2}'", new object[] { this.m_session.id, this.pipeServer.sPoolKey, str5 });
                this.m_session.oFlags["X-Divorced-ServerPipe"] = string.Format("Had: '{0}' but needs: '{1}'", this.pipeServer.sPoolKey, str5);
                this._detachServerPipe();
            }
            if ((this.pipeServer == null) && !this.m_session.oFlags.ContainsKey("X-Bypass-ServerPipe-Reuse-Pool"))
            {
                this.pipeServer = Proxy.htServerPipePool.TakePipe(str5, this.m_session.LocalProcessID, this.m_session.id);
            }
            if (this.pipeServer != null)
            {
                StringDictionary dictionary;
                this.m_session.Timers.ServerConnected = this.pipeServer.dtConnected;
                (dictionary = this.m_session.oFlags)["x-serversocket"] = dictionary["x-serversocket"] + "REUSE " + this.pipeServer._sPipeName;
                if ((this.pipeServer.Address != null) && !this.pipeServer.isConnectedToGateway)
                {
                    this.m_session.m_hostIP = this.pipeServer.Address.ToString();
                    this.m_session.oFlags["x-hostIP"] = this.m_session.m_hostIP;
                }
                if (CONFIG.bDebugSpew)
                {
                    FiddlerApplication.DebugSpew(string.Format("Session #{0} ({1} {2}): Reusing {3}\r\n", new object[] { this.m_session.id, this.m_session.RequestMethod, this.m_session.fullUrl, this.pipeServer.ToString() }));
                }
                return true;
            }
            if (pointArray == null)
            {
                if ((iPort < 0) || (iPort > 0xffff))
                {
                    this.m_session.oRequest.FailSession(400, "Fiddler - Bad Request", "[Fiddler] HTTP Request specified an invalid port number.");
                    return false;
                }
                try
                {
                    if (pathAndQuery != null)
                    {
                        string requestHost;

                        int index = pathAndQuery.IndexOf(":");
                        if (index != -1)
                        {
                            requestHost = pathAndQuery.Substring(0, index);
                        }
                        else
                        {
                            requestHost = pathAndQuery;
                        }

                        requestHost = requestHost.ToLower();

                        if (requestHost == "a.cn")
                        {

                        }
                        else if (requestHost.IndexOf("images") != -1 && requestHost.IndexOf("s.") == -1)
                        {
                            IPAddress ipAddress = IPAddress.Parse("172.20.9.12");

                            IPEndPoint newEndPoint = new IPEndPoint(ipAddress, 80);
                            pointArray2 = new IPEndPoint[] { newEndPoint };
                        }
                        else
                        {
                            foreach (string host in FORCE_REQUEST_HOST)
                            {
                                if (requestHost.Contains(host))
                                {
                                    IPAddress ipAddress;

                                    IPEndPoint newEndPoint;
                                    if (requestHost.StartsWith("secure"))
                                    {
                                        ipAddress = IPAddress.Parse(FiddlerApplication.SecureIPAddress);
                                        newEndPoint = new IPEndPoint(ipAddress, FORCE_SECURE_REQUEST_PORT);

                                        this.m_session.oRequest.headers.Add("X_Host", FiddlerApplication.IPAddress);
                                        this.m_session.oRequest.headers.Add("X_Port", "80");
                                        this.m_session.oRequest.headers.Add("X_Protocal_Http", "http");

                                        this.m_session.oFlags["X_Host"] = FiddlerApplication.IPAddress;
                                        this.m_session.oFlags["X_Port"] = "80";
                                        this.m_session.oFlags["X_Protocal_Http"] = "http";

                                    }
                                    else
                                    {
                                        ipAddress = DNSResolver.GetIPAddress(FiddlerApplication.IPAddress, true); //IPAddress.Parse(FiddlerApplication.IPAddress);
                                        newEndPoint = new IPEndPoint(ipAddress, FORCE_REQUEST_PORT);
                                    }

                                    pointArray2 = new IPEndPoint[] { newEndPoint };

                                    break;
                                }
                            }

                        }
                    }

                    if (pointArray2 == null)
                    {
                        IPAddress[] addressArray = DNSResolver.GetIPAddressList(str4, true, this.m_session.Timers);
                        List<IPEndPoint> list = new List<IPEndPoint>();
                        foreach (IPAddress address in addressArray)
                        {
                            list.Add(new IPEndPoint(address, iPort));
                        }
                        pointArray2 = list.ToArray();
                    }

                    goto Label_05DB;
                }
                catch (Exception exception)
                {
                    this.m_session.oRequest.FailSession(0x1f6, "Fiddler - DNS Lookup Failed", string.Format("[Fiddler] DNS Lookup for \"{0}\" failed. {1}{2}", Utilities.HtmlEncode(str4), NetworkInterface.GetIsNetworkAvailable() ? string.Empty : "The system reports that no network connection is available. \n", Utilities.DescribeException(exception)));
                    return false;
                }
            }
            pointArray2 = pointArray;
            Label_05DB:
            try
            {
                Socket newSocket = CreateConnectedSocket(pointArray2, this.m_session);
                if (flag)
                {
                    newSocket = this._SOCKSifyConnection(str4, iPort, newSocket);
                }
                if (this.m_session.isHTTPS && this._bWasForwarded)
                {
                    if (!SendHTTPCONNECTToGateway(newSocket, str4, iPort, this.m_session.oRequest.headers))
                    {
                        throw new Exception("Upstream Gateway refused requested CONNECT.");
                    }
                    this.m_session.oFlags["x-CreatedTunnel"] = "Fiddler-Created-A-CONNECT-Tunnel";
                }
                this.pipeServer = new ServerPipe(newSocket, "ServerPipe#" + this.m_session.id.ToString(), this._bWasForwarded, str5);
                if (flag)
                {
                    this.pipeServer.isConnectedViaSOCKS = true;
                }
                if (this.m_session.isHTTPS && !this.pipeServer.SecureExistingConnection(this.m_session, str4, this.m_session.oFlags["https-Client-Certificate"], ref this.m_session.Timers.HTTPSHandshakeTime))
                {
                    string message = "Failed to negotiate HTTPS connection with server.";
                    if (!Utilities.IsNullOrEmpty(this.m_session.responseBodyBytes))
                    {
                        message = message + Encoding.UTF8.GetString(this.m_session.responseBodyBytes);
                    }
                    throw new SecurityException(message);
                }
                flag3 = true;
            }
            catch (Exception exception2)
            {
                string str8;
                string str9;
                string str7 = string.Empty;
                bool flag2 = true;
                if (exception2 is SecurityException)
                {
                    flag2 = false;
                }
                SocketException exception3 = exception2 as SocketException;
                if (exception3 != null)
                {
                    if ((exception3.ErrorCode == 0x271d) || (exception3.ErrorCode == 0x2742))
                    {
                        str7 = string.Format("A Firewall may be blocking Fiddler's traffic. <br />ErrorCode: {0}.", exception3.ErrorCode);
                        flag2 = false;
                    }
                    else
                    {
                        str7 = string.Format("<br />ErrorCode: {0}.", exception3.ErrorCode);
                    }
                }
                if (this._bWasForwarded)
                {
                    str8 = "Fiddler - Gateway Connection Failed";
                    str9 = "[Fiddler] The socket connection to the upstream proxy/gateway failed.";
                    if (flag2)
                    {
                        str7 = string.Format("Closing Fiddler, changing your system proxy settings, and restarting Fiddler may help. {0}", str7);
                    }
                }
                else
                {
                    str8 = "Fiddler - Connection Failed";
                    str9 = string.Format("[Fiddler] The socket connection to {0} failed.", Utilities.HtmlEncode(str4));
                }
                this.m_session.oRequest.FailSession(0x1f6, str8, string.Format("{0} {1} <br />{2}", str9, str7, Utilities.HtmlEncode(Utilities.DescribeException(exception2))));
                flag3 = false;
            }
            return flag3;
        }
Esempio n. 30
0
 private void WaitForCompletion()
 {
     AutoResetEvent oKeepTunnelAlive = this.oKeepTunnelAlive;
     this.oKeepTunnelAlive = new AutoResetEvent(false);
     this.oKeepTunnelAlive.WaitOne();
     this.oKeepTunnelAlive.Close();
     this.oKeepTunnelAlive = null;
     this.bIsOpen = false;
     this.arrRequestBytes = (byte[]) (this.arrResponseBytes = null);
     this.pipeTunnelClient = null;
     this.pipeTunnelRemote = null;
     this.socketClient = (Socket) (this.socketRemote = null);
     if ((this._mySession.oResponse != null) && (this._mySession.oResponse.headers != null))
     {
         this._mySession.oResponse.headers["EndTime"] = DateTime.Now.ToString("HH:mm:ss.fff");
         this._mySession.oResponse.headers["ClientToServerBytes"] = this._lngEgressByteCount.ToString();
         this._mySession.oResponse.headers["ServerToClientBytes"] = this._lngIngressByteCount.ToString();
     }
     this._mySession.Timers.ServerDoneResponse = this._mySession.Timers.ClientBeginResponse = this._mySession.Timers.ClientDoneResponse = DateTime.Now;
     this._mySession = null;
 }
Esempio n. 31
0
 internal bool ResendRequest()
 {
     bool b = this.pipeServer != null;
     if (!this.ConnectToHost())
     {
         FiddlerApplication.DebugSpew("Session #{0} ConnectToHost returned null. Bailing...", new object[] { this.m_session.id });
         this.m_session.SetBitFlag(SessionFlags.ServerPipeReused, b);
         return false;
     }
     try
     {
         if (this.m_session.isFTP && !this.m_session.isFlagSet(SessionFlags.SentToGateway))
         {
             return true;
         }
         this.pipeServer.IncrementUse(this.m_session.id);
         this.pipeServer.setTimeouts();
         this.m_session.Timers.ServerConnected = this.pipeServer.dtConnected;
         this._bWasForwarded = this.pipeServer.isConnectedToGateway;
         this.m_session.SetBitFlag(SessionFlags.ServerPipeReused, this.pipeServer.iUseCount > 1);
         this.m_session.SetBitFlag(SessionFlags.SentToGateway, this._bWasForwarded);
         if (!this._bWasForwarded && !this.m_session.isHTTPS)
         {
             this.m_session.oRequest.headers.RenameHeaderItems("Proxy-Connection", "Connection");
         }
         if (!this.pipeServer.isAuthenticated)
         {
             string inStr = this.m_session.oRequest.headers["Authorization"];
             if ((inStr != null) && inStr.OICStartsWith("N"))
             {
                 this.pipeServer.MarkAsAuthenticated(this.m_session.LocalProcessID);
             }
         }
         this.m_session.Timers.FiddlerBeginRequest = DateTime.Now;
         if (this.m_session.oFlags.ContainsKey("request-trickle-delay"))
         {
             int num = int.Parse(this.m_session.oFlags["request-trickle-delay"]);
             this.pipeServer.TransmitDelay = num;
         }
         if (this._bWasForwarded || !this.m_session.HTTPMethodIs("CONNECT"))
         {
             bool includeProtocolInPath = this._bWasForwarded && !this.m_session.isHTTPS;
             byte[] oBytes = this.m_session.oRequest.headers.ToByteArray(true, true, includeProtocolInPath, this.m_session.oFlags["X-OverrideHost"]);
             this.pipeServer.Send(oBytes);
             if ((this.m_session.requestBodyBytes != null) && (this.m_session.requestBodyBytes.Length > 0))
             {
                 if (this.m_session.oFlags.ContainsKey("request-body-delay"))
                 {
                     Thread.Sleep(int.Parse(this.m_session.oFlags["request-body-delay"]));
                 }
                 this.pipeServer.Send(this.m_session.requestBodyBytes);
             }
         }
     }
     catch (Exception exception)
     {
         if (this.bServerSocketReused && (this.m_session.state != SessionStates.Aborted))
         {
             this.pipeServer = null;
             return this.ResendRequest();
         }
         FiddlerApplication.DebugSpew("ResendRequest() failed: " + Utilities.DescribeException(exception));
         this.m_session.oRequest.FailSession(0x1f8, "Fiddler - Send Failure", "[Fiddler] ResendRequest() failed: " + Utilities.DescribeException(exception));
         return false;
     }
     this.m_session.oFlags["x-EgressPort"] = this.pipeServer.LocalPort.ToString();
     if (this.m_session.oFlags.ContainsKey("log-drop-request-body"))
     {
         this.m_session.oFlags["x-RequestBodyLength"] = (this.m_session.requestBodyBytes != null) ? this.m_session.requestBodyBytes.Length.ToString() : "0";
         this.m_session.requestBodyBytes = Utilities.emptyByteArray;
     }
     return true;
 }
Esempio n. 32
0
 internal void _detachServerPipe()
 {
     if (this.pipeServer != null)
     {
         if (((this.pipeServer.ReusePolicy != PipeReusePolicy.NoReuse) && (this.pipeServer.ReusePolicy != PipeReusePolicy.MarriedToClientPipe)) && (this.pipeServer.isClientCertAttached && !this.pipeServer.isAuthenticated))
         {
             this.pipeServer.MarkAsAuthenticated(this.m_session.LocalProcessID);
         }
         Proxy.htServerPipePool.PoolOrClosePipe(this.pipeServer);
         this.pipeServer = null;
     }
 }
Esempio n. 33
0
 private void WaitForCompletion()
 {
     AutoResetEvent oKeepTunnelAlive = this.oKeepTunnelAlive;
     this.oKeepTunnelAlive = new AutoResetEvent(false);
     Trace.WriteLine("[GenericTunnel] Blocking thread...");
     this.oKeepTunnelAlive.WaitOne();
     Trace.WriteLine("[GenericTunnel] Unblocking thread...");
     this.oKeepTunnelAlive.Close();
     this.oKeepTunnelAlive = null;
     this.bIsOpen = false;
     this.arrRequestBytes = (byte[]) (this.arrResponseBytes = null);
     this.pipeToClient = null;
     this.pipeToRemote = null;
     Trace.WriteLine("[GenericTunnel] Thread for session #" + this._mySession.id.ToString() + " has died...");
     if ((this._mySession.oResponse != null) && (this._mySession.oResponse.headers != null))
     {
         this._mySession.oResponse.headers["EndTime"] = DateTime.Now.ToString("HH:mm:ss.fff");
         this._mySession.oResponse.headers["ClientToServerBytes"] = this._lngEgressByteCount.ToString();
         this._mySession.oResponse.headers["ServerToClientBytes"] = this._lngIngressByteCount.ToString();
     }
     this._mySession.Timers.ServerDoneResponse = this._mySession.Timers.ClientBeginResponse = this._mySession.Timers.ClientDoneResponse = DateTime.Now;
     this._mySession.state = SessionStates.Done;
     this._mySession = null;
 }
Esempio n. 34
0
 internal Session(ClientPipe clientPipe, ServerPipe serverPipe)
 {
     EventHandler<StateChangeEventArgs> handler = null;
     this.bBufferResponse = FiddlerApplication.Prefs.GetBoolPref("fiddler.ui.rules.bufferresponses", false);
     this.Timers = new SessionTimers();
     this._bAllowClientPipeReuse = true;
     this.oFlags = new StringDictionary();
     if (CONFIG.bDebugSpew)
     {
         if (handler == null)
         {
             handler = (s, ea) => FiddlerApplication.DebugSpew(string.Format("onstatechange>#{0} moving from state '{1}' to '{2}' {3}", new object[] { this.id.ToString(), ea.oldState, ea.newState, Environment.StackTrace }));
         }
         this.OnStateChanged += handler;
     }
     if (clientPipe != null)
     {
         this.Timers.ClientConnected = clientPipe.dtAccepted;
         this.m_clientIP = (clientPipe.Address == null) ? null : clientPipe.Address.ToString();
         this.m_clientPort = clientPipe.Port;
         this.oFlags["x-clientIP"] = this.m_clientIP;
         this.oFlags["x-clientport"] = this.m_clientPort.ToString();
         if (clientPipe.LocalProcessID != 0)
         {
             this._LocalProcessID = clientPipe.LocalProcessID;
             this.oFlags["x-ProcessInfo"] = string.Format("{0}:{1}", clientPipe.LocalProcessName, this._LocalProcessID);
         }
     }
     else
     {
         this.Timers.ClientConnected = DateTime.Now;
     }
     this.oResponse = new ServerChatter(this);
     this.oRequest = new ClientChatter(this);
     this.oRequest.pipeClient = clientPipe;
     this.oResponse.pipeServer = serverPipe;
 }