Beispiel #1
0
        // 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)
        {
            /*
             *  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));
        }
Beispiel #3
0
        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));
        }
Beispiel #4
0
        protected override BitwiseStream internalEncode(BitwiseStream data)
        {
            byte[] buf = new byte[data.Length];
            data.Read(buf, 0, (int)data.Length);


            byte[]       retbuf = new byte[Huffman.ENCODER.GetEncodedLength(buf)];
            MemoryStream ms     = new MemoryStream(retbuf);

            using (BinaryWriter bw = new BinaryWriter(ms))
                Huffman.ENCODER.Encode(bw, buf);

            return(new BitStream(retbuf));
        }
        protected override void OnOutput(BitwiseStream data)
        {
            System.Diagnostics.Debug.Assert(_socket != null);

            if (Logger.IsDebugEnabled)
            {
                Logger.Debug("\n\n" + Utilities.HexDump(data));
            }

            long count  = data.Length;
            var  buffer = new byte[MaxSendSize];
            int  size   = data.Read(buffer, 0, buffer.Length);

            try
            {
                FilterOutput(buffer, 0, size);

                var ar = _socket.BeginSendTo(buffer, 0, size, SocketFlags.None, _remoteEp, null, null);
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(Timeout)))
                {
                    throw new TimeoutException();
                }
                size = _socket.EndSendTo(ar);

                if (count != size)
                {
                    throw new Exception(string.Format("Only sent {0} of {1} byte {2} packet.", size, count, _type));
                }
            }
            catch (Exception ex)
            {
                if (ex is TimeoutException)
                {
                    Logger.Debug("{0} packet not sent to {1}:{2} in {3}ms, timing out.",
                                 _type, Host, Port, Timeout);
                }
                else
                {
                    Logger.Error("Unable to send {0} packet to {1}:{2}. {3}",
                                 _type, Host, Port, ex.Message);
                }

                throw new SoftException(ex);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Returns a new BitStream composed of the first 'length' bytes of src.
        /// When done, src is positioned at length bytes, and the returned
        /// BitStream is positioned at SeekOrigin.End
        /// </summary>
        /// <param name="src"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private BitStream copyBytes(BitwiseStream src, long length)
        {
            if (length > src.Length)
            {
                throw new ArgumentOutOfRangeException("length");
            }

            var buf = new byte[BitwiseStream.BlockCopySize];
            var ret = new BitStream();

            src.Seek(0, SeekOrigin.Begin);

            while (length > 0)
            {
                int len = (int)Math.Min(length, buf.Length);
                len = src.Read(buf, 0, len);
                ret.Write(buf, 0, len);
                length -= len;
            }

            return(ret);
        }
Beispiel #7
0
        public static byte[] ToArray(this BitwiseStream bs)
        {
            long pos = bs.PositionBits;

            bs.SeekBits(0, SeekOrigin.Begin);

            int len    = 0;
            int count  = (int)((bs.LengthBits + 7) / 8);
            int offset = 0;

            byte[] buffer = new byte[count];

            do
            {
                len     = bs.Read(buffer, offset, count);
                offset += len;
                count  -= len;
            }while (len != 0);

            if (count != 0)
            {
                ulong remain;
                len = bs.ReadBits(out remain, 64);

                System.Diagnostics.Debug.Assert(count == 1);
                System.Diagnostics.Debug.Assert(len < 8);
                System.Diagnostics.Debug.Assert(len > 0);

                buffer[offset] = (byte)(remain << (8 - len));
                ++offset;
                --count;
            }

            bs.SeekBits(pos, SeekOrigin.Begin);
            return(buffer);
        }
Beispiel #8
0
        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);
                }
            }
        }
Beispiel #9
0
        private static string BitsToString(BitwiseStream bs)
        {
            if (bs.LengthBits == 0)
            {
                return("");
            }

            byte[] buf = new byte[32];
            long   pos = bs.PositionBits;

            bs.SeekBits(0, System.IO.SeekOrigin.Begin);
            int len = bs.Read(buf, 0, buf.Length);

            StringBuilder ret = new StringBuilder();

            if (len > 0)
            {
                ret.AppendFormat("{0:x2}", buf[0]);
            }

            int end = Math.Min(len, buf.Length);

            for (int i = 1; i < end; ++i)
            {
                ret.AppendFormat(" {0:x2}", buf[i]);
            }

            long lengthBits = bs.LengthBits;

            if ((len * 8) < lengthBits)
            {
                if (len < buf.Length)
                {
                    ulong tmp;
                    int   bits = bs.ReadBits(out tmp, 64);
                    System.Diagnostics.Debug.Assert(bits < 8);

                    tmp <<= (8 - bits);

                    if (len != 0)
                    {
                        ret.Append(" ");
                    }

                    ret.AppendFormat("{0:x2}", tmp);
                    ret.AppendFormat(" (Len: {0} bits)", lengthBits);
                }
                else if ((lengthBits % 8) == 0)
                {
                    ret.AppendFormat(".. (Len: {0} bytes)", lengthBits / 8);
                }
                else
                {
                    ret.AppendFormat(".. (Len: {0} bits)", lengthBits);
                }
            }

            bs.SeekBits(pos, System.IO.SeekOrigin.Begin);

            return(ret.ToString());
        }
        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)); 
            
        }
Beispiel #11
0
        protected override void OnOutput(BitwiseStream data)
        {
            IAsyncResult ar     = null;
            int          offset = 0;
            int          length = 0;

            try
            {
                while (true)
                {
                    lock (_clientLock)
                    {
                        //Check to make sure buffer has been initilized before continuing.
                        if (_client == null)
                        {
                            // First time through, propigate error
                            if (ar == null)
                            {
                                throw new PeachException("Error on data output, the client is not initalized.");
                            }

                            // Client has been closed!
                            return;
                        }

                        if (Logger.IsDebugEnabled && ar == null)
                        {
                            Logger.Debug("\n\n" + Utilities.HexDump(data));
                        }

                        if (ar != null)
                        {
                            offset += ClientEndWrite(ar);
                        }

                        if (offset == length)
                        {
                            offset = 0;
                            length = data.Read(_sendBuf, 0, _sendBuf.Length);

                            if (length == 0)
                            {
                                return;
                            }
                        }

                        ar = ClientBeginWrite(_sendBuf, offset, length - offset, null, null);
                    }

                    if (SendTimeout == 0)
                    {
                        ar.AsyncWaitHandle.WaitOne();
                    }
                    else if (!ar.AsyncWaitHandle.WaitOne(SendTimeout))
                    {
                        throw new TimeoutException();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("output: Error during send.  " + ex.Message);
                throw new SoftException(ex);
            }
        }
Beispiel #12
0
		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);
				}
			}
		}