//public void SetValue(byte[] v) //{ // _type = VariantType.ByteString; // _valueByteArray = v; // _valueString = null; // _valueBitStream = null; //} public void SetValue(BitwiseStream v) { _type = VariantType.BitStream; _valueBitStream = v; _valueString = null; _valueByteArray = null; }
// TODO: Figure out how to not do this! private static byte[] ToByteArray(BitwiseStream data) { var length = (data.LengthBits + 7) / 8; var buffer = new byte[length]; var offset = 0; var count = buffer.Length; data.Seek(0, System.IO.SeekOrigin.Begin); int nread; while ((nread = data.Read(buffer, offset, count)) != 0) { offset += nread; count -= nread; } if (count != 0) { System.Diagnostics.Debug.Assert(count == 1); ulong bits; nread = data.ReadBits(out bits, 64); System.Diagnostics.Debug.Assert(nread > 0); System.Diagnostics.Debug.Assert(nread < 8); buffer[offset] = (byte)(bits << (8 - nread)); } return(buffer); }
protected override void OnOutput(BitwiseStream data) { int byteRead; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); Byte[] bytes; long data_length = data.Length; if ((this.Iteration % Counter) == 0) { this.OnClose(); this.setFileName(this.Iteration / Counter); this.OnOpen(); } if (data_length == 0) { return; } while ((byteRead = data.ReadByte()) != -1) { bytes = encoding.GetBytes(byteRead.ToString("X2")); stream.WriteByte(bytes[0]); stream.WriteByte(bytes[1]); } bytes = encoding.GetBytes("\n"); stream.WriteByte(bytes[0]); }
protected override BitwiseStream internalEncode(BitwiseStream data) { BitStream ret = new BitStream(); using (var bzip2 = new BZip2InputStream(data, true)) { try { // For some reason, Ionic decided the BZip2InputStream // should return -1 from Read() when EOF is reached. This // breaks Stream.CopyTo() as it expects 0 on EOF. // We need to use ReadByte() instead. int val; while ((val = bzip2.ReadByte()) != -1) { ret.WriteByte((byte)val); } } catch (Exception ex) { throw new SoftException("Could not BZip decompress data.", ex); } } ret.Seek(0, SeekOrigin.Begin); return(ret); }
protected override BitwiseStream internalEncode(BitwiseStream data) { BitStream ret = new BitStream(); BitWriter writer = new BitWriter(ret); int b; while ((b = data.ReadByte()) != -1) { if ((b >= 97 && b <= 122) || (b >= 65 && b <= 90) || (b >= 48 && b <= 57) || b == 32 || b == 44 || b == 46) { writer.WriteByte((byte)b); } else if (b <= 127) { writer.WriteString(string.Format("\\x{0:X2}", b)); } else { //NOTE: Doing at ASCII byte level.. might not not be necesarry here as the string is not typed... writer.WriteString(string.Format("\\u{0:X4}", b)); } } ret.Seek(0, System.IO.SeekOrigin.Begin); return(ret); }
protected void OnInvalidated(EventArgs e) { // Prevent infinite loops if (_invalidated) { return; } try { _invalidated = true; // Cause values to be regenerated next time they are // requested. We don't want todo this now as there could // be a series of invalidations that occur. _internalValue = null; _value = null; // Bubble this up the chain if (_parent != null) { _parent.Invalidate(); } if (_invalidatedEvent != null) { _invalidatedEvent(this, e); } } finally { _invalidated = false; } }
public void TestString <T>(T value, byte[] expected, int size, bool signed, bool isLittleEndian) { string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Peach>\n" + " <DataModel name=\"TheDataModel\">"+ " <Number name=\"TheNumber\" size=\""+ size + "\" value=\"" + value + "\"" + " signed=\""+ (signed ? "true" : "false") + "\"" + " endian=\""+ (isLittleEndian ? "little" : "big") + "\"/>" + " </DataModel>"+ "</Peach>"; PitParser parser = new PitParser(); Dom.Dom dom = parser.asParser(null, new MemoryStream(ASCIIEncoding.ASCII.GetBytes(xml))); Number num = dom.dataModels[0][0] as Number; Assert.AreEqual(signed, num.Signed); Assert.AreEqual(isLittleEndian, num.LittleEndian); if (!(value is string)) { if (signed) { Assert.AreEqual(value, (long)num.DefaultValue); } else { Assert.AreEqual(value, (ulong)num.DefaultValue); } } BitwiseStream val = num.Value; Assert.AreEqual(size, val.LengthBits); Assert.AreEqual(expected, val.ToArray()); }
private void DoHexParse(bool throws, string value, int size) { string template = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Peach>\n" + " <DataModel name=\"TheDataModel\">" + " <Number name=\"TheNumber\" size=\"{0}\" value=\"{1}\""+ " signed=\"true\" endian=\"big\" valueType=\"hex\"/>"+ " </DataModel>" + "</Peach>"; string xml = string.Format(template, size, value); PitParser parser = new PitParser(); if (throws) { Assert.Throws <PeachException>(delegate() { parser.asParser(null, new MemoryStream(ASCIIEncoding.ASCII.GetBytes(xml))); }); return; } Dom.Dom dom = parser.asParser(null, new MemoryStream(ASCIIEncoding.ASCII.GetBytes(xml))); Number num = dom.dataModels[0][0] as Number; Assert.AreEqual(true, num.Signed); Assert.AreEqual(false, num.LittleEndian); Assert.AreNotEqual(0, (long)num.DefaultValue); BitwiseStream val = num.Value; Assert.AreEqual(size, val.LengthBits); }
public void SetValue(string v) { _type = VariantType.String; _valueString = v; _valueBitStream = null; _valueByteArray = null; }
// NEW_BYTES_ZERO // private void generateNewBytesZero(BitwiseStream data, long size) { while (size-- > 0) { data.WriteByte(0); } }
protected override BitwiseStream internalEncode(BitwiseStream data) { if (data.Length % 2 != 0) { throw new SoftException("NetBiosDecode transformer internalEncode failed: Length must be divisible by two."); } var sb = new System.Text.StringBuilder((int)data.Length / 2); var nbs = new BitReader(data).ReadString(); for (int i = 0; i < nbs.Length; i += 2) { char c1 = nbs[i]; char c2 = nbs[i + 1]; var part1 = (c1 - 0x41) * 16; var part2 = (c2 - 0x41); sb.Append((Char)(part1 + part2)); } var ret = new BitStream(); var writer = new BitWriter(ret); writer.WriteString(sb.ToString()); ret.Seek(0, System.IO.SeekOrigin.Begin); return(ret); }
// NEW_BYTES_ALL_RANDOM // private void generateNewBytesAllRandom(BitwiseStream data, long size) { while (size-- > 0) { data.WriteByte((byte)context.Random.Next(256)); } }
/// <summary> /// Generate the final value of this data element /// </summary> /// <returns></returns> protected BitwiseStream GenerateValue() { ++GenerateCount; BitwiseStream value = null; if (_mutatedValue != null && mutationFlags.HasFlag(MutateOverride.TypeTransform)) { value = (BitwiseStream)_mutatedValue; } else { value = InternalValueToBitStream(); } if (_mutatedValue == null || !mutationFlags.HasFlag(MutateOverride.Transformer)) { if (_transformer != null) { value = _transformer.encode(value); } } return(value); }
protected override BitwiseStream internalEncode(BitwiseStream data) { //string format; //if (m_args.ContainsKey("eval")) // format = (string)(m_args["eval"]); return(data); }
protected static string ReadString(BitwiseStream data) { data.Seek(0, SeekOrigin.Begin); var rdr = new BitReader(data); var str = rdr.ReadString(Encoding.UTF8); return(str); }
public void SetValue(int v) { _type = VariantType.Int; _valueInt = v; _valueString = null; _valueBitStream = null; _valueByteArray = null; }
public void SetValue(double v) { _type = VariantType.Double; _valueDouble = v; _valueString = null; _valueBitStream = null; _valueByteArray = null; }
// NEW_BYTES_SINGLE_RANDOM // private void generateNewBytesSingleRandom(BitwiseStream data, long size) { byte val = (byte)(context.Random.Next(256)); while (size-- > 0) { data.WriteByte(val); } }
protected override void OnOutput(BitwiseStream data) { /* * An Abc Proto Packet is structured: * +-------+-------+-------+------- * [ Hdr ][ Length ] * [ Data ]... * * Hdr = 2 btyes, Length = 2 bytes (network byte order) * Data is variable length */ // Calculate the Length of the Entire Encapsulated Packet (Data + Abc Proto Hdr Len [2 bytes] + Abc Proto Len [2 bytes] int totalPktLen = (int)data.Length + 4; if (StrictLength) { /* * Here we're restricting the size of the mutated data. This is an important item to * note. Long string mutations are a major part of fuzzing, and by implementing this * sort of logic in our custom publisher, we're limiting our test cases. It might * be a better approach to ignore this length restriction.. but i'll leave that up * to the user via the StrictLength parameter. */ if (totalPktLen > 65535) { Logger.Debug("ABC Proto Max Packet Length Reached, capping at 65535"); totalPktLen = 65535; } if (totalPktLen <= 0) { Logger.Debug("ABC Proto Min PacketLength Reached, just setting to 4 to account for header and length fields"); totalPktLen = 4; } } // Abc Proto Header - 1234 indicates the start of an abcproto packet byte[] abcProtoHdr = { 0x12, 0x34 }; // Create a new buffer that will the final encapsulated packet var buffer = new byte[totalPktLen]; // Copy Abc Proto Header into our new buffer Array.Copy(abcProtoHdr, 0, buffer, 0, abcProtoHdr.Length); // Copy AbcProto Length into buffer after Abc Proto Hdr - We're also doing a bit of a int to short conversion here Array.Copy(BitConverter.GetBytes(totalPktLen - 4), 0, buffer, abcProtoHdr.Length, sizeof(ushort)); // Rearrange the Length to be in Big Endian (Network Byte Order) Array.Reverse(buffer, abcProtoHdr.Length, sizeof(ushort)); //Copy Data into buffer data.Read(buffer, abcProtoHdr.Length + sizeof(ushort), buffer.Length - 4); // Call the original OnOutput() using the buffer as our new BitStream base.OnOutput(new BitStream(buffer)); }
protected override void OnStart() { logger.Debug(">> OnStart"); _stream = Context.agentManager.CreateBitwiseStream(Agent); _publisher = Context.agentManager.CreatePublisher(Agent, Class, Args); _publisher.Iteration = Iteration; _publisher.IsControlIteration = IsControlIteration; _publisher.start(); }
public void CrackFlag1() { string xml = @" <Peach> <DataModel name=""TheDataModel""> <Flags size=""16""> <Flag position=""0"" size=""1""/> </Flags> <String value=""Hello World""/> </DataModel> <StateModel name=""TheState"" initialState=""Initial""> <State name=""Initial""> <Action type=""output""> <DataModel ref=""TheDataModel""/> </Action> </State> </StateModel> <Test name=""Default""> <StateModel ref=""TheState""/> <Publisher class=""StdoutHex""/> <Strategy class=""Sequential""/> </Test> </Peach> "; var pub = new Peach.Core.Test.Publishers.TestPublisher(); PitParser parser = new PitParser(); Dom.Dom dom = parser.asParser(null, new MemoryStream(ASCIIEncoding.ASCII.GetBytes(xml))); dom.tests[0].publishers[0] = pub; RunConfiguration config = new RunConfiguration(); config.singleIteration = true; Engine e = new Engine(null); e.startFuzzing(dom, config); BitwiseStream val = dom.dataModels[0].Value; Assert.NotNull(val); Assert.AreEqual(13, val.Length); Assert.AreEqual(13 * 8, val.LengthBits); pub.Stream.Seek(0, SeekOrigin.Begin); string results = Encoding.ASCII.GetString(pub.Stream.ToArray()); Assert.NotNull(results); string expected = "00000000 00 00 48 65 6C 6C 6F 20 57 6F 72 6C 64 ??Hello World " + Environment.NewLine; Assert.AreEqual(expected, results); }
public void OutputFlag() { string xml = @" <Peach> <DataModel name=""Model""> <Block name=""block""> <Flags name=""tlv"" size=""16"" endian=""big""> <Flag name=""type"" size=""7"" position=""0"" value=""1""/> <Flag name=""length"" size=""9"" position=""7"" value=""7""/> </Flags> <Blob name=""value"" valueType=""hex"" value=""ff""/> </Block> </DataModel> <StateModel name=""TheStateModel"" initialState=""initial""> <State name=""initial""> <Action type=""output""> <DataModel ref=""Model"" /> </Action> </State> </StateModel> <Test name=""Default""> <Strategy class=""Sequential""/> <StateModel ref=""TheStateModel""/> <Publisher class=""Null""/> </Test> </Peach> "; PitParser parser = new PitParser(); Dom.Dom dom = parser.asParser(null, new MemoryStream(ASCIIEncoding.ASCII.GetBytes(xml))); RunConfiguration config = new RunConfiguration(); config.singleIteration = true; Engine e = new Engine(null); e.startFuzzing(dom, config); BitwiseStream val = dom.dataModels[0].Value; Assert.NotNull(val); Assert.AreEqual(3, val.Length); Assert.AreEqual(3 * 8, val.LengthBits); byte[] buf = val.ToArray(); Assert.AreEqual(3, buf.Length); Assert.AreEqual(0x02, buf[0]); Assert.AreEqual(0x07, buf[1]); Assert.AreEqual(0xff, buf[2]); }
protected override BitwiseStream internalEncode(BitwiseStream data) { var s = new BitReader(data).ReadString(); var ds = System.Web.HttpUtility.HtmlDecode(s); var ret = new BitStream(); var writer = new BitWriter(ret); writer.WriteString(ds); ret.Seek(0, System.IO.SeekOrigin.Begin); return(ret); }
protected override void OnOutput(BitwiseStream data) { var request = new OnOutputRequest(); request.data = new byte[data.Length]; data.Read(request.data, 0, (int)data.Length); data.Position = 0; Send("output", JsonConvert.SerializeObject(request)); }
protected override void OnOutput(BitwiseStream data) { try { data.CopyTo(stream); } catch (IOException ioException) { throw new SoftException("Error, Console Output Too Large", ioException); } }
/// <summary> /// Send data /// </summary> /// <param name="data">Data to send/write</param> protected override void OnOutput(BitwiseStream data) { lock (_clientLock) { if (_client != null) { CloseClient(); } } CreateClient(data); }
protected override BitwiseStream internalEncode(BitwiseStream data) { BitStream ret = new BitStream(); using (var bzip2 = new BZip2OutputStream(ret, true)) { data.CopyTo(bzip2); } ret.Seek(0, SeekOrigin.Begin); return(ret); }
protected override BitwiseStream internalEncode(BitwiseStream data) { BitStream ret = new BitStream(); using (var strm = new GZipStream(ret, CompressionMode.Compress, true)) { data.CopyTo(strm); } ret.Seek(0, SeekOrigin.Begin); return(ret); }
public override BitwiseStream CreateBitwiseStream() { logger.Trace("CreateBitwiseStream"); OnCreateBitwiseStreamEvent(); BitwiseStream ret = null; PerformRemoting(delegate() { ret = proxy.CreateBitwiseStream(); }); return(ret); }
/// <summary> /// Encode data, will properly call any chained transformers. /// </summary> /// <param name="data">Data to encode</param> /// <returns>Returns encoded value or null if encoding is not supported.</returns> public virtual BitwiseStream encode(BitwiseStream data) { data.Seek(0, System.IO.SeekOrigin.Begin); data = internalEncode(data); if (anotherTransformer != null) { return(anotherTransformer.encode(data)); } return(data); }
protected override void OnOutput(BitwiseStream data) { BinaryReader br = new BinaryReader(data); int len = (int)data.Length; byte[] buffer; buffer = br.ReadBytes(len); try { pipeClient.Write(buffer, 0, len); } catch(IOException) { logger.Fatal("Named pipe server was closed"); // Console.WriteLine("Named pipe server was closed"); } }
protected override void OnOutput(BitwiseStream data) { if (Logger.IsDebugEnabled) Logger.Debug("\n\n" + Utilities.HexDump(data)); long count = data.Length; //var buffer = new byte[MaxMTU]; var buffer = new byte[CAN_MTU]; int size = data.Read(buffer, 0, buffer.Length); Pollfd[] fds = new Pollfd[1]; fds[0].fd = _socket.Handle; fds[0].events = PollEvents.POLLOUT; int expires = Environment.TickCount + Timeout; int wait = 0; for (;;) { try { wait = Math.Max(0, expires - Environment.TickCount); fds[0].revents = 0; int ret = Syscall.poll(fds, wait); if (UnixMarshal.ShouldRetrySyscall(ret)) continue; UnixMarshal.ThrowExceptionForLastErrorIf(ret); if (ret == 0) throw new TimeoutException(); if (ret != 1 || (fds[0].revents & PollEvents.POLLOUT) == 0) continue; //_socket.Write(buffer, 0, size); _socket.Write(buffer, 0, CAN_MTU); if (count != size) throw new Exception(string.Format("Only sent {0} of {1} byte packet.", size, count)); return; } catch (Exception ex) { Logger.Error("Unable to send CAN packet to {0}. {1}", Interface, ex.Message); throw new SoftException(ex); } } }
protected override void OnOutput(BitwiseStream data) { int byteRead; System.Text.ASCIIEncoding encoding= new System.Text.ASCIIEncoding(); Byte[] bytes; long data_length = data.Length; if((this.Iteration % Counter) == 0) { this.OnClose(); this.setFileName(this.Iteration / Counter); this.OnOpen(); } if(data_length == 0) return; while((byteRead = data.ReadByte()) != -1) { bytes = encoding.GetBytes(byteRead.ToString("X2")); stream.WriteByte(bytes[0]); stream.WriteByte(bytes[1]); } bytes = encoding.GetBytes("\n"); stream.WriteByte(bytes[0]); }
protected override void OnOutput(BitwiseStream data) { /* An Abc Proto Packet is structured: +-------+-------+-------+------- [ Hdr ][ Length ] [ Data ]... Hdr = 2 btyes, Length = 2 bytes (network byte order) Data is variable length */ // Calculate the Length of the Entire Encapsulated Packet (Data + Abc Proto Hdr Len [2 bytes] + Abc Proto Len [2 bytes] int totalPktLen = (int)data.Length + 4; if (StrictLength) { /* Here we're restricting the size of the mutated data. This is an important item to note. Long string mutations are a major part of fuzzing, and by implementing this sort of logic in our custom publisher, we're limiting our test cases. It might be a better approach to ignore this length restriction.. but i'll leave that up to the user via the StrictLength parameter. */ if (totalPktLen > 65535) { Logger.Debug("ABC Proto Max Packet Length Reached, capping at 65535"); totalPktLen = 65535; } if ( totalPktLen <= 0 ) { Logger.Debug("ABC Proto Min PacketLength Reached, just setting to 4 to account for header and length fields"); totalPktLen = 4; } } // Abc Proto Header - 1234 indicates the start of an abcproto packet byte[] abcProtoHdr = { 0x12, 0x34 } ; // Create a new buffer that will the final encapsulated packet var buffer = new byte[totalPktLen]; // Copy Abc Proto Header into our new buffer Array.Copy(abcProtoHdr, 0, buffer, 0, abcProtoHdr.Length); // Copy AbcProto Length into buffer after Abc Proto Hdr - We're also doing a bit of a int to short conversion here Array.Copy(BitConverter.GetBytes(totalPktLen - 4), 0, buffer, abcProtoHdr.Length, sizeof(ushort)); // Rearrange the Length to be in Big Endian (Network Byte Order) Array.Reverse(buffer, abcProtoHdr.Length, sizeof(ushort)); //Copy Data into buffer data.Read(buffer, abcProtoHdr.Length + sizeof(ushort), buffer.Length - 4); // Call the original OnOutput() using the buffer as our new BitStream base.OnOutput(new BitStream(buffer)); }