/// <summary> /// Constructor /// </summary> /// <param name="remoteEndPoint">EndPoint</param> public void ConnectTo(IPEndPoint remoteEndPoint) { Socket = TuringSocket.ConnectTo(remoteEndPoint); Socket.EnqueueMessages = true; Task = new Task <EFuzzingReturn>(InternalJob); }
public void TestTuringSocket() { using (TuringSocket server = TuringSocket.Bind(new IPEndPoint(IPAddress.Any, 9787))) { server.OnMessage += Server_OnMessage; using (TuringSocket client = TuringSocket.ConnectTo(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9787))) { client.OnMessage += Client_OnMessage; client.SendMessage(new OpenStreamMessageRequest() { }); for (int x = 0; x < 20 && !isOk; x++) { Thread.Sleep(1000); } } } if (!isOk) { throw (new System.Exception()); } }
public override void OnRun(TuringSocket socket, TuringAgentArgs e) { // Create client using (TcpClient ret = new TcpClient()) { // Try connect to server IAsyncResult result = ret.BeginConnect(ConnectTo.Address, ConnectTo.Port, null, null); bool success = result.AsyncWaitHandle.WaitOne(ConnectTimeout); ret.EndConnect(result); if (!success) { return; } // Flag as connected ConnectedOk = true; // Fuzzer stream using (TuringStream stream = new TuringStream(socket)) try { //Try send all we can using (Stream sr = ret.GetStream()) { stream.CopyTo(sr); sr.Flush(); } } catch //(Exception e) { } } }
/// <summary> /// Create process /// </summary> /// <param name="socket">Socket</param> /// <param name="e">Arguments</param> public ICrashDetector GetCrashDetector(TuringSocket socket, TuringAgentArgs e) { var ret = new Core.Detectors.Multi.OutputErrorProcessDetector(Process.Select(u => u.GetProcessStartInfo()).ToArray()); socket[ProcessPid] = ret; return(ret); }
/// <summary> /// Start logic /// </summary> public bool Start() { Stop(); _State = EFuzzerState.Started; _Socket = TuringSocket.Bind(Listen); _Socket.OnMessage += _Socket_OnMessage; return(true); }
/// <summary> /// Stop logic /// </summary> public bool Stop() { _State = EFuzzerState.Stopped; _Paused = false; if (_Socket != null) { _Socket.Dispose(); _Socket = null; } return(true); }
/// <summary> /// Search in socket variables /// </summary> /// <param name="socket">Socket</param> IEnumerable <ILogFile> GetLogsEntry(TuringSocket socket) { if (socket != null) { foreach (string key in socket.Variables.Key) { object o = socket.Variables[key]; if (o == null) { continue; } FuzzingLogInfo cfg = null; if (o is FuzzingStream) { FuzzingStream f = (FuzzingStream)o; cfg = new FuzzingLogInfo(f); } else { if (o is FuzzingLogInfo) { cfg = (FuzzingLogInfo)o; } } if (cfg != null) { string iz, dr; StringHelper.SplitInTwo(key, "=", out iz, out dr); // Save original input if (cfg.OriginalData != null) { yield return(new MemoryLogFile(dr + "_" + HashHelper.SHA1(cfg.OriginalData) + ".dat", cfg.OriginalData)); } if (!string.IsNullOrEmpty(cfg.Info)) { // Save info byte[] data = Encoding.UTF8.GetBytes(cfg.Info); yield return(new MemoryLogFile(dr + "_" + HashHelper.SHA1(data) + ".txt", data)); } if (cfg.Patch != null) { // Save patch byte[] bjson = Encoding.UTF8.GetBytes(cfg.Patch.ToJson()); yield return(new MemoryLogFile(dr + "_" + HashHelper.SHA1(bjson) + ".fpatch", bjson)); } } } } }
Stream Proxy_OnCreateStream(object sender, Stream stream, ESource owner) { TcpInvisibleProxy proxy = (TcpInvisibleProxy)sender; TuringSocket socket = (TuringSocket)proxy.Tag; switch (Type) { case EFuzzingType.Server: return(owner == ESource.Server ? stream : new TuringStream(socket, stream)); case EFuzzingType.Client: return(owner == ESource.Client ? stream : new TuringStream(socket, stream)); } return(stream); }
/// <summary> /// Create proxy ( auto-dispose whith socket ) /// </summary> /// <param name="socket">Socket</param> /// <param name="e">Arguments</param> public ICrashDetector GetCrashDetector(TuringSocket socket, TuringAgentArgs e) { var proxy = new TcpInvisibleProxy(ListenEndPoint, ConnectTo) { Tag = socket }; proxy.OnCreateStream += Proxy_OnCreateStream; socket[ProxyVarName] = proxy; proxy.Start(); // Create process return(new WERDetector(Process)); }
/// <summary> /// Constructor /// </summary> /// <param name="socket">Socket</param> /// <param name="stream">Stream</param> public TuringStream(TuringSocket socket, Stream stream) { _Base = stream; _Socket = socket; socket.EnqueueMessages = true; socket.SendMessage(new OpenStreamMessageRequest()); OpenStreamMessageResponse ret = socket.ReadMessage <OpenStreamMessageResponse>(); _StreamId = ret.Id; _CanRead = ret.CanRead; _CanSeek = ret.CanSeek; _CanTimeout = ret.CanTimeout; _CanWrite = ret.CanWrite; }
/// <summary> /// Check if can reconnect (¿its alive?) /// </summary> /// <param name="socket">Socket</param> public override bool GetItsAlive(TuringSocket socket, TuringAgentArgs e) { try { using (TcpClient ret = new TcpClient()) { ret.Connect(ConnectTo); //IAsyncResult result = ret.BeginConnect(ConnectTo.Address, ConnectTo.Port, null, null); //bool success = result.AsyncWaitHandle.WaitOne(ConnectTimeout); //ret.EndConnect(result); //if (success) return(true); } } catch { } // If sometime connected, and now not, are dead return(!ConnectedOk); }
public void OnRun(TuringSocket socket, TuringAgentArgs e) { var ret = (Core.Detectors.Multi.OutputErrorProcessDetector)socket[ProcessPid]; // Fuzzer stream using (var stream = new TuringStream(socket)) try { var data = new byte[4096]; var cdata = new char[data.Length]; // Try send all we can while (true) { var r = stream.Read(data, 0, data.Length); if (r > 0) { for (var x = 0; x < r; x++) { cdata[x] = (char)data[x]; } foreach (var process in ret.Process) { process.StandardInput.Write(cdata, 0, cdata.Length); process.StandardInput.Flush(); } } else { break; } } } catch //(Exception e) { } }
/// <summary> /// Save and return the save path /// </summary> /// <param name="sender">Socket</param> public FuzzerLog SaveResult(TuringSocket sender, out List <FuzzerStat <IFuzzingInput> > sinput, out List <FuzzerStat <IFuzzingConfig> > sconfig) { sinput = (List <FuzzerStat <IFuzzingInput> >)sender["INPUT"]; sconfig = (List <FuzzerStat <IFuzzingConfig> >)sender["CONFIG"]; if (ZipData != null && ZipData.Length > 0) { ZipHelper.AppendOrCreateZip(ref _ZipData, GetLogsEntry(sender).Select(u => u.GetZipEntry())); // Save if (ZipData != null) { string data = Path.Combine(Application.StartupPath, "Dumps", Result.ToString(), ExplotationResult.ToString(), HashHelper.SHA1(ZipData) + ".zip"); // Create dir if (!Directory.Exists(Path.GetDirectoryName(data))) { Directory.CreateDirectory(Path.GetDirectoryName(data)); } // Write file File.WriteAllBytes(data, ZipData); return(new FuzzerLog() { Input = StringHelper.List2String(sinput, "; "), Config = StringHelper.List2String(sconfig, "; "), Type = Result, ExplotationResult = ExplotationResult.ToString().Replace("_", " "), Origin = sender.EndPoint.Address, Path = data }); } } return(null); }
public bool IsCrashed(TuringSocket socket, out byte[] zipCrashData, out EExploitableResult exploitResult, delItsAlive isAlive, TuringAgentArgs e) { byte[] zip = null; zipCrashData = null; exploitResult = EExploitableResult.NOT_DUMP_FOUND; var errors = new List <ZipHelper.FileEntry>(); foreach (var pr in Process) { if (!pr.HasExited) { continue; } string error = pr.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(error) && !string.IsNullOrEmpty(error.Trim())) { errors.Add ( new ZipHelper.FileEntry("Error_" + pr.ProcessName + "_" + pr.Id.ToString() + ".txt", pr.StandardError.CurrentEncoding.GetBytes(error.Trim())) ); } } if (errors.Count > 0) { if (ZipHelper.AppendOrCreateZip(ref zip, errors) > 0 && zip != null && zip.Length > 0) { zipCrashData = zip; } } return(zipCrashData != null && zipCrashData.Length > 0); }
/// <summary> /// Create detector (First action) /// </summary> /// <param name="socket">Socket</param> /// <param name="e">Arguments</param> public virtual ICrashDetector GetCrashDetector(TuringSocket socket, TuringAgentArgs e) { return(null); }
/// <summary> /// Message logic /// </summary> /// <param name="sender">Socket</param> /// <param name="message">Message</param> void _Socket_OnMessage(TuringSocket sender, TuringMessage message) { if (_Paused) { // Send Paused signal //sender.SendMessage(new WaitMessage(TimeSpan.FromSeconds(1))); // Wait disable pause while (_Paused) { Thread.Sleep(500); } } TuringMessage response = new ExceptionMessage("Bad request"); try { switch (message.Type) { case ETuringMessageType.EndTask: { EndTaskMessage msg = (EndTaskMessage)message; List <FuzzerStat <IFuzzingInput> > sinput = null; List <FuzzerStat <IFuzzingConfig> > sconfig = null; // Log if are data FuzzerLog log = msg.SaveResult(sender, out sinput, out sconfig); if (log != null) { RaiseOnCrashLog(log); } // Send message of the end RaiseOnTestEnd(msg.Result, sinput == null ? null : sinput.ToArray(), sconfig == null ? null : sconfig.ToArray()); response = new BoolMessageResponse(true); break; } case ETuringMessageType.OpenStreamRequest: { Guid id = Guid.NewGuid(); OpenStreamMessageRequest msg = (OpenStreamMessageRequest)message; FuzzingStream stream = GetRandomStream(msg, sender, true, id); if (stream == null) { response = new ExceptionMessage("Not found stream"); break; } sender[id.ToString()] = stream; //if (msg.UseMemoryStream) // response = new OpenStreamMessageResponse(id) // { // CanRead = msg.CanRead, // CanSeek = msg.CanSeek, // CanTimeout = msg.CanTimeout, // CanWrite = msg.CanWrite // }; //else response = new OpenStreamMessageResponse(id) { CanRead = stream.CanRead, CanSeek = stream.CanSeek, CanTimeout = stream.CanTimeout, CanWrite = stream.CanWrite }; break; } case ETuringMessageType.GetStreamLengthRequest: { GetStreamLengthMessageRequest msg = (GetStreamLengthMessageRequest)message; FuzzingStream stream = (FuzzingStream)sender[msg.Id.ToString()]; if (stream == null) { response = new ExceptionMessage("No stream openned with id: " + msg.Id.ToString()); break; } response = new LongMessageResponse(stream.Length); break; } case ETuringMessageType.GetStreamPositionRequest: { GetStreamPositionMessageRequest msg = (GetStreamPositionMessageRequest)message; FuzzingStream stream = (FuzzingStream)sender[msg.Id.ToString()]; if (stream == null) { response = new ExceptionMessage("No stream openned with id: " + msg.Id.ToString()); break; } response = new LongMessageResponse(stream.Position); break; } case ETuringMessageType.SetStreamRequest: { SetStreamMessageRequest msg = (SetStreamMessageRequest)message; FuzzingStream stream = (FuzzingStream)sender[msg.Id.ToString()]; if (stream == null) { response = new ExceptionMessage("No stream openned with id: " + msg.Id.ToString()); break; } switch (msg.ValueType) { case SetStreamMessageRequest.EMode.Position: stream.Position = msg.Value; break; case SetStreamMessageRequest.EMode.Length: stream.SetLength(msg.Value); break; } response = new BoolMessageResponse(true); break; } case ETuringMessageType.FlushStreamRequest: { FlushStreamMessageRequest msg = (FlushStreamMessageRequest)message; FuzzingStream stream = (FuzzingStream)sender[msg.Id.ToString()]; if (stream == null) { response = new ExceptionMessage("No stream openned with id: " + msg.Id.ToString()); break; } stream.Flush(); response = new BoolMessageResponse(true); break; } case ETuringMessageType.CloseStreamRequest: { CloseStreamMessageRequest msg = (CloseStreamMessageRequest)message; FuzzingStream stream = (FuzzingStream)sender[msg.Id.ToString()]; if (stream == null) { response = new ExceptionMessage("No stream openned with id: " + msg.Id.ToString()); break; } // Save patch for dump sender[msg.Id.ToString()] = null; sender["Info=" + msg.Id.ToString()] = new FuzzingLogInfo(stream); try { stream.Close(); } catch { } try { stream.Dispose(); } catch { } response = new BoolMessageResponse(true); break; } case ETuringMessageType.ReadStreamRequest: { StreamReadMessageRequest msg = (StreamReadMessageRequest)message; FuzzingStream stream = (FuzzingStream)sender[msg.Id.ToString()]; if (stream == null) { response = new ExceptionMessage("No stream openned with id: " + msg.Id.ToString()); break; } if (msg.PreAppend != null) { stream.AppendToSource(msg.PreAppend, 0, msg.PreAppend.Length, msg.PreAppendReSeek); } byte[] data = new byte[msg.Length]; int r = stream.Read(data, 0, data.Length); if (r != data.Length) { Array.Resize(ref data, r); } response = new ByteArrayMessageResponse(data); break; } case ETuringMessageType.WriteStreamRequest: { StreamWriteMessageRequest msg = (StreamWriteMessageRequest)message; FuzzingStream stream = (FuzzingStream)sender[msg.Id.ToString()]; if (stream == null) { response = new ExceptionMessage("No stream openned with id: " + msg.Id.ToString()); break; } stream.Write(msg.Data, 0, msg.Data.Length); response = new BoolMessageResponse(true); break; } } } catch (Exception e) { response = new ExceptionMessage(e.ToString()); } sender.SendMessage(response); }
public bool GetItsAlive(TuringSocket socket, TuringAgentArgs e) => false;
FuzzingStream GetRandomStream(OpenStreamMessageRequest msg, TuringSocket sender, bool fuzzer, Guid id) { FuzzerStat <IFuzzingInput> sinput = RandomHelper.GetRandom(Inputs); MemoryStream binput = null; IFuzzingInput input = sinput == null ? null : sinput.Source; if (input != null) { if (sender["INPUT"] == null) { List <FuzzerStat <IFuzzingInput> > ls = new List <FuzzerStat <IFuzzingInput> >(); ls.Add(sinput); sender["INPUT"] = ls; } else { List <FuzzerStat <IFuzzingInput> > ls = (List <FuzzerStat <IFuzzingInput> >)sender["INPUT"]; ls.Add(sinput); } } if (input != null && !(input is EmptyFuzzingInput)) { binput = new MemoryStream(input.GetStream()); } else { binput = new MemoryStream(); } FuzzingStream ret = null; if (fuzzer) { FuzzerStat <IFuzzingConfig> sconfig = RandomHelper.GetRandom(Configurations); if (sconfig != null && sconfig != null) { IFuzzingConfig config = sconfig.Source; if (sconfig == null) { throw (new Exception("Require fuzzer configuration")); } if (sender["CONFIG"] == null) { List <FuzzerStat <IFuzzingConfig> > ls = new List <FuzzerStat <IFuzzingConfig> >(); ls.Add(sconfig); sender["CONFIG"] = ls; } else { List <FuzzerStat <IFuzzingConfig> > ls = (List <FuzzerStat <IFuzzingConfig> >)sender["CONFIG"]; ls.Add(sconfig); } ret = new FuzzingStream(binput, config); if (ret != null) { ret.InputName = sinput == null ? "None" : sinput.ToString(); ret.ConfigName = sconfig.ToString(); } } } if (ret == null) { // Disable Fuzzing if (binput == null) { ret = new FuzzingStream(new MemoryStream(), null) { InputName = sinput == null ? "None" : sinput.ToString() } } ; else { ret = new FuzzingStream(binput, null) { InputName = sinput == null ? "None" : sinput.ToString() } }; } //if (!msg.RequireStream) //{ // ret.CanRead = msg.CanRead; // ret.CanSeek = msg.CanSeek; // ret.CanTimeout = msg.CanTimeout; // ret.CanWrite = msg.CanWrite; //} return(ret); } }
public void OnRun(TuringSocket socket, TuringAgentArgs e) { }
/// <summary> /// Create process /// </summary> /// <param name="socket">Socket</param> /// <param name="e">Arguments</param> public override ICrashDetector GetCrashDetector(TuringSocket socket, TuringAgentArgs e) { return(new WERDetector(Process)); }
public bool GetItsAlive(TuringSocket socket, TuringAgentArgs e) { var proxy = (TcpInvisibleProxy)socket[ProxyVarName]; return(proxy != null && proxy.Running && proxy.ConnectedClients > 0); }
void Client_OnMessage(TuringSocket sender, TuringMessage message) { isOk = message is CloseStreamMessageRequest; }
void Server_OnMessage(TuringSocket sender, TuringMessage message) { sender.SendMessage(new CloseStreamMessageRequest() { }); }
/// <summary> /// Return if are WER file /// </summary> /// <param name="socket">Socket</param> /// <param name="zipCrashData">Crash data</param> /// <param name="isAlive">IsAlive</param> public bool IsCrashed(TuringSocket socket, out byte[] zipCrashData, out EExploitableResult exploitResult, delItsAlive isAlive, TuringAgentArgs e) { zipCrashData = null; if (_Process == null) { exploitResult = EExploitableResult.NOT_DUMP_FOUND; return(false); } // Wait for exit var isBreak = false; if (_Process != null) { var miniwait = TimeSpan.FromMilliseconds(100); foreach (var p in _Process) { try { var ts = TimeSpan.FromMilliseconds(p.StartInfo.ExitTimeout.TotalMilliseconds); while (ts.TotalMilliseconds > 0 && (isAlive == null || isAlive.Invoke(socket, e)) && !p.HasExited) { p.WaitForExit((int)miniwait.TotalMilliseconds); ts = ts.Subtract(miniwait); } } catch { } // Check store location for changes if (!isBreak && p.ItsChangedStoreLocation()) { isBreak = true; } } } // Courtesy wait Thread.Sleep(500); // Search logs var fileAppend = new List <ILogFile>(); if (_FileNames != null) { foreach (var f in _FileNames) { var l = new LogFile(f); if (l.TryLoadFile(TimeSpan.FromSeconds(isBreak ? 5 : 2))) { fileAppend.Add(l); } } } // If its alive kill them if (_Process != null) { foreach (var p in _Process) { try { p.KillProcess(); } catch { } } } // Check exploitability exploitResult = EExploitableResult.NOT_DUMP_FOUND; for (int x = 0, m = fileAppend.Count; x < m; x++) { var dump = (LogFile)fileAppend[x]; if (dump.FileName.ToLowerInvariant().EndsWith(".dmp")) { exploitResult = WinDbgHelper.CheckMemoryDump(dump.Path, out string log); if (!string.IsNullOrEmpty(log)) { fileAppend.Add(new MemoryLogFile("exploitable.log", Encoding.UTF8.GetBytes(log))); } } } // Compress to zip byte[] zip = null; if (ZipHelper.AppendOrCreateZip(ref zip, fileAppend.Select(u => u.GetZipEntry())) > 0 && zip != null && zip.Length > 0) { zipCrashData = zip; } return(zipCrashData != null && zipCrashData.Length > 0); }
/// <summary> /// Return if its alive /// </summary> /// <param name="socket">Socket</param> /// <param name="e">Arguments</param> public virtual bool GetItsAlive(TuringSocket socket, TuringAgentArgs e) { return(false); }
public override void OnRun(TuringSocket socket, TuringAgentArgs e) { }
/// <summary> /// Constructor /// </summary> /// <param name="socket">Socket</param> public TuringStream(TuringSocket socket) : this(socket, null) { }
/// <summary> /// Get Task of agent /// </summary> /// <param name="socket">Socket</param> /// <param name="e">Arguments</param> public virtual void OnRun(TuringSocket socket, TuringAgentArgs e) { throw (new NotImplementedException()); }
/// <summary> /// Return crashed data /// </summary> /// <param name="socket">Socket</param> /// <param name="zipCrashData">Crash data</param> /// <param name="exploitResult">Explotation result</param> /// <param name="isAlive">Its alive</param> /// <param name="e">Arguments</param> public virtual bool IsCrashed(TuringSocket socket, out byte[] zipCrashData, out EExploitableResult exploitResult, ITuringMachineAgent.delItsAlive isAlive, TuringAgentArgs e) { throw new NotImplementedException(); }