//internal object _GetTransportContext() //{ // if (base._httpsStream != null) // { // return base._httpsStream.get_TransportContext(); // } // return null; //} 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)) { X509Certificate certificate = this._GetDefaultCertificate(); if (certificate != null) { this.MarkAsAuthenticated(oS.LocalProcessID); oS.oFlags["x-client-cert"] = certificate.Subject + " Serial#" + certificate.GetSerialNumberString(); return(certificate); } if (KPCONFIG.bShowDefaultClientCertificateNeededPrompt && KProxyApplication.Prefs.GetBoolPref("KProxy.network.https.clientcertificate.ephemeral.prompt-for-missing", true)) { KProxyApplication.DoNotifyUser("The server [" + targetHost + "] requests a client certificate.\nPlease save a client certificate using the filename:\n\n" + KPCONFIG.GetPath("DefaultClientCertificate"), "Client Certificate Requested"); KProxyApplication.Prefs.SetBoolPref("KProxy.network.https.clientcertificate.ephemeral.prompt-for-missing", false); } } return(null); }
internal bool Attach(bool bCollectGWInfo) { if (!this._bIsAttached) { if (bCollectGWInfo) { this.CollectConnectoidAndGatewayInfo(); } WinINETProxyInfo oNewInfo = new WinINETProxyInfo(); oNewInfo.bUseManualProxies = true; oNewInfo.bAllowDirect = true; oNewInfo.sHttpProxy = KPCONFIG.sKProxyListenHostPort; if (KPCONFIG.bCaptureCONNECT) { oNewInfo.sHttpsProxy = KPCONFIG.sKProxyListenHostPort; } else if (this.piPrior != null) { oNewInfo.sHttpsProxy = this.piPrior.sHttpsProxy; } if ((this.piPrior != null) && this.piPrior.bUseManualProxies) { oNewInfo.sFtpProxy = this.piPrior.sFtpProxy; oNewInfo.sSocksProxy = this.piPrior.sSocksProxy; } if (KPCONFIG.bCaptureFTP) { oNewInfo.sFtpProxy = KPCONFIG.sKProxyListenHostPort; } oNewInfo.sHostsThatBypass = KPCONFIG.sHostsThatBypassKProxy; if (KPCONFIG.bHookWithPAC) { if (KProxyApplication.Prefs.GetBoolPref("KProxy.proxy.pacfile.usefileprotocol", true)) { oNewInfo.sPACScriptLocation = "file://" + KPCONFIG.GetPath("Pac"); } else { oNewInfo.sPACScriptLocation = "http://" + KPCONFIG.sKProxyListenHostPort + "/proxy.pac"; } } if (!KPCONFIG.bIsViewOnly) { if (this.oAllConnectoids.HookConnections(oNewInfo)) { this._bIsAttached = true; KProxyApplication.OnKProxyAttach(); this.WriteAutoProxyPACFile(true); } else { KProxyApplication.DoNotifyUser("Failed to register KProxy as the system proxy.", "Error"); _setDynamicRegistryKey(false); return(false); } _setDynamicRegistryKey(true); } } return(true); }
private bool HeadersAvailable() { if (this.iEntityBodyOffset <= 0) { HTTPHeaderParseWarnings warnings; if (this.m_responseData == null) { return(false); } if (!Parser.FindEndOfHeaders(this.m_responseData.GetBuffer(), ref this._iBodySeekProgress, this.m_responseData.Length, out warnings)) { return(false); } this.iEntityBodyOffset = this._iBodySeekProgress + 1; switch (warnings) { case HTTPHeaderParseWarnings.EndedWithLFLF: KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "The Server did not return properly formatted HTTP Headers. HTTP headers\nshould be terminated with CRLFCRLF. These were terminated with LFLF."); break; case HTTPHeaderParseWarnings.EndedWithLFCRLF: KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "The Server did not return properly formatted HTTP Headers. HTTP headers\nshould be terminated with CRLFCRLF. These were terminated with LFCRLF."); break; } } return(true); }
private bool isRequestComplete() { if (this.m_headers == null) { if (!this.HeadersAvailable()) { return(false); } if (!this.ParseRequestForHeaders()) { string str; if (this.m_requestData != null) { str = Utilities.ByteArrayToHexView(this.m_requestData.GetBuffer(), 0x18, (int)Math.Min(this.m_requestData.Length, 0x800L)); } else { str = "{Kavprot Proxy:no data}"; } if (this.m_headers == null) { this.m_headers = new HTTPRequestHeaders(); this.m_headers.HTTPMethod = "BAD"; this.m_headers["Host"] = "BAD-REQUEST"; this.m_headers.RequestPath = "/BAD_REQUEST"; } this.FailSession(400, "Kavprot Proxy - Bad Request", "[Kavprot Proxy] Request Header parsing failed. Request was:\n" + str); return(true); } this.m_session.Timers.KProxyGotRequestHeaders = DateTime.Now; this.m_session._AssignID(); KProxyApplication.DoRequestHeadersAvailable(this.m_session); } if (this.m_headers.ExistsAndEquals("Transfer-encoding", "chunked")) { long num; long num2; return(Utilities.IsChunkedBodyComplete(this.m_session, this.m_requestData, (long)this.iEntityBodyOffset, out num2, out num)); } if (this.m_headers.Exists("Content-Length")) { long result = 0L; try { if (!long.TryParse(this.m_headers["Content-Length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out result) || (result < 0L)) { KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, true, "Request content length was invalid.\nContent-Length: " + this.m_headers["Content-Length"]); this.FailSession(400, "Kavprot Proxy - Bad Request", "[Kavprot Proxy] Request Content-Length header parsing failed.\nContent-Length: " + this.m_headers["Content-Length"]); return(true); } return(this.m_requestData.Length >= (this.iEntityBodyOffset + result)); } catch { this.FailSession(400, "Kavprot Proxy - Bad Request", "[Kavprot Proxy] Unknown error: Check content length header?"); return(false); } } return(true); }
internal bool SecureExistingConnection(Session oS, string sCertCN, string sClientCertificateFilename, string sPoolingKey, ref int iHandshakeTime) { RemoteCertificateValidationCallback userCertificateValidationCallback = null; LocalCertificateSelectionCallback userCertificateSelectionCallback = null; Stopwatch stopwatch = Stopwatch.StartNew(); try { this.sPoolKey = sPoolingKey; X509CertificateCollection certificateCollectionFromFile = this.GetCertificateCollectionFromFile(sClientCertificateFilename); if (userCertificateValidationCallback == null) { userCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(ConfirmServerCertificate(oS, sCertCN, certificate, chain, sslPolicyErrors)); }; } if (userCertificateSelectionCallback == null) { userCertificateSelectionCallback = delegate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { return(this.AttachClientCertificate(oS, sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers)); }; } base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false, userCertificateValidationCallback, userCertificateSelectionCallback); base._httpsStream.AuthenticateAsClient(sCertCN, certificateCollectionFromFile, KPCONFIG.oAcceptedServerHTTPSProtocols, KProxyApplication.Prefs.GetBoolPref("KProxy.https.checkcertificaterevocation", false)); iHandshakeTime = (int)stopwatch.ElapsedMilliseconds; } catch (Exception exception) { iHandshakeTime = (int)stopwatch.ElapsedMilliseconds; KProxyApplication.DebugSpew(exception.StackTrace + "\n" + exception.Message); return(false); } return(true); }
internal bool ResendRequest() { bool b = this.pipeServer != null; if (!this.ConnectToHost()) { KProxyApplication.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.KProxyBeginRequest = 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()); } KProxyApplication.DebugSpew("ResendRequest() failed: " + Utilities.DescribeException(exception)); this.m_session.oRequest.FailSession(0x1f8, "Kavprot Proxy - Send Failure", "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 = new byte[0]; } return(true); }
private bool GetHeaders() { if (!this.HeadersAvailable()) { return(false); } if (!this.ParseResponseForHeaders()) { string str; this.m_session.SetBitFlag(SessionFlags.ProtocolViolationInResponse, true); this._PoisonPipe(); if (this.m_responseData != null) { str = "<plaintext>\n" + Utilities.ByteArrayToHexView(this.m_responseData.GetBuffer(), 0x18, (int)Math.Min(this.m_responseData.Length, 0x800L)); } else { str = "{Kavprot Proxy:no data}"; } this.m_session.oRequest.FailSession(500, "Kavprot Proxy - Bad Response", string.Format("[Kavprot Proxy] Response Header parsing failed.\n{0}Response Data:\n{1}", this.m_session.isFlagSet(SessionFlags.ServerPipeReused) ? "This can be caused by an illegal HTTP response earlier on this reused server socket-- for instance, a HTTP/304 response which illegally contains a body.\n" : string.Empty, str)); return(true); } if ((this.m_inHeaders.HTTPResponseCode <= 0x63) || (this.m_inHeaders.HTTPResponseCode >= 200)) { return(true); } if (this.m_inHeaders.Exists("Content-Length") && ("0" != this.m_inHeaders["Content-Length"].Trim())) { KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "HTTP/1xx responses MUST NOT contain a body, but a non-zero content-length was returned."); } if (KProxyApplication.Prefs.GetBoolPref("KProxy.network.streaming.leakhttp1xx", true) && (this.m_session.oRequest.pipeClient != null)) { try { StringDictionary dictionary; this.m_session.oRequest.pipeClient.Send(this.m_inHeaders.ToByteArray(true, true)); (dictionary = this.m_session.oFlags)["x-KProxy-Stream1xx"] = dictionary["x-KProxy-Stream1xx"] + "Returned a HTTP/" + this.m_inHeaders.HTTPResponseCode.ToString() + " message from the server."; } catch (Exception exception) { if (KProxyApplication.Prefs.GetBoolPref("KProxy.network.streaming.abortifclientaborts", false)) { throw new Exception("Leaking HTTP/1xx response to client failed", exception); } } } else { StringDictionary dictionary2; (dictionary2 = this.m_session.oFlags)["x-KProxy-streaming"] = dictionary2["x-KProxy-streaming"] + "Eating a HTTP/" + this.m_inHeaders.HTTPResponseCode.ToString() + " message from the stream."; } this._deleteInformationalMessage(); return(this.GetHeaders()); }
internal bool SecureClientPipe(string sHostname, HTTPResponseHeaders oHeaders) { X509Certificate2 certificate; try { certificate = CertMaker.FindCert(sHostname, true); } catch (Exception exception) { //KProxyApplication.Log.LogFormat("KProxy.https> Failed to obtain certificate for {0} due to {1}", new object[] { sHostname, exception.Message }); certificate = null; } try { if (certificate == null) { KProxyApplication.DoNotifyUser("Unable to find Certificate for " + sHostname, "HTTPS Interception Failure"); oHeaders.HTTPResponseCode = 0x1f6; oHeaders.HTTPResponseStatus = "502 KProxy unable to generate certificate"; } if (KPCONFIG.bDebugSpew) { KProxyApplication.DebugSpew("SecureClientPipe for: " + this.ToString() + " sending data to client:\n" + Utilities.ByteArrayToHexView(oHeaders.ToByteArray(true, true), 0x20)); } base.Send(oHeaders.ToByteArray(true, true)); if (oHeaders.HTTPResponseCode != 200) { KProxyApplication.DebugSpew("SecureClientPipe returning FALSE because HTTPResponseCode != 200"); return(false); } base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false); base._httpsStream.AuthenticateAsServer(certificate, _bWantClientCert, KPCONFIG.oAcceptedClientHTTPSProtocols, false); return(true); } catch (Exception exception2) { //KProxyApplication.Log.LogFormat("Secure client pipe failed: {0}{1}.", new object[] { exception2.Message, (exception2.InnerException == null) ? string.Empty : (" InnerException: " + exception2.InnerException.Message) }); KProxyApplication.DebugSpew("Secure client pipe failed: " + exception2.Message); try { base.End(); } catch { } } return(false); }
internal byte[] TakeEntity() { byte[] bytes; if (this.iEntityBodyOffset < 0) { throw new InvalidDataException("Request Entity Body Offset must not be negative"); } long num = this.m_requestData.Length - this.iEntityBodyOffset; long num2 = this._calculateExpectedEntityTransferSize(); if (num > num2) { //KProxyApplication.Log.LogFormat("HTTP Pipelining Client detected; excess data on client socket for session #{0}.", new object[] { this.m_session.id }); try { bytes = new byte[num - num2]; this.m_requestData.Position = this.iEntityBodyOffset + num2; this.m_requestData.Read(bytes, 0, bytes.Length); } catch (OutOfMemoryException exception) { KProxyApplication.ReportException(exception, "HTTP Request Pipeline Too Large"); bytes = Encoding.ASCII.GetBytes("Kavprot Proxy: Out of memory"); this.m_session.PoisonClientPipe(); return(new byte[0]); } this.pipeClient.putBackSomeBytes(bytes); num = num2; } if ((num != num2) && (num < num2)) { KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, true, string.Format("Content-Length mismatch: Request Header indicated {0:N0} bytes, but client sent {1:N0} bytes.", num2, num)); } try { bytes = new byte[num]; this.m_requestData.Position = this.iEntityBodyOffset; this.m_requestData.Read(bytes, 0, bytes.Length); } catch (OutOfMemoryException exception2) { KProxyApplication.ReportException(exception2, "HTTP Request Too Large"); bytes = Encoding.ASCII.GetBytes("Kavprot Proxy: Out of memory"); this.m_session.PoisonClientPipe(); } this._freeRequestData(); return(bytes); }
private void ScanPathForTranscoders(string sPath) { try { if (Directory.Exists(sPath)) { Evidence securityEvidence = Assembly.GetExecutingAssembly().Evidence; bool boolPref = KProxyApplication.Prefs.GetBoolPref("KProxy.debug.extensions.verbose", false); if (boolPref) { //KProxyApplication.Log.LogFormat("Searching for Transcoders under {0}", new object[] { sPath }); } foreach (FileInfo info in new DirectoryInfo(sPath).GetFiles()) { if (info.FullName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !info.FullName.StartsWith("_", StringComparison.OrdinalIgnoreCase)) { Assembly assembly; if (boolPref) { //KProxyApplication.Log.LogFormat("Looking for Transcoders inside {0}", new object[] { info.FullName.ToString() }); } try { if (KPCONFIG.bRunningOnCLRv4) { assembly = Assembly.LoadFrom(info.FullName); } else { assembly = Assembly.LoadFrom(info.FullName, securityEvidence); } } catch (Exception exception) { KProxyApplication.LogAddonException(exception, "Failed to load " + info.FullName); continue; } this.ScanAssemblyForTranscoders(assembly); } } } } catch (Exception exception2) { KProxyApplication.DoNotifyUser(string.Format("[Kavprot Proxy] Failure loading Transcoders: {0}", exception2.Message), "Transcoders Load Error"); } }
private void _NotifyThreadExecute(object objThreadState) { PrefChangeEventArgs e = (PrefChangeEventArgs)objThreadState; string prefName = e.PrefName; List <EventHandler <PrefChangeEventArgs> > list = null; try { GetReaderLock(this._RWLockWatchers); try { foreach (PrefWatcher watcher in this._listWatchers) { if (prefName.StartsWith(watcher.sPrefixToWatch, StringComparison.Ordinal)) { if (list == null) { list = new List <EventHandler <PrefChangeEventArgs> >(); } list.Add(watcher.fnToNotify); } } } finally { FreeReaderLock(this._RWLockWatchers); } if (list != null) { foreach (EventHandler <PrefChangeEventArgs> handler in list) { try { handler(this, e); } catch (Exception exception) { KProxyApplication.ReportException(exception); } } } } catch (Exception exception2) { KProxyApplication.ReportException(exception2); } }
public void FailSession(int iError, string sErrorStatusText, string sErrorBody) { this.m_session.SetBitFlag(SessionFlags.ResponseGeneratedByKProxy, true); if ((iError >= 400) && (sErrorBody.Length < 0x200)) { sErrorBody = sErrorBody.PadRight(0x200, ' '); } this.m_session.responseBodyBytes = Encoding.UTF8.GetBytes(sErrorBody); this.m_session.oResponse.headers = new HTTPResponseHeaders(KPCONFIG.oHeaderEncoding); this.m_session.oResponse.headers.HTTPResponseCode = iError; this.m_session.oResponse.headers.HTTPResponseStatus = iError.ToString() + " " + sErrorStatusText; this.m_session.oResponse.headers.Add("Content-Type", "text/html; charset=UTF-8"); this.m_session.oResponse.headers.Add("Connection", "close"); this.m_session.oResponse.headers.Add("Timestamp", DateTime.Now.ToString("HH:mm:ss.fff")); this.m_session.state = SessionStates.Aborted; KProxyApplication.DoBeforeReturningError(this.m_session); this.m_session.ReturnResponse(false); }
internal static bool exportRootToDesktop() { try { byte[] bytes = getRootCertBytes(); if (bytes != null) { File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ASRoot.cer", bytes); return(true); } } catch (Exception exception) { KProxyApplication.ReportException(exception); return(false); } return(false); }
internal byte[] TakeEntity() { byte[] bytes; try { bytes = new byte[this.m_responseData.Length - this.iEntityBodyOffset]; this.m_responseData.Position = this.iEntityBodyOffset; this.m_responseData.Read(bytes, 0, bytes.Length); } catch (OutOfMemoryException exception) { KProxyApplication.ReportException(exception, "HTTP Response Too Large"); bytes = Encoding.ASCII.GetBytes("Kavprot Proxy: Out of memory"); this.m_session.PoisonServerPipe(); } this.FreeResponseDataBuffer(); return(bytes); }
private bool isResponseBodyComplete() { if (this.m_session.HTTPMethodIs("HEAD")) { return(true); } if (this.m_session.HTTPMethodIs("CONNECT") && (this.m_inHeaders.HTTPResponseCode == 200)) { return(true); } if (((this.m_inHeaders.HTTPResponseCode == 0xcc) || (this.m_inHeaders.HTTPResponseCode == 0xcd)) || (this.m_inHeaders.HTTPResponseCode == 0x130)) { if (this.m_inHeaders.Exists("Content-Length") && ("0" != this.m_inHeaders["Content-Length"].Trim())) { KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, false, true, "This type of HTTP response MUST NOT contain a body, but a non-zero content-length was returned."); return(true); } return(true); } if (this.m_inHeaders.ExistsAndEquals("Transfer-Encoding", "chunked")) { long num; if (this._lngLastChunkInfoOffset < this.iEntityBodyOffset) { this._lngLastChunkInfoOffset = this.iEntityBodyOffset; } return(Utilities.IsChunkedBodyComplete(this.m_session, this.m_responseData, this._lngLastChunkInfoOffset, out this._lngLastChunkInfoOffset, out num)); } if (this.m_inHeaders.Exists("Content-Length")) { long num2; if (long.TryParse(this.m_inHeaders["Content-Length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out num2) && (num2 >= 0L)) { return(this.m_responseTotalDataCount >= (this.iEntityBodyOffset + num2)); } KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, true, true, "Content-Length response header is not a valid unsigned integer.\nContent-Length: " + this.m_inHeaders["Content-Length"]); return(true); } if ((!this.m_inHeaders.ExistsAndEquals("Connection", "close") && !this.m_inHeaders.ExistsAndEquals("Proxy-Connection", "close")) && ((this.m_inHeaders.HTTPVersion == "HTTP/1.1") || this.m_inHeaders.ExistsAndContains("Connection", "Keep-Alive"))) { KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInResponse, true, true, "No Connection: close, no Content-Length. No way to tell if the response is complete."); } return(false); }
private static bool ConfirmServerCertificate(Session oS, string sExpectedCN, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { CertificateValidity oValidity = CertificateValidity.Default; KProxyApplication.CheckOverrideCertificatePolicy(oS, sExpectedCN, certificate, chain, sslPolicyErrors, ref oValidity); switch (oValidity) { case CertificateValidity.ForceInvalid: return(false); case CertificateValidity.ForceValid: return(true); } if ((oValidity == CertificateValidity.ConfirmWithUser) || ((sslPolicyErrors != SslPolicyErrors.None) && !KPCONFIG.IgnoreServerCertErrors)) { return(false); } return(true); }
private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e) { try { DNSResolver.ClearCache(); //KProxyApplication.Log.LogString("NetworkAddressChanged."); if (this.oAutoProxy != null) { this.oAutoProxy.iAutoProxySuccessCount = 0; } if ((KPCONFIG.bForwardToGateway && (this.piPrior != null)) && this.piPrior.bUseManualProxies) { this._DetermineGatewayIPEndPoints(); } } catch (Exception exception) { KProxyApplication.ReportException(exception); } }
public bool Detach() { if (!this._bIsAttached) { return(true); } if (KPCONFIG.bIsViewOnly) { return(true); } _setDynamicRegistryKey(false); if (this.oAllConnectoids.UnhookAllConnections()) { this._bIsAttached = false; KProxyApplication.OnKProxyDetach(); this.WriteAutoProxyPACFile(false); return(true); } return(false); }
private void RunTunnel() { if (KProxyApplication.oProxy != null) { try { IPEndPoint ipepForwardHTTPS = null; if (this._mySession.oFlags["x-overrideGateway"] != null) { if (string.Equals("DIRECT", this._mySession.oFlags["x-overrideGateway"], StringComparison.OrdinalIgnoreCase)) { this._mySession.bypassGateway = true; } else { ipepForwardHTTPS = Utilities.IPEndPointFromHostPortString(this._mySession.oFlags["x-overrideGateway"]); } } else if (!this._mySession.bypassGateway) { int tickCount = Environment.TickCount; ipepForwardHTTPS = KProxyApplication.oProxy.FindGatewayForOrigin("https", this._mySession.oFlags["x-overrideHost"] ?? this._mySession.PathAndQuery); this._mySession.Timers.GatewayDeterminationTime = Environment.TickCount - tickCount; } if (ipepForwardHTTPS != null) { this.TunnelToGateway(ipepForwardHTTPS); } else { this.TunnelDirectly(); } } catch (Exception exception) { KProxyApplication.ReportException(exception, "Uncaught Exception in Tunnel; Session #" + this._mySession.id.ToString()); } } }
internal bool SecureClientPipeDirect(X509Certificate2 certServer) { try { base._httpsStream = new SslStream(new NetworkStream(base._baseSocket, false), false); base._httpsStream.AuthenticateAsServer(certServer, _bWantClientCert, KPCONFIG.oAcceptedClientHTTPSProtocols, false); return(true); } catch (Exception exception) { //KProxyApplication.Log.LogFormat("Secure client pipe failed: {0}{1}.", new object[] { exception.Message, (exception.InnerException == null) ? string.Empty : (" InnerException: " + exception.InnerException.Message) }); KProxyApplication.DebugSpew("Secure client pipe failed: " + exception.Message); try { base.End(); } catch { } } return(false); }
private static void VistaClearTracks(bool bClearFiles, bool bClearCookies) { int num = 0; if (bClearCookies) { num = 2; } if (bClearFiles) { num = 0x100c; } try { using (Process.Start("rundll32.exe", "inetcpl.cpl,ClearMyTracksByProcess " + num.ToString())) { } } catch (Exception exception) { KProxyApplication.DoNotifyUser("Failed to launch ClearMyTracksByProcess.\n" + exception.Message, "Error"); } }
private void _indicateTunnelFailure(int iResponseCode, string sErr) { try { this._mySession.oResponse.headers = new HTTPResponseHeaders(); this._mySession.oResponse.headers.HTTPVersion = this._mySession.oRequest.headers.HTTPVersion; this._mySession.oResponse.headers.HTTPResponseCode = iResponseCode; this._mySession.oResponse.headers.HTTPResponseStatus = (iResponseCode == 0x1f6) ? "502 Gateway Connection failure" : "504 Connection Failed"; this._mySession.oResponse.headers.Add("Connection", "close"); this._mySession.responseBodyBytes = Encoding.UTF8.GetBytes("[Kavprot Proxy] " + this._mySession.oResponse.headers.HTTPResponseStatus + ": " + sErr + "<BR>Timestamp: " + DateTime.Now.ToString("HH:mm:ss.fff")); KProxyApplication.DoBeforeReturningError(this._mySession); this.socketClient.Send(this._mySession.oResponse.headers.ToByteArray(true, true)); this.socketClient.Send(this._mySession.responseBodyBytes); this.socketClient.Shutdown(SocketShutdown.Both); if (this.socketRemote != null) { this.socketRemote.Close(); } } catch { } }
private static ICertificateProvider LoadOverrideCertProvider() { string stringPref = KProxyApplication.Prefs.GetStringPref("KProxy.certmaker.assembly", KPCONFIG.GetPath("App") + "CertMaker.dll"); if (File.Exists(stringPref)) { Assembly assembly; try { assembly = Assembly.LoadFrom(stringPref); if (!Utilities.KProxyMeetsVersionRequirement(assembly, "Certificate Maker")) { return(null); } } catch (Exception exception) { KProxyApplication.LogAddonException(exception, "Failed to load CertMaker" + stringPref); return(null); } foreach (Type type in assembly.GetExportedTypes()) { if ((!type.IsAbstract && type.IsPublic) && (type.IsClass && typeof(ICertificateProvider).IsAssignableFrom(type))) { try { return((ICertificateProvider)Activator.CreateInstance(type)); } catch (Exception exception2) { KProxyApplication.DoNotifyUser(string.Format("[Kavprot Proxy] Failure loading {0} CertMaker from {1}: {2}\n\n{3}\n\n{4}", new object[] { type.Name, assembly.CodeBase, exception2.Message, exception2.StackTrace, exception2.InnerException }), "Load Error"); } } } } return(null); }
internal static void EnsureFoldersExist() { try { if (!Directory.Exists(GetPath("Captures"))) { Directory.CreateDirectory(GetPath("Captures")); } if (!Directory.Exists(GetPath("Requests"))) { Directory.CreateDirectory(GetPath("Requests")); } if (!Directory.Exists(GetPath("Responses"))) { Directory.CreateDirectory(GetPath("Responses")); } if (!Directory.Exists(GetPath("Scripts"))) { Directory.CreateDirectory(GetPath("Scripts")); } } catch (Exception exception) { KProxyApplication.DoNotifyUser(exception.ToString(), "Folder Creation Failed"); } try { if ((!KProxyApplication.Prefs.GetBoolPref("KProxy.script.delaycreate", true) && !File.Exists(GetPath("CustomRules"))) && File.Exists(GetPath("SampleRules"))) { File.Copy(GetPath("SampleRules"), GetPath("CustomRules")); } } catch (Exception exception2) { KProxyApplication.DoNotifyUser(exception2.ToString(), "Initial file copies failed"); } }
internal static string[] GetConnectionNames() { if (KPCONFIG.bDebugSpew) { KProxyApplication.DebugSpew("WinINET indicates connectivity is via: " + GetConnectedState()); } int lpcb = Marshal.SizeOf(typeof(RASENTRYNAME)); int lpcEntries = 0; RASENTRYNAME[] lprasentryname = new RASENTRYNAME[1]; lprasentryname[0].dwSize = lpcb; uint num3 = RasEnumEntries(IntPtr.Zero, IntPtr.Zero, lprasentryname, ref lpcb, ref lpcEntries); if ((num3 != 0) && (0x25b != num3)) { lpcEntries = 0; } string[] strArray = new string[lpcEntries + 1]; strArray[0] = "DefaultLAN"; if (lpcEntries != 0) { lprasentryname = new RASENTRYNAME[lpcEntries]; for (int i = 0; i < lpcEntries; i++) { lprasentryname[i].dwSize = Marshal.SizeOf(typeof(RASENTRYNAME)); } if (RasEnumEntries(IntPtr.Zero, IntPtr.Zero, lprasentryname, ref lpcb, ref lpcEntries) != 0) { return(strArray); } for (int j = 0; j < lpcEntries; j++) { strArray[j + 1] = lprasentryname[j].szEntryName; } } return(strArray); }
internal ServerPipe DequeuePipe(string sPoolKey, int iPID, int HackiForSession) { Queue <ServerPipe> queue; ServerPipe pipe; Queue <ServerPipe> queue2; if (!KPCONFIG.bReuseServerSockets) { return(null); } lock (this.thePool) { if ((((iPID == 0) || !this.thePool.TryGetValue(string.Format("PID{0}*{1}", iPID, sPoolKey), out queue)) || (queue.Count < 1)) && (!this.thePool.TryGetValue(sPoolKey, out queue) || (queue.Count < 1))) { return(null); } } Monitor.Enter(queue2 = queue); try { if (queue.Count == 0) { return(null); } pipe = queue.Dequeue(); } catch (Exception exception) { KProxyApplication.ReportException(exception); return(null); } finally { Monitor.Exit(queue2); } return(pipe); }
internal bool Start(int iPort, bool bAllowRemote) { if (KPCONFIG.bIsViewOnly) { return(false); } bool flag = false; try { flag = (bAllowRemote && KPCONFIG.bEnableIPv6) && Socket.OSSupportsIPv6; } catch (Exception exception) { KProxyApplication.DoNotifyUser(string.Concat(new object[] { "A Microsoft .NET configuration file (listed below) is corrupt and contains invalid data. You can often correct this error by installing updates from WindowsUpdate and/or reinstalling the .NET Framework.\n\n", exception.Message, "\nSource: ", exception.Source, "\n", exception.StackTrace, "\n\n", exception.InnerException, "\nKProxy v", Application.ProductVersion, (8 == IntPtr.Size) ? " (x64) " : " (x86) ", " [.NET ", Environment.Version, " on ", Environment.OSVersion.VersionString, "] " }), ".NET Configuration Error", MessageBoxIcon.Hand); this.oAcceptor = null; return(false); } try { if (flag) { this.oAcceptor = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); if (Environment.OSVersion.Version.Major > 5) { this.oAcceptor.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation | SocketOptionName.KeepAlive, 0); } } else { this.oAcceptor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } if (KPCONFIG.ForceExclusivePort) { this.oAcceptor.ExclusiveAddressUse = true; } if (bAllowRemote) { if (flag) { this.oAcceptor.Bind(new IPEndPoint(IPAddress.IPv6Any, iPort)); } else { this.oAcceptor.Bind(new IPEndPoint(IPAddress.Any, iPort)); } } else { this.oAcceptor.Bind(new IPEndPoint(IPAddress.Loopback, iPort)); } this.oAcceptor.Listen(50); } catch (SocketException exception2) { string str = string.Empty; string sTitle = "KProxy Cannot Listen"; switch (exception2.ErrorCode) { case 0x273f: case 0x2741: if (flag) { str = "\nThis often means that you've enabled IPv6 support inside Tools > Kavprot Proxy Options, but your computer has IPv6 disabled."; } break; case 0x2740: case 0x271d: str = "\nThis is usually due to another service running on this port. Run NETSTAT -A at a command prompt.\nIf you don't want to stop using the other program, simply change the port used by KProxy.\nClick Tools > KProxy Options > Connections, select a new port, and restart KProxy."; sTitle = "Kavprot Proxy Port in Use"; break; } this.oAcceptor = null; KProxyApplication.DoNotifyUser(string.Format("Unable to bind to port [Localhost:{0}]. ErrorCode: {1}.\n{2}\n\n{3}\n\n{4}", new object[] { KPCONFIG.ListenPort, exception2.ErrorCode, str, exception2.ToString(), string.Concat(new object[] { "KProxy v", Application.ProductVersion, " [.NET ", Environment.Version, " on ", Environment.OSVersion.VersionString, "]" }) }), sTitle, MessageBoxIcon.Hand); return(false); } catch (Exception exception3) { this.oAcceptor = null; KProxyApplication.ReportException(exception3); return(false); } try { this.oAcceptor.BeginAccept(new AsyncCallback(this.AcceptConnection), null); } catch (Exception exception4) { this.oAcceptor = null; //KProxyApplication.Log.LogFormat("Kavprot Proxy BeginAccept() Exception: {0}", new object[] { exception4.Message }); return(false); } return(true); }
internal bool ReadRequest() { if (this.m_requestData != null) { KProxyApplication.ReportException(new InvalidOperationException("ReadRequest called after requestData was null'd.")); return(false); } if (this.pipeClient == null) { KProxyApplication.ReportException(new InvalidOperationException("ReadRequest called after pipeClient was null'd.")); return(false); } this.m_requestData = new MemoryStream(0x1000); this.pipeClient.IncrementUse(0); this.m_session.SetBitFlag(SessionFlags.ClientPipeReused, this.pipeClient.iUseCount > 1); this.pipeClient.setReceiveTimeout(); int iMaxByteCount = 0; bool flag = false; bool flag2 = false; byte[] arrBuffer = new byte[_cbClientReadBuffer]; do { try { iMaxByteCount = this.pipeClient.Receive(arrBuffer); } catch (Exception exception) { KProxyApplication.DebugSpew("ReadRequest Failure: " + exception.Message); flag = true; } if (iMaxByteCount <= 0) { flag2 = true; KProxyApplication.DebugSpew("ReadRequest read 0 bytes!!!!!"); } else { if (KPCONFIG.bDebugSpew) { KProxyApplication.DebugSpew("READ FROM: " + this.pipeClient.ToString() + ":\n" + Utilities.ByteArrayToHexView(arrBuffer, 0x20, iMaxByteCount)); } if (this.m_requestData.Length == 0L) { this.m_session.Timers.ClientBeginRequest = DateTime.Now; int index = 0; while ((index < iMaxByteCount) && ((arrBuffer[index] == 13) || (arrBuffer[index] == 10))) { index++; } this.m_requestData.Write(arrBuffer, index, iMaxByteCount - index); } else { this.m_requestData.Write(arrBuffer, 0, iMaxByteCount); } } }while ((!flag2 && !flag) && !this.isRequestComplete()); arrBuffer = null; if (flag || (this.m_requestData.Length == 0L)) { if ((this.pipeClient.iUseCount < 2) || (this.pipeClient.bIsSecured && (this.pipeClient.iUseCount < 3))) { //KProxyApplication.Log.LogFormat("[Kavprot Proxy] Failed to read {0} request from ({1}) new client socket, port {2}.", new object[] { this.pipeClient.bIsSecured ? "HTTPS" : "HTTP", this.m_session.oFlags["X-ProcessInfo"], this.m_session.oFlags["X-CLIENTPORT"] }); } this._freeRequestData(); return(false); } if ((this.m_headers == null) || (this.m_session.state >= SessionStates.Done)) { this._freeRequestData(); return(false); } if ("CONNECT" == this.m_headers.HTTPMethod) { this.m_session.isTunnel = true; this.m_sHostFromURI = this.m_session.PathAndQuery; } if (this.m_sHostFromURI != null) { if (this.m_headers.Exists("Host") && !Utilities.areOriginsEquivalent(this.m_sHostFromURI, this.m_headers["Host"], (this.m_session.isTunnel || this.m_session.isHTTPS) ? 0x1bb : (this.m_session.isFTP ? 0x15 : 80))) { this.m_session.oFlags["X-Original-Host"] = this.m_headers["Host"]; this.m_headers["Host"] = this.m_sHostFromURI; } else if (!this.m_headers.Exists("Host")) { if (this.m_headers.HTTPVersion.Equals("HTTP/1.1", StringComparison.OrdinalIgnoreCase)) { this.m_session.oFlags["X-Original-Host"] = string.Empty; } this.m_headers["Host"] = this.m_sHostFromURI; } this.m_sHostFromURI = null; } if (!this.m_headers.Exists("Host")) { this._freeRequestData(); return(false); } return(true); }
private bool ScanAssemblyForTranscoders(Assembly assemblyInput) { bool flag = false; bool boolPref = KProxyApplication.Prefs.GetBoolPref("KProxy.debug.extensions.verbose", false); try { if (!Utilities.KProxyMeetsVersionRequirement(assemblyInput, "Importers and Exporters")) { //KProxyApplication.Log.LogFormat("Assembly {0} did not specify a RequiredVersionAttribute. Aborting load of transcoders.", new object[] { assemblyInput.CodeBase }); return(false); } foreach (Type type in assemblyInput.GetExportedTypes()) { if ((!type.IsAbstract && type.IsPublic) && type.IsClass) { if (typeof(ISessionImporter).IsAssignableFrom(type)) { try { if (!this.AddToImportOrExportCollection(this.m_Importers, type)) { //KProxyApplication.Log.LogFormat("WARNING: SessionImporter {0} from {1} failed to specify any ImportExportFormat attributes.", new object[] { type.Name, assemblyInput.CodeBase }); } else { flag = true; if (boolPref) { //KProxyApplication.Log.LogFormat(" Added SessionImporter {0}", new object[] { type.FullName }); } } } catch (Exception exception) { KProxyApplication.DoNotifyUser(string.Format("[Kavprot Proxy] Failure loading {0} SessionImporter from {1}: {2}\n\n{3}\n\n{4}", new object[] { type.Name, assemblyInput.CodeBase, exception.Message, exception.StackTrace, exception.InnerException }), "Extension Load Error"); } } if (typeof(ISessionExporter).IsAssignableFrom(type)) { try { if (!this.AddToImportOrExportCollection(this.m_Exporters, type)) { //KProxyApplication.Log.LogFormat("WARNING: SessionExporter {0} from {1} failed to specify any ImportExportFormat attributes.", new object[] { type.Name, assemblyInput.CodeBase }); } else { flag = true; if (boolPref) { //KProxyApplication.Log.LogFormat(" Added SessionExporter {0}", new object[] { type.FullName }); } } } catch (Exception exception2) { KProxyApplication.DoNotifyUser(string.Format("[Kavprot Proxy] Failure loading {0} SessionExporter from {1}: {2}\n\n{3}\n\n{4}", new object[] { type.Name, assemblyInput.CodeBase, exception2.Message, exception2.StackTrace, exception2.InnerException }), "Extension Load Error"); } } } } } catch (Exception exception3) { KProxyApplication.DoNotifyUser(string.Format("[Kavprot Proxy] Failure loading Importer/Exporter from {0}: {1}", assemblyInput.CodeBase, exception3.Message), "Extension Load Error"); return(false); } return(flag); }
private bool ParseRequestForHeaders() { int num; int num2; int num3; if ((this.m_requestData == null) || (this.iEntityBodyOffset < 4)) { return(false); } this.m_headers = new HTTPRequestHeaders(KPCONFIG.oHeaderEncoding); byte[] arrRequest = this.m_requestData.GetBuffer(); Parser.CrackRequestLine(arrRequest, out num2, out num3, out num); if ((num2 < 1) || (num3 < 1)) { KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, false, "Incorrectly formed Request-Line"); return(false); } this.m_headers.HTTPMethod = Encoding.ASCII.GetString(arrRequest, 0, num2 - 1).ToUpper(); this.m_headers.HTTPVersion = Encoding.ASCII.GetString(arrRequest, (num2 + num3) + 1, ((num - num3) - num2) - 2).Trim().ToUpper(); int num4 = 0; if (arrRequest[num2] != 0x2f) { if (((num3 > 7) && (arrRequest[num2 + 4] == 0x3a)) && ((arrRequest[num2 + 5] == 0x2f) && (arrRequest[num2 + 6] == 0x2f))) { this.m_headers.UriScheme = Encoding.ASCII.GetString(arrRequest, num2, 4); num4 = num2 + 6; num2 += 7; num3 -= 7; } else if (((num3 > 8) && (arrRequest[num2 + 5] == 0x3a)) && ((arrRequest[num2 + 6] == 0x2f) && (arrRequest[num2 + 7] == 0x2f))) { this.m_headers.UriScheme = Encoding.ASCII.GetString(arrRequest, num2, 5); num4 = num2 + 7; num2 += 8; num3 -= 8; } else if (((num3 > 6) && (arrRequest[num2 + 3] == 0x3a)) && ((arrRequest[num2 + 4] == 0x2f) && (arrRequest[num2 + 5] == 0x2f))) { this.m_headers.UriScheme = Encoding.ASCII.GetString(arrRequest, num2, 3); num4 = num2 + 5; num2 += 6; num3 -= 6; } } if (num4 == 0) { if ((this.pipeClient != null) && this.pipeClient.bIsSecured) { this.m_headers.UriScheme = "https"; } else { this.m_headers.UriScheme = "http"; } } if (num4 > 0) { while (((num3 > 0) && (arrRequest[num2] != 0x2f)) && (arrRequest[num2] != 0x3f)) { num2++; num3--; } if (num3 == 0) { num2 = num4; num3 = 1; } int index = num4 + 1; int count = num2 - index; if (count > 0) { this.m_sHostFromURI = KPCONFIG.oHeaderEncoding.GetString(arrRequest, index, count); if ((this.m_headers.UriScheme == "ftp") && this.m_sHostFromURI.Contains("@")) { int length = this.m_sHostFromURI.LastIndexOf("@") + 1; this.m_headers._uriUserInfo = this.m_sHostFromURI.Substring(0, length); this.m_sHostFromURI = this.m_sHostFromURI.Substring(length); } } } byte[] dst = new byte[num3]; Buffer.BlockCopy(arrRequest, num2, dst, 0, num3); this.m_headers.RawPath = dst; string str = KPCONFIG.oHeaderEncoding.GetString(arrRequest, num, this.iEntityBodyOffset - num).Trim(); arrRequest = null; if (str.Length >= 1) { string[] sHeaderLines = str.Replace("\r\n", "\n").Split(new char[] { '\n' }); string sErrors = string.Empty; if (!Parser.ParseNVPHeaders(this.m_headers, sHeaderLines, 0, ref sErrors)) { KProxyApplication.HandleHTTPError(this.m_session, SessionFlags.ProtocolViolationInRequest, true, false, "Incorrectly formed request headers.\n" + sErrors); } } return(true); }