private void ReadPackets(IAsyncResult ar) { ReadObj obj = (ReadObj)ar.AsyncState; Socket client = obj.s; byte[] buffer = obj.buffer; int read = -1; try { read = client.EndReceive(ar); } catch (Exception) { KillSocket(client, !stopping); ctx.LogMod.Log("[DISCONNECT] Client Disconnected from server", VLogger.LogLevel.information); return; } if (read == 0) { try { if (client.Connected) { client.BeginReceive(obj.buffer, 0, obj.buffer.Length, SocketFlags.None, new AsyncCallback(ReadPackets), obj); } } catch (Exception e) { KillSocket(client, !stopping); Console.WriteLine("Client aborted session!" + Environment.NewLine + e.Message); } return; } string text = Encoding.ASCII.GetString(buffer, 0, read); Request r; bool sslHandlerStarted = false; if (obj.request != null) { if (obj.request.notEnded) { string des = obj.request.full; des += text; r = new Request(des); } else { r = new Request(text); } } else { r = new Request(text); } if (!r.notEnded && !r.bogus) { ctx.LogMod.Log("<target> [HTTP]", VLogger.LogLevel.request, r); Tunnel t = new Tunnel(Tunnel.Mode.HTTP, httpMode, httpsMode, ctx, client, console); t.CreateMinimalTunnel(r); if (t.sslRead && httpMode == Mode.MITM) //Handle MITM SSL Connections { string host = t.GetHost(); NetworkStream clientNS = new NetworkStream(client); VSslHandler vsh = new VSslHandler(ctx, console); VSslHandler.Error errCode = vsh.InitSslStream(clientNS, host); if (errCode != VSslHandler.Error.Success) { ctx.LogMod.Log("Init SSL Stream failed\r\nError Code: " + errCode.ToString(), VLogger.LogLevel.error); } else { sslHandlerStarted = true; vsh.InitAsyncRead(); console.Debug("SSL Tunnel MITM Started"); return; } } else if (t.sslRead && httpsMode == Mode.forward) //Handle HTTPS normal { t.InitHTTPS(client); return; } if (httpMode == Mode.MITM) //Handle HTTP MITM { Request httpSend = new Request(t.FormatRequest(r)); Tunnel.Send("", Tunnel.Mode.HTTP, ctx, httpSend, new NetworkStream(client)); } else if (httpMode == Mode.forward) //Handle HTTP normal { t.SendHTTP(r, client); return; } } else if (r.notEnded) { obj.request = r; } Array.Clear(buffer, 0, buffer.Length); try { if (client.Connected && !sslHandlerStarted) { client.BeginReceive(obj.buffer, 0, obj.buffer.Length, SocketFlags.None, new AsyncCallback(ReadPackets), obj); } } catch (Exception e) { KillSocket(client, !stopping); Console.WriteLine("Client aborted session!" + Environment.NewLine + e.Message); } }
private static void BISend(Request r, NetworkStream ns, VSslHandler vSsl, Mode Protocol, Form1 ctx) { Task getPage = new Task(new Action(() => { if (ctx.mitmHttp.started) { ctx.mitmHttp.DumpRequest(r); } string hostString = r.headers["Host"]; string target = r.target.Replace(hostString, string.Empty); if (Protocol == Tunnel.Mode.HTTPs) { hostString = "https://" + hostString + target; } else { hostString = "http://" + hostString + target; } HttpClientHandler handler = new HttpClientHandler() { UseProxy = false, Proxy = null }; HttpClient client = new HttpClient(handler); HttpRequestMessage hrm = new HttpRequestMessage { Method = new HttpMethod(r.method), RequestUri = new Uri(hostString) }; foreach (KeyValuePair <string, string> kvp in r.headers.Items) { hrm.Headers.Add(kvp.Key, kvp.Value); } if (r.htmlBody != null) { hrm.Content = new StringContent(r.htmlBody); } client.SendAsync(hrm).ContinueWith(responseTask => { try { HttpResponseMessage resp = responseTask.Result; byte[] content = new byte[0]; string strContent = ""; int statusCode = 0; string statusDescription = ""; string version = ""; VDictionary headers = new VDictionary(); Task getContent = new Task(() => { content = resp.Content.ReadAsByteArrayAsync().Result; foreach (KeyValuePair <string, IEnumerable <string> > x in resp.Content.Headers) { string name = x.Key; if (name == "Content-Length") { ctx.ConMod.Debug("Got content length"); } string value = ""; foreach (string val in x.Value) { value += val + ";"; } value = value.Substring(0, value.Length - 1); headers.Add(name, value); } ctx.ConMod.Debug("Headers in content" + resp.Content.Headers.Count()); strContent = Encoding.ASCII.GetString(content); }); Task getHeaders = new Task(() => { foreach (KeyValuePair <string, IEnumerable <string> > x in resp.Headers) { string name = x.Key; string value = ""; foreach (string val in x.Value) { value += val + ";"; } value = value.Substring(0, value.Length - 1); headers.Add(name, value); } }); Task getRest = new Task(() => { statusCode = (int)resp.StatusCode; statusDescription = resp.ReasonPhrase; version = "HTTP/" + resp.Version.ToString(); }); getContent.Start(); getHeaders.Start(); getRest.Start(); Task.WaitAll(getContent, getHeaders, getRest); Response _r = new Response(statusCode, statusDescription, version, headers, strContent, content, ctx.ConMod, ctx.mitmHttp); _r.SetManager(ctx.vf); _r.BindFilter("resp_mime", "mime_white_list"); _r.BindFilter("resp_mime_block", "mime_skip_list"); _r.CheckMimeAndSetBody(); if (ctx.mitmHttp.started) { string _target = r.target; if (_target.Contains("?")) { _target = _target.Substring(0, _target.IndexOf("?")); } ctx.mitmHttp.DumpResponse(_r, _target); } //ConMod.Debug("Before sending to client"); if (Protocol == Tunnel.Mode.HTTPs) { _r.Deserialize(null, r, vSsl); } else { _r.Deserialize(ns, r); } } catch (Exception) { //ctx.ConMod.Debug("Error: " + ex.ToString() + "\r\nStackTrace:\r\n" + ex.StackTrace); //ctx.ConMod.Debug($"On resource: {r.target}"); } }); })); getPage.Start(); }
public void Deserialize(NetworkStream ns, Request req, VSslHandler vsh = null) { string sResult = version + " " + statusCode + " " + httpMessage + "\r\n"; int ctLength = 0; //edit bodyText here VDecoder vd = new VDecoder(); if (headers.ContainsKey("Content-Length") && headers["Content-Length"] != "0" && headers["Content-Length"] != null) { if (mitm != null && mitm.started) //MITM Media and Text injection { if (bodyText != "") { if (mitm.CheckBody(bodyText)) { return; } string cType = (headers.ContainsKey("Content-Type")) ? headers["Content-Type"] : null; if (cType != null) { string nt = ""; nt = mitm.Inject(bodyText, headers["Content-Type"]); if (nt != null) { bodyText = nt; } } } else { byte[] n = mitm.MediaRewrite(this, req); if (n != null) { body = n; } } } if (bodyText != "" && headers.ContainsKey("Content-Encoding")) { Array.Clear(body, 0, body.Length); byte[] toCode = vd.EncodeCharset(headers["Content-Type"], bodyText); string enc = headers["Content-Encoding"]; if (enc == "gzip") { body = vd.EncodeGzip(toCode); } else if (enc == "deflate") { body = vd.EncodeDeflate(toCode); } else if (enc == "br") { body = vd.EncodeBrotli(toCode); } Array.Clear(toCode, 0, toCode.Length); } else if (bodyText == "" && headers.ContainsKey("Content-Encoding")) { string enc = headers["Content-Encoding"]; if (enc == "gzip") { body = vd.EncodeGzip(body); } else if (enc == "deflate") { body = vd.EncodeDeflate(body); } else if (enc == "br") { body = vd.EncodeBrotli(body); } } else if (bodyText != "" && !headers.ContainsKey("Content-Encoding")) { body = vd.EncodeCharset(headers["Content-Type"], bodyText); } ctLength = body.Length; } foreach (KeyValuePair <string, string> kvp in headers.Items) { string line = ""; if (kvp.Key == "Content-Length" && ctLength > 0) { line = "Content-Length: " + ctLength + "\r\n"; } else if (kvp.Key == "Transfer-Encoding" && kvp.Value == "chunked" && ctLength > 0) { // insert the content-length and skip the transfer-encoding header, because we concatanated it. line = "Content-Length: " + ctLength.ToString() + "\r\n"; } else { line = kvp.Key + ": " + kvp.Value + "\r\n"; } sResult += line; } //console.Debug($"{req.target} - responded with content-type: {headers["Content-Type"]}"); sResult += "\r\n"; byte[] text = Encoding.ASCII.GetBytes(sResult); if (vsh == null) { ns.Write(text, 0, text.Length); if (ctLength > 0) { ns.Write(body, 0, body.Length); } ns.Flush(); } else { //console.Debug("Handler " + vsh.HandlerID + " receiving " + (headers.ContainsKey("Content-Type") ? headers["Content-Type"] : "No content type sent")); vsh.WriteSslStream(text); if (ctLength > 0) { vsh.WriteSslStream(body); } vsh.FlushSslStream(); } }
public static void Send(string data, Mode Protocol, Form1 context, Request r = null, NetworkStream targetHttp = null, VSslHandler targetHttps = null) { //ConMod.Debug("Send string"); BISend(r, targetHttp, targetHttps, Protocol, context); }