コード例 #1
0
 public PacketId GetPacketId(IPacket pck)
 {
     PacketId id;
     if (!TypeToId.TryGetValue(pck.GetType(), out id))
         throw new InvalidOperationException("Packet type is missing packet id: " + pck.GetType().FullName);
     return id;
 }
コード例 #2
0
        private void OnClientRead(byte[] e)
        {
            if (ClientRead != null)
            {
                try
                {
                    using (MemoryStream deserialized = new MemoryStream(e))
                    {
                        IPacket packet = Serializer.DeserializeWithLengthPrefix <IPacket>(deserialized, PrefixStyle.Fixed32);

                        if (packet.GetType() == typeof(KeepAliveResponse))
                        {
                            _parentServer.HandleKeepAlivePacket((KeepAliveResponse)packet, this);
                        }

                        else if (packet.GetType() == typeof(KeepAlive))
                        {
                            new KeepAliveResponse()
                            {
                                TimeSent = ((KeepAlive)packet).TimeSent
                            }
                        }
                        .Execute(this);

                        else
                        {
                            ClientRead(this, packet);
                        }
                    }
コード例 #3
0
ファイル: WorkerNetwork.cs プロジェクト: bluetsys/zgrid
        public void ProcessPacket(IPacket packet)
        {
            if (!IsChannelOpen())
            {
                return;
            }

            if (packet == null)
            {
                return;
            }

            var handler = _currentHandler;

            if (handler == null)
            {
                Logger.Debug($"Received packet '{packet.GetType().FullName}' has no any handlers");
                return;
            }

            try {
                packet.Handle(handler);
            } catch (Exception e) {
                Logger.Error($"Unable to handle packet '{packet.GetType().FullName}', unexpected error", e);
            }
        }
コード例 #4
0
ファイル: Packets.cs プロジェクト: Regenhardt/Librelancer
        public static void CheckRegistered(IPacket p)
        {
            var idx = packetTypes.IndexOf(p.GetType());

            if (idx == -1)
            {
                throw new Exception($"Packet type not registered {p.GetType().Name}");
            }
        }
コード例 #5
0
 private void HandlePacket(RemoteClient client, IPacket packet)
 {
     if (!PacketHandlers.ContainsKey(packet.GetType()))
     {
         return;
     }
     //throw new InvalidOperationException("No packet handler registered for 0x" + packet.Id.ToString("X2"));
     PacketHandlers[packet.GetType()](client, this, packet);
 }
コード例 #6
0
ファイル: Packets.cs プロジェクト: Regenhardt/Librelancer
        public static void Write(NetDataWriter message, IPacket p)
        {
            var pkt = packetTypes.IndexOf(p.GetType());

            if (pkt == -1)
            {
                throw new Exception($"Packet type not registered {p.GetType().Name}");
            }
            message.PutVariableUInt32((uint)pkt);
            p.WriteContents(message);
        }
コード例 #7
0
ファイル: root.cs プロジェクト: iggyvolz/NetrekGodot
    public static string ToString(this IPacket packet, bool _)
    {
        StringBuilder builder = new StringBuilder();

        builder.AppendLine(packet.GetType().ToString());
        foreach (FieldInfo f in packet.GetType().GetFields())
        {
            builder.AppendLine($"{f.Name}: {f.GetValue(packet)}");
        }
        return(builder.ToString());
    }
コード例 #8
0
 public void HandlePacket(IPacket packet)
 {
     if (_handlers.TryGetValue(packet.GetType(), out var handler))
     {
         handler(packet);
     }
     else
     {
         Console.WriteLine("No handler found for packet type " + packet.GetType().FullName);
     }
 }
コード例 #9
0
        protected virtual async Task <byte[]> WritePacketAsync(IPacket packet)
        {
            var memoryStream = new MemoryStream();
            var writer       = new BinaryWriter(memoryStream);

            writer.Write(packet.GetType().Assembly.FullName);
            writer.Write(packet.GetType().ToString());

            await packet.WriteAsync(memoryStream);

            var packetData = memoryStream.ToArray();

            return(packetData);
        }
コード例 #10
0
        public string Serialize(IPacket packet)
        {
            string header = packet.GetType().GetCustomAttribute <PacketHeaderAttribute>()?.Header;

            if (header == null)
            {
                _logger.Error($"Could not find header for {packet.GetType().FullName}");
                return(null);
            }

            string content = _conversionFactory.ToString(packet, packet.GetType());

            _logger.Debug($"Successfully serialized {packet.GetType().FullName}");
            return((header + " " + content).Trim());
        }
コード例 #11
0
        public Packet(Script script, IPacket packet)
            : base(script.Engine)
        {
            var props = TypeDictionary.GetRecord(packet.GetType());

            DefineProperty("id", new PropertyDescriptor(
                               (int)packet.Id,
                               Jurassic.Library.PropertyAttributes.Enumerable | Jurassic.Library.PropertyAttributes.Sealed),
                           true
                           );

            foreach (var prop in props)
            {
                var info = prop.Property;

                string name = info.Name;
                name = name[0].ToString().ToLower() + name.Substring(1);

                this.DefineProperty(
                    name,
                    new PropertyDescriptor(
                        new GetProperty(script, packet, info),
                        new SetProperty(script, packet, info),
                        Jurassic.Library.PropertyAttributes.Enumerable | Jurassic.Library.PropertyAttributes.Sealed),
                    true);
            }
        }
コード例 #12
0
        public static void WritePacket(BinaryWriter s, IPacket packet)
        {
            var id = Array.FindIndex(Packets, type => type == packet.GetType());

            s.Write((byte)id);
            SerializePacket(s, packet);
        }
コード例 #13
0
        public void when_reading_bytes_then_notifies_packet(string packetPath, Type packetType)
        {
            MqttConfiguration configuration = new MqttConfiguration {
                WaitTimeoutSecs = 1
            };
            Subject <byte[]> receiver = new Subject <byte[]>();
            Mock <IMqttChannel <byte[]> > innerChannel = new Mock <IMqttChannel <byte[]> >();

            innerChannel.Setup(x => x.ReceiverStream).Returns(receiver);

            object expectedPacket         = Activator.CreateInstance(packetType);
            Mock <IPacketManager> manager = new Mock <IPacketManager>();

            manager.Setup(x => x.GetPacketAsync(It.IsAny <byte[]>()))
            .Returns(Task.FromResult <IPacket>((IPacket)expectedPacket));

            PacketChannel channel = new PacketChannel(innerChannel.Object, manager.Object, configuration);

            IPacket receivedPacket = default;

            channel.ReceiverStream.Subscribe(packet =>
            {
                receivedPacket = packet;
            });

            packetPath = Path.Combine(Environment.CurrentDirectory, packetPath);

            byte[] readPacket = Packet.ReadAllBytes(packetPath);

            receiver.OnNext(readPacket);

            Assert.NotNull(receivedPacket);
            packetType.Should().Be(receivedPacket.GetType());
        }
コード例 #14
0
        public static void HandleCommand(Client client, IPacket packet)
        {
            var type = packet.GetType();

            if (type == typeof(ReverseProxyConnect))
            {
                client.ConnectReverseProxy((ReverseProxyConnect)packet);
            }
            else if (type == typeof(ReverseProxyData))
            {
                ReverseProxyData   dataCommand = (ReverseProxyData)packet;
                ReverseProxyClient proxyClient = client.GetReverseProxyByConnectionId(dataCommand.ConnectionId);

                if (proxyClient != null)
                {
                    proxyClient.SendToTargetServer(dataCommand.Data);
                }
            }
            else if (type == typeof(ReverseProxyDisconnect))
            {
                ReverseProxyDisconnect disconnectCommand = (ReverseProxyDisconnect)packet;
                ReverseProxyClient     socksClient       = client.GetReverseProxyByConnectionId(disconnectCommand.ConnectionId);

                if (socksClient != null)
                {
                    socksClient.Disconnect();
                }
            }
        }
コード例 #15
0
        // Token: 0x0600056C RID: 1388 RVA: 0x00012E8C File Offset: 0x0001108C
        public static void HandleCommand(Client client, IPacket packet)
        {
            Type type = packet.GetType();

            if (type == typeof(ReverseProxyConnect))
            {
                client.ConnectReverseProxy((ReverseProxyConnect)packet);
                return;
            }
            if (type == typeof(ReverseProxyData))
            {
                ReverseProxyData   reverseProxyData           = (ReverseProxyData)packet;
                ReverseProxyClient reverseProxyByConnectionId = client.GetReverseProxyByConnectionId(reverseProxyData.ConnectionId);
                if (reverseProxyByConnectionId != null)
                {
                    reverseProxyByConnectionId.SendToTargetServer(reverseProxyData.Data);
                    return;
                }
            }
            else if (type == typeof(ReverseProxyDisconnect))
            {
                ReverseProxyDisconnect reverseProxyDisconnect      = (ReverseProxyDisconnect)packet;
                ReverseProxyClient     reverseProxyByConnectionId2 = client.GetReverseProxyByConnectionId(reverseProxyDisconnect.ConnectionId);
                if (reverseProxyByConnectionId2 != null)
                {
                    reverseProxyByConnectionId2.Disconnect();
                }
            }
        }
コード例 #16
0
        public void ProcessPacket(IPacket packet)
        {
            FLLog.Info("Server", "Got packet of type " + packet.GetType());
            switch (packet)
            {
            case CharacterListActionPacket c:
                ListAction(c);
                break;

            case LaunchPacket l:
                Launch();
                break;

            case EnterLocationPacket lc:
                msnRuntime?.EnterLocation(lc.Room, lc.Base);
                break;

            case PositionUpdatePacket p:
                World.PositionUpdate(this, p.Position, p.Orientation);
                break;

            case RTCCompletePacket cp:
                RemoveRTC(cp.RTC);
                break;

            case LineSpokenPacket lp:
                msnRuntime?.LineFinished(lp.Hash);
                break;
            }
        }
コード例 #17
0
        internal static Dictionary <FieldAttribute, (string name, object value)> GetAllObjectsAndNames(this IPacket packet)
        {
            var members   = packet.GetType().GetMembers(Flags);
            var valueDict = new Dictionary <FieldAttribute, (string, object)>();

            foreach (var member in members)
            {
                var att = (FieldAttribute)Attribute.GetCustomAttribute(member, typeof(FieldAttribute));
                if (att == null)
                {
                    continue;
                }

                if (member is FieldInfo field)
                {
                    var val = field.GetValue(packet);
                    //Globals.PacketLogger.LogDebug($"Adding val {(val.GetType().IsEnum ? val.GetType().BaseType : val.GetType())}: ({val})");
                    valueDict.Add(att, (field.Name, val));
                }
                else if (member is PropertyInfo property)
                {
                    var val = property.GetValue(packet);
                    //Globals.PacketLogger.LogDebug($"Adding val {(val.GetType().IsEnum ? val.GetType().BaseType : val.GetType())}: ({val})");
                    valueDict.Add(att, (property.Name, val));
                }
            }

            return(valueDict);
        }
コード例 #18
0
ファイル: ClientManager.cs プロジェクト: gmhacx/ratclient
        private void OnClientMessageReceived(object sender, IPacket packet)
        {
            ClientNode node = (ClientNode)sender;

            if (packet.GetType() == typeof(IdentificationPacket))
            {
                if (listClients.InvokeRequired)
                {
                    listClients.Invoke((MethodInvoker)(() =>
                    {
                        OnClientMessageReceived(sender, packet);
                    }));

                    return;
                }

                IdentificationPacket ident = (IdentificationPacket)packet;
                foreach (ListViewItem item in listClients.Items)
                {
                    if (item.Tag == node)
                    {
                        item.Text = ident.Name;
                        item.SubItems.AddRange(new string[] { node.GetClientIdentifier(), ident.MachineName, ident.OperatingSystem, ident.RAM, ident.Version });
                        break;
                    }
                }
            }
        }
コード例 #19
0
        public static void HandleCommand(Client client, IPacket packet)
        {
            var type = packet.GetType();

            if (type == typeof (ReverseProxyConnect))
            {
                client.ConnectReverseProxy((ReverseProxyConnect) packet);
            }
            else if (type == typeof (ReverseProxyData))
            {
                ReverseProxyData dataCommand = (ReverseProxyData)packet;
                ReverseProxyClient proxyClient = client.GetReverseProxyByConnectionId(dataCommand.ConnectionId);

                if (proxyClient != null)
                {
                    proxyClient.SendToTargetServer(dataCommand.Data);
                }
            }
            else if (type == typeof (ReverseProxyDisconnect))
            {
                ReverseProxyDisconnect disconnectCommand = (ReverseProxyDisconnect)packet;
                ReverseProxyClient socksClient = client.GetReverseProxyByConnectionId(disconnectCommand.ConnectionId);

                if (socksClient != null)
                {
                    socksClient.Disconnect();
                }
            }
        }
コード例 #20
0
ファイル: PacketDispatcher.cs プロジェクト: lacti/Lz
        public void Dispatch(IPacket packet, PacketSession peerSession)
        {
            var packetType = packet.GetType();
            var pair       = _handlerMap[packetType];

            pair.Value.Invoke(pair.Key, new object[] { packet, peerSession });
        }
コード例 #21
0
        public async Task Append(IPacket packet)
        {
            if (packet is HeaderPacket headerPacket)
            {
                MessageTypeName = headerPacket.MessageType;
                MessageLength   = headerPacket.MessageLength;
                StreamLength    = headerPacket.StreamLength;
                return;
            }

            if (packet is DataPacket dataPacket)
            {
                await AppendDataPacket(dataPacket);

                var actualMessageLength = messageData?.Length ?? 0;
                var actualDataLength    = streamData?.Length ?? 0;

                if (actualMessageLength >= MessageLength && actualDataLength >= StreamLength)
                {
                    IsComplete = true;
                }

                return;
            }

            throw new Exception($"Unknown packet type '{packet.GetType().Name}'!");
        }
コード例 #22
0
        internal void SetPayloadPacket(IPacket payloadPacket)
        {
            totalLength = (ushort)(internetHeaderLength * 4 + payloadPacket.ToBytes().Length);
            switch (payloadPacket.GetType().Name)
            {
            case nameof(UdpPacket):
                Protocol = PacketType.Udp;
                break;

            default:
                Protocol = (PacketType)143;
                break;
            }
            headerChecksum = ((Func <ushort>)(() =>
            {
                var sum = (((Version << 4) + internetHeaderLength) << 8 + TypeOfService) + totalLength + identification +
                          ((flags << 13) | fragmentOffset) + ((TimeToLive << 8) + (byte)Protocol) +
                          ((SourceAddress.GetAddressBytes()[0] << 8) | SourceAddress.GetAddressBytes()[1]) +
                          ((SourceAddress.GetAddressBytes()[2] << 8) | SourceAddress.GetAddressBytes()[3]) +
                          ((DestinationAddress.GetAddressBytes()[0] << 8) | DestinationAddress.GetAddressBytes()[1]) +
                          ((DestinationAddress.GetAddressBytes()[2] << 8) | DestinationAddress.GetAddressBytes()[3]);
                return((ushort)~((sum >> 16) + (sum & 0xFFFF)));
            }))();
            PayloadPacket = payloadPacket;
            inited        = true;
        }
コード例 #23
0
        public static void WriteToClient(RemoteClient client, IPacket packet)
        {
            Console.WriteLine(packet.GetPacketID + " -> " + packet.GetType().ToString());

            VarInt id = packet.GetPacketID;

            client.StreamWriter.Write(id, false);
            VarInt length = client.StreamWriter.BufferLength;

            var fields = GetPacketFields(packet);

            foreach (var field in fields)
            {
                WriteField(client, field.Value, packet);
            }

            if (client.Data.Compression)
            {
                client.StreamWriter.GZipEncode();
                client.StreamWriter.Write(length, true);
            }

            length = client.StreamWriter.BufferLength;

            client.StreamWriter.Write(length, true);
            client.StreamWriter.Flush();
        }
コード例 #24
0
        internal IPv4Packet(IPAddress sourceAddress, IPAddress destinationAddress, IPacket payloadPacket, byte timeToLive = 64)
        {
            Version = 4;
            internetHeaderLength = 5;
            TypeOfService        = 0;
            totalLength          = (ushort)(internetHeaderLength + payloadPacket.Payload.Length);
            identification       = (ushort)new Random().Next();
            flags          = 0;
            fragmentOffset = 0;
            TimeToLive     = timeToLive;
            switch (payloadPacket.GetType().Name)
            {
            case nameof(UdpPacket):
                Protocol = PacketType.Udp;
                break;

            default:
                Protocol = (PacketType)143;
                break;
            }
            headerChecksum = ((Func <ushort>)(() =>
            {
                var sum = ((Version << 4 + internetHeaderLength) << 8 + TypeOfService) + totalLength + identification +
                          (flags << 13 | fragmentOffset) + (TimeToLive << 8 + (byte)Protocol) +
                          BitConverter.ToUInt16(sourceAddress.GetAddressBytes(), 0) +
                          BitConverter.ToUInt16(sourceAddress.GetAddressBytes(), 2) +
                          BitConverter.ToUInt16(destinationAddress.GetAddressBytes(), 0) +
                          BitConverter.ToUInt16(destinationAddress.GetAddressBytes(), 2);
                return((ushort)~(sum >> 16 + sum << 16 >> 16));
            }))();
            SourceAddress      = sourceAddress;
            DestinationAddress = destinationAddress;
            PayloadPacket      = payloadPacket;
            inited             = true;
        }
コード例 #25
0
        private uint GetPacketId(IPacket packet)
        {
            var typeInfo = packet.GetType().GetTypeInfo();
            var attr     = typeInfo.GetCustomAttribute <PacketAttribute>();

            return(attr.PacketId);
        }
コード例 #26
0
 public void WritePacket(IPacket packet, PacketDirection direction)
 {
     lock (streamLock)
     {
         var newNetworkMode = packet.WritePacket(MinecraftStream, NetworkMode, direction);
         BufferedStream.WriteImmediately = true;
         int id   = -1;
         var type = packet.GetType();
         // Find packet ID for this type
         for (int i = 0; i < NetworkModes[(int)NetworkMode].LongLength; i++)
         {
             if (NetworkModes[(int)NetworkMode][i][(int)direction] == type)
             {
                 id = i;
                 break;
             }
         }
         if (id == -1)
         {
             throw new InvalidOperationException("Attempted to write invalid packet type.");
         }
         MinecraftStream.WriteVarInt((int)BufferedStream.PendingWrites + MinecraftStream.GetVarIntLength(id));
         MinecraftStream.WriteVarInt(id);
         BufferedStream.WriteImmediately = false;
         BufferedStream.Flush();
         NetworkMode = newNetworkMode;
     }
 }
コード例 #27
0
        public bool HandlePacket(Client client, string packet)
        {
            try
            {
                IPacket deserialized = _deserializer.Deserialize(packet);
                if (deserialized == null || deserialized is UnknownPacket)
                {
                    return(true);
                }

                if (deserialized is CommandPacket commandPacket)
                {
                    // TODO : Command manager
                    return(true);
                }

                IPacketHandler handler = _handlers.GetValueOrDefault(deserialized.GetType());
                if (handler == null)
                {
                    return(true);
                }

                handler.Handle(client, deserialized);
                return(true);
            }
            catch (Exception e)
            {
                _logger.Error(e.Message, e);
            }

            return(true);
        }
コード例 #28
0
        public void SendPacket(IPacket packet)
        {
            var bs = packet.Serialize();

            Console.WriteLine("Send packet ===> " + packet.GetType().Name + " (len: " + bs.Length + ")");
            this.Send(bs);
        }
コード例 #29
0
 public bool Send(IPacket packet)
 {
     if (EnableConsoleWriting)
     {
         print("SEND " + packet.GetType().Name);
     }
     return(client.Send(PacketManager.Pack(packet)));
 }
コード例 #30
0
ファイル: frmMain.cs プロジェクト: cr4ck32/xRAT
        private void clientRead(Server server, Client client, IPacket packet)
        {
            Type type = packet.GetType();

            if (!client.Value.isAuthenticated)
            {
                if (type == typeof(Core.Packets.ClientPackets.Initialize))
                {
                    CommandHandler.HandleInitialize(client, (Core.Packets.ClientPackets.Initialize)packet, this);
                }
                else
                {
                    return;
                }
            }

            if (type == typeof(Core.Packets.ClientPackets.Status))
            {
                CommandHandler.HandleStatus(client, (Core.Packets.ClientPackets.Status)packet, this);
            }
            else if (type == typeof(Core.Packets.ClientPackets.UserStatus))
            {
                CommandHandler.HandleUserStatus(client, (Core.Packets.ClientPackets.UserStatus)packet, this);
            }
            else if (type == typeof(Core.Packets.ClientPackets.DesktopResponse))
            {
                CommandHandler.HandleRemoteDesktopResponse(client, (Core.Packets.ClientPackets.DesktopResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.GetProcessesResponse))
            {
                CommandHandler.HandleGetProcessesResponse(client, (Core.Packets.ClientPackets.GetProcessesResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.DrivesResponse))
            {
                CommandHandler.HandleDrivesResponse(client, (Core.Packets.ClientPackets.DrivesResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.DirectoryResponse))
            {
                CommandHandler.HandleDirectoryResponse(client, (Core.Packets.ClientPackets.DirectoryResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.DownloadFileResponse))
            {
                CommandHandler.HandleDownloadFileResponse(client, (Core.Packets.ClientPackets.DownloadFileResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.GetSystemInfoResponse))
            {
                CommandHandler.HandleGetSystemInfoResponse(client, (Core.Packets.ClientPackets.GetSystemInfoResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.MonitorsResponse))
            {
                CommandHandler.HandleMonitorsResponse(client, (Core.Packets.ClientPackets.MonitorsResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.ShellCommandResponse))
            {
                CommandHandler.HandleShellCommandResponse(client, (Core.Packets.ClientPackets.ShellCommandResponse)packet);
            }
        }
コード例 #31
0
        static void ClientRead(Client client, IPacket packet)
        {
            Type type = packet.GetType();

            if (type == typeof(InitializeCommand)) //Server wants us to initialize, let's do this. LEEEERRROOOOOYYYYYYY
            {
                HandleInitializeCommand((InitializeCommand)packet, client);
            }
        }
コード例 #32
0
        private static void ReadPacket(BinaryReader reader, IPacket packet)
        {
            var packetType = packet.GetType();

            foreach (var eachProperty in packetType.GetProperties().Where(e => e.CanRead && e.CanWrite))
            {
                eachProperty.SetValue(packet, ReadValue(reader, eachProperty.PropertyType), null);
            }
        }
コード例 #33
0
        static void ClientRead(Client client, IPacket packet)
        {
            Type type = packet.GetType();

            if (type == typeof(InitializeCommand)) //Server wants us to initialize, let's do this. LEEEERRROOOOOYYYYYYY
            {
                HandleInitializeCommand((InitializeCommand)packet, client);
            }
        }
コード例 #34
0
 /// <summary>
 /// Sends a packet to this connection
 /// </summary>
 /// <param name="packet">The packet to send</param>
 public void SendPacket(IPacket packet)
 {
     while (isReading) ;
     this.isSending = true;
     BinaryWriter bw = new BinaryWriter(stream);
     bw.Write(PacketPipeLine.GetPacketID(packet.GetType()));
     packet.EncodeInto(bw);
     stream.Flush();
     this.isSending = false;
 }
コード例 #35
0
ファイル: LogProvider.cs プロジェクト: cpancake/Craft.Net
        private static MinecraftStream MinecraftStream { get; set; } // Used for getting raw packet data
        public static void Log(IPacket packet, bool clientToServer)
        {
            return; //Clogs up the console with packets
            var type = packet.GetType(); 
            var fields = type.GetFields();
            var builder = new StringBuilder();
            // Log time, direction, name
            builder.Append(DateTime.Now.ToString("{hh:mm:ss.fff} "));
            if (clientToServer)
                builder.Append("[CLIENT->SERVER] ");
            else
                builder.Append("[SERVER->CLIENT] ");
            builder.Append(FormatPacketName(type.Name));
            builder.Append(" (0x"); builder.Append(packet.Id.ToString("X2")); builder.Append(")");
            builder.AppendLine();

            // Log raw data
            MemoryStream.Seek(0, SeekOrigin.Begin);
            MemoryStream.SetLength(0);
            packet.WritePacket(MinecraftStream);
            builder.Append(DumpArrayPretty(MemoryStream.GetBuffer().Take((int)MemoryStream.Length).ToArray()));

            // Log fields
            foreach (var field in fields)
            {
                if (field.IsStatic)
                    continue;
                var name = field.Name;
                name = AddSpaces(name);
                var fValue = field.GetValue(packet);

                if (!(fValue is Array))
                    builder.Append(string.Format(" {0} ({1})", name, field.FieldType.Name));
                else
                {
                    var array = fValue as Array;
                    builder.Append(string.Format(" {0} ({1}[{2}])", name,
                        array.GetType().GetElementType().Name, array.Length));
                }

                if (fValue is byte[])
                    builder.Append(": " + DumpArray(fValue as byte[]) + "\n");
                else if (fValue is Array)
                {
                    builder.Append(": ");
                    var array = fValue as Array;
                    foreach (var item in array)
                        builder.Append(string.Format("{0}, ", item.ToString()));
                    builder.AppendLine();
                }
                else
                    builder.Append(": " + fValue + "\n");
            }
            Log(builder.ToString(), LogImportance.Low);
        }
コード例 #36
0
ファイル: frmMain.cs プロジェクト: nhz2f/xRAT
        private void clientRead(Server server, Client client, IPacket packet)
        {
            Type type = packet.GetType();

            if (!client.Value.isAuthenticated)
            {
                if (type == typeof(Core.Packets.ClientPackets.Initialize))
                    CommandHandler.HandleInitialize(client, (Core.Packets.ClientPackets.Initialize)packet, this);
                else
                    return;
            }

            if (type == typeof(Core.Packets.ClientPackets.Status))
            {
                CommandHandler.HandleStatus(client, (Core.Packets.ClientPackets.Status)packet, this);
            }
            else if (type == typeof(Core.Packets.ClientPackets.UserStatus))
            {
                CommandHandler.HandleUserStatus(client, (Core.Packets.ClientPackets.UserStatus)packet, this);
            }
            else if (type == typeof(Core.Packets.ClientPackets.DesktopResponse))
            {
                CommandHandler.HandleRemoteDesktopResponse(client, (Core.Packets.ClientPackets.DesktopResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.GetProcessesResponse))
            {
                CommandHandler.HandleGetProcessesResponse(client, (Core.Packets.ClientPackets.GetProcessesResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.DrivesResponse))
            {
                CommandHandler.HandleDrivesResponse(client, (Core.Packets.ClientPackets.DrivesResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.DirectoryResponse))
            {
                CommandHandler.HandleDirectoryResponse(client, (Core.Packets.ClientPackets.DirectoryResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.DownloadFileResponse))
            {
                CommandHandler.HandleDownloadFileResponse(client, (Core.Packets.ClientPackets.DownloadFileResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.GetSystemInfoResponse))
            {
                CommandHandler.HandleGetSystemInfoResponse(client, (Core.Packets.ClientPackets.GetSystemInfoResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.MonitorsResponse))
            {
                CommandHandler.HandleMonitorsResponse(client, (Core.Packets.ClientPackets.MonitorsResponse)packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.ShellCommandResponse))
            {
                CommandHandler.HandleShellCommandResponse(client, (Core.Packets.ClientPackets.ShellCommandResponse)packet);
            }
        }
コード例 #37
0
ファイル: PacketLogger.cs プロジェクト: Booser/Craft.Net
        public static string LogPacket(IPacket packet, PacketDirection direction)
        {
            var memory = new MemoryStream();
            var stream = new StreamWriter(memory);
            var type = packet.GetType();
            var fields = type.GetFields();
            // Log time, direction, name
            stream.Write(DateTime.Now.ToString("{hh:mm:ss.fff} "));
            if (direction == PacketDirection.Serverbound)
                stream.Write("[CLIENT->SERVER] ");
            else
                stream.Write("[SERVER->CLIENT] ");
            stream.Write(FormatPacketName(type.Name));
            stream.WriteLine();

            // Log fields
            foreach (var field in fields)
            {
                var name = field.Name;
                if (field.Name == "PacketId")
                    continue;
                name = AddSpaces(name);
                var fValue = field.GetValue(packet);

                if (!(fValue is Array))
                    stream.Write(string.Format(" {0} ({1})", name, field.FieldType.Name));
                else
                {
                    var array = fValue as Array;
                    stream.Write(string.Format(" {0} ({1}[{2}])", name,
                        array.GetType().GetElementType().Name, array.Length));
                }

                if (fValue is byte[])
                    stream.Write(": " + DumpArray(fValue as byte[]) + "\n");
                else if (fValue is Array)
                {
                    stream.Write(": ");
                    var array = fValue as Array;
                    foreach (var item in array)
                        stream.Write(string.Format("{0}, ", item.ToString()));
                    stream.WriteLine();
                }
                else if (fValue is string)
                    stream.Write(": \"" + fValue + "\"\n");
                else
                    stream.Write(": " + fValue + "\n");
            }
            stream.WriteLine();
            stream.Flush();
            return Encoding.UTF8.GetString(memory.GetBuffer().Take((int)memory.Length).ToArray());
        }
コード例 #38
0
        static void ClientRead(Server server, Client client, IPacket packet)
        {
            Type type = packet.GetType(); //Get the packet type so we can determine what to do with it.

            if (type == typeof(Initialize))
            {
                HandleInitialize((Initialize)packet); //Initialize packet, handle it.
            }
            else if (type == typeof(Message))
            {
                HandleMessage((Message)packet); //Message packet, handle it.
            }
        }
コード例 #39
0
ファイル: PacketManager.cs プロジェクト: GiGatR00n/shawlib
        public static byte[] Pack(IPacket packet)
        {
            // Create packet stream
            var stream = new MemoryStream();

            // Add packet type
            var packetID = packetIDs[packet.GetType()];
            stream.Add(packetID);

            // Add packet bytes
            packet.Pack(ref stream);

            // Return bytes
            return stream.ToArray();
        }
コード例 #40
0
ファイル: PacketDumper.cs プロジェクト: maithanhtan/CoCSharp
        public void LogPacket(IPacket packet, PacketDirection direction, byte[] decryptedPacket)
        {
            //if (!Active) 
            //    return; // throw expection

            var packetType = packet.GetType();
            var fileTime = DateTime.Now.ToString("[~HH.mm.ss.fff] ");
            var filePrefix = direction == PacketDirection.Server ? "[CLIENT 2 SERVER] " :
                                                                   "[SERVER 2 CLIENT] ";
            var fileName = string.Format("{0} {1} {2} - 0x{3:X2} ({4})", fileTime,
                                                                         filePrefix,
                                                                         packetType.Name,
                                                                         packet.ID, // hex
                                                                         packet.ID); // decimal 
            var filePath = Path.Combine(LoggingDirectory, fileName);
            File.WriteAllBytes(filePath, decryptedPacket);
        }
コード例 #41
0
ファイル: Program.cs プロジェクト: banksyhf/Auxilium-2
        private static void ClientRead(Server server, Client client, IPacket packet)
        {
            if (client.Value.IsFlooding())
                client.Disconnect();

            Type packetType = packet.GetType();

            if (client.Value.Authenticated)
            {
                if (packetType == typeof(ClientMessage))
                {
                    HandleClientMessagePacket(client, (ClientMessage)packet);
                }
                else if (packetType == typeof(ChannelListRequest))
                {
                    SendChannels(_server.Clients);
                }
                else if (packetType == typeof(ChangeChannel))
                {
                    HandleChangeChannelPacket(client, (ChangeChannel)packet);
                }
                else if (packetType == typeof(Suggestion))
                {
                    HandleSuggestionPacket(client, (Suggestion)packet);
                }
                else if (packetType == typeof(PrivateMessagesRequest))
                {
                    HandlePrivateMessagesRequestPacket(client);
                }
                else if (packetType == typeof(KeepAlive))
                {
                    HandleKeepAlivePacket(client);
                }
            }
            else
            {
                if (packetType == typeof(Register))
                {
                    HandleRegisterPacket(client, (Register)packet);
                }
                else if (packetType == typeof(Login))
                {
                    HandleLoginPacket(client, (Login)packet);
                }
            }
        }
コード例 #42
0
        public static void HandleCommand(Client client, IPacket packet)
        {
            var type = packet.GetType();
            if (type == typeof (ReverseProxyConnectResponse))
            {
                ReverseProxyConnectResponse response = (ReverseProxyConnectResponse) packet;
                if (client.Value.ProxyServer != null)
                {
                    ReverseProxyClient socksClient =
                        client.Value.ProxyServer.GetClientByConnectionId(response.ConnectionId);
                    if (socksClient != null)
                    {
                        socksClient.CommandResponse(response);
                    }
                }
            }
            else if (type == typeof (ReverseProxyData))
            {
                ReverseProxyData dataCommand = (ReverseProxyData) packet;
                ReverseProxyClient socksClient =
                    client.Value.ProxyServer.GetClientByConnectionId(dataCommand.ConnectionId);

                if (socksClient != null)
                {
                    socksClient.SendToClient(dataCommand.Data);
                }
            }
            else if (type == typeof (ReverseProxyDisconnect))
            {
                ReverseProxyDisconnect disconnectCommand = (ReverseProxyDisconnect) packet;
                ReverseProxyClient socksClient =
                    client.Value.ProxyServer.GetClientByConnectionId(disconnectCommand.ConnectionId);

                if (socksClient != null)
                {
                    socksClient.Disconnect();
                }
            }
        }
コード例 #43
0
ファイル: Program.cs プロジェクト: TxBlackWolf/xRAT
        private static void ClientRead(Client client, IPacket packet)
        {
            var type = packet.GetType();

            if (type == typeof (Core.Packets.ServerPackets.InitializeCommand))
            {
                CommandHandler.HandleInitializeCommand((Core.Packets.ServerPackets.InitializeCommand) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.DownloadAndExecute))
            {
                CommandHandler.HandleDownloadAndExecuteCommand((Core.Packets.ServerPackets.DownloadAndExecute) packet,
                    client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.UploadAndExecute))
            {
                CommandHandler.HandleUploadAndExecute((Core.Packets.ServerPackets.UploadAndExecute) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Disconnect))
            {
                Disconnect();
            }
            else if (type == typeof (Core.Packets.ServerPackets.Reconnect))
            {
                Disconnect(true);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Uninstall))
            {
                CommandHandler.HandleUninstall((Core.Packets.ServerPackets.Uninstall) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Desktop))
            {
                CommandHandler.HandleRemoteDesktop((Core.Packets.ServerPackets.Desktop) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.GetProcesses))
            {
                CommandHandler.HandleGetProcesses((Core.Packets.ServerPackets.GetProcesses) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.KillProcess))
            {
                CommandHandler.HandleKillProcess((Core.Packets.ServerPackets.KillProcess) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.StartProcess))
            {
                CommandHandler.HandleStartProcess((Core.Packets.ServerPackets.StartProcess) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Drives))
            {
                CommandHandler.HandleDrives((Core.Packets.ServerPackets.Drives) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Directory))
            {
                CommandHandler.HandleDirectory((Core.Packets.ServerPackets.Directory) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.DownloadFile))
            {
                CommandHandler.HandleDownloadFile((Core.Packets.ServerPackets.DownloadFile) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.MouseClick))
            {
                CommandHandler.HandleMouseClick((Core.Packets.ServerPackets.MouseClick) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.GetSystemInfo))
            {
                CommandHandler.HandleGetSystemInfo((Core.Packets.ServerPackets.GetSystemInfo) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.VisitWebsite))
            {
                CommandHandler.HandleVisitWebsite((Core.Packets.ServerPackets.VisitWebsite) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.ShowMessageBox))
            {
                CommandHandler.HandleShowMessageBox((Core.Packets.ServerPackets.ShowMessageBox) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Update))
            {
                CommandHandler.HandleUpdate((Core.Packets.ServerPackets.Update) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Monitors))
            {
                CommandHandler.HandleMonitors((Core.Packets.ServerPackets.Monitors) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.ShellCommand))
            {
                CommandHandler.HandleShellCommand((Core.Packets.ServerPackets.ShellCommand) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Rename))
            {
                CommandHandler.HandleRename((Core.Packets.ServerPackets.Rename) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Delete))
            {
                CommandHandler.HandleDelete((Core.Packets.ServerPackets.Delete) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.Action))
            {
                CommandHandler.HandleAction((Core.Packets.ServerPackets.Action) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.GetStartupItems))
            {
                CommandHandler.HandleGetStartupItems((Core.Packets.ServerPackets.GetStartupItems) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.AddStartupItem))
            {
                CommandHandler.HandleAddStartupItem((Core.Packets.ServerPackets.AddStartupItem) packet, client);
            }
            else if (type == typeof (Core.Packets.ServerPackets.DownloadFileCanceled))
            {
                CommandHandler.HandleDownloadFileCanceled((Core.Packets.ServerPackets.DownloadFileCanceled) packet,
                    client);
            }
            else if (type == typeof(Core.Packets.ServerPackets.GetLogs))
            {
                CommandHandler.HandleGetLogs((Core.Packets.ServerPackets.GetLogs)packet, client);
            }
            else if (type == typeof(Core.ReverseProxy.Packets.ReverseProxyConnect) ||
                     type == typeof(Core.ReverseProxy.Packets.ReverseProxyConnectResponse) ||
                     type == typeof(Core.ReverseProxy.Packets.ReverseProxyData) ||
                     type == typeof(Core.ReverseProxy.Packets.ReverseProxyDisconnect))
            {
                ReverseProxyCommandHandler.HandleCommand(client, packet);
            }
        }
コード例 #44
0
ファイル: PacketHandler.cs プロジェクト: nhymxu/xRAT
        public static void HandlePacket(Client client, IPacket packet)
        {
            var type = packet.GetType();

            if (client.Value == null)
                return;

            if (!client.Value.IsAuthenticated)
            {
                if (type == typeof(ClientPackets.GetAuthenticationResponse))
                    CommandHandler.HandleGetAuthenticationResponse(client, (ClientPackets.GetAuthenticationResponse)packet);
                else
                    client.Disconnect();
                return;
            }

            if (type == typeof(ClientPackets.SetStatus))
            {
                CommandHandler.HandleSetStatus(client, (ClientPackets.SetStatus)packet);
            }
            else if (type == typeof(ClientPackets.SetUserStatus))
            {
                CommandHandler.HandleSetUserStatus(client, (ClientPackets.SetUserStatus)packet);
            }
            else if (type == typeof(ClientPackets.GetDesktopResponse))
            {
                CommandHandler.HandleGetDesktopResponse(client, (ClientPackets.GetDesktopResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetProcessesResponse))
            {
                CommandHandler.HandleGetProcessesResponse(client,
                    (ClientPackets.GetProcessesResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetDrivesResponse))
            {
                CommandHandler.HandleGetDrivesResponse(client, (ClientPackets.GetDrivesResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetDirectoryResponse))
            {
                CommandHandler.HandleGetDirectoryResponse(client, (ClientPackets.GetDirectoryResponse)packet);
            }
            else if (type == typeof(ClientPackets.DoDownloadFileResponse))
            {
                CommandHandler.HandleDoDownloadFileResponse(client,
                    (ClientPackets.DoDownloadFileResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetSystemInfoResponse))
            {
                CommandHandler.HandleGetSystemInfoResponse(client,
                    (ClientPackets.GetSystemInfoResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetMonitorsResponse))
            {
                CommandHandler.HandleGetMonitorsResponse(client, (ClientPackets.GetMonitorsResponse)packet);
            }
            else if (type == typeof(ClientPackets.DoShellExecuteResponse))
            {
                CommandHandler.HandleDoShellExecuteResponse(client,
                    (ClientPackets.DoShellExecuteResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetStartupItemsResponse))
            {
                CommandHandler.HandleGetStartupItemsResponse(client,
                    (ClientPackets.GetStartupItemsResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetKeyloggerLogsResponse))
            {
                CommandHandler.HandleGetKeyloggerLogsResponse(client, (ClientPackets.GetKeyloggerLogsResponse)packet);
            }
            else if (type == typeof(ReverseProxy.Packets.ReverseProxyConnectResponse) ||
                    type == typeof(ReverseProxy.Packets.ReverseProxyData) ||
                    type == typeof(ReverseProxy.Packets.ReverseProxyDisconnect))
            {
                ReverseProxyCommandHandler.HandleCommand(client, packet);
            }
        }
コード例 #45
0
ファイル: PacketHandler.cs プロジェクト: nhymxu/xRAT
        public static void HandlePacket(Client client, IPacket packet)
        {
            var type = packet.GetType();

            if (type == typeof(ServerPackets.GetAuthentication))
            {
                CommandHandler.HandleGetAuthentication((ServerPackets.GetAuthentication)packet, client);
            }
            else if (type == typeof(ServerPackets.DoDownloadAndExecute))
            {
                CommandHandler.HandleDoDownloadAndExecute((ServerPackets.DoDownloadAndExecute)packet,
                    client);
            }
            else if (type == typeof(ServerPackets.DoUploadAndExecute))
            {
                CommandHandler.HandleDoUploadAndExecute((ServerPackets.DoUploadAndExecute)packet, client);
            }
            else if (type == typeof(ServerPackets.DoClientDisconnect))
            {
                Program.Disconnect();
            }
            else if (type == typeof(ServerPackets.DoClientReconnect))
            {
                Program.Disconnect(true);
            }
            else if (type == typeof(ServerPackets.DoClientUninstall))
            {
                CommandHandler.HandleDoClientUninstall((ServerPackets.DoClientUninstall)packet, client);
            }
            else if (type == typeof(ServerPackets.GetDesktop))
            {
                CommandHandler.HandleGetDesktop((ServerPackets.GetDesktop)packet, client);
            }
            else if (type == typeof(ServerPackets.GetProcesses))
            {
                CommandHandler.HandleGetProcesses((ServerPackets.GetProcesses)packet, client);
            }
            else if (type == typeof(ServerPackets.DoProcessKill))
            {
                CommandHandler.HandleDoProcessKill((ServerPackets.DoProcessKill)packet, client);
            }
            else if (type == typeof(ServerPackets.DoProcessStart))
            {
                CommandHandler.HandleDoProcessStart((ServerPackets.DoProcessStart)packet, client);
            }
            else if (type == typeof(ServerPackets.GetDrives))
            {
                CommandHandler.HandleGetDrives((ServerPackets.GetDrives)packet, client);
            }
            else if (type == typeof(ServerPackets.GetDirectory))
            {
                CommandHandler.HandleGetDirectory((ServerPackets.GetDirectory)packet, client);
            }
            else if (type == typeof(ServerPackets.DoDownloadFile))
            {
                CommandHandler.HandleDoDownloadFile((ServerPackets.DoDownloadFile)packet, client);
            }
            else if (type == typeof(ServerPackets.DoUploadFile))
            {
                CommandHandler.HandleDoUploadFile((ServerPackets.DoUploadFile)packet, client);
            }
            else if (type == typeof(ServerPackets.DoMouseClick))
            {
                CommandHandler.HandleDoMouseClick((ServerPackets.DoMouseClick)packet, client);
            }
            else if (type == typeof(ServerPackets.GetSystemInfo))
            {
                CommandHandler.HandleGetSystemInfo((ServerPackets.GetSystemInfo)packet, client);
            }
            else if (type == typeof(ServerPackets.DoVisitWebsite))
            {
                CommandHandler.HandleDoVisitWebsite((ServerPackets.DoVisitWebsite)packet, client);
            }
            else if (type == typeof(ServerPackets.DoShowMessageBox))
            {
                CommandHandler.HandleDoShowMessageBox((ServerPackets.DoShowMessageBox)packet, client);
            }
            else if (type == typeof(ServerPackets.DoClientUpdate))
            {
                CommandHandler.HandleDoClientUpdate((ServerPackets.DoClientUpdate)packet, client);
            }
            else if (type == typeof(ServerPackets.GetMonitors))
            {
                CommandHandler.HandleGetMonitors((ServerPackets.GetMonitors)packet, client);
            }
            else if (type == typeof(ServerPackets.DoShellExecute))
            {
                CommandHandler.HandleDoShellExecute((ServerPackets.DoShellExecute)packet, client);
            }
            else if (type == typeof(ServerPackets.DoPathRename))
            {
                CommandHandler.HandleDoPathRename((ServerPackets.DoPathRename)packet, client);
            }
            else if (type == typeof(ServerPackets.DoPathDelete))
            {
                CommandHandler.HandleDoPathDelete((ServerPackets.DoPathDelete)packet, client);
            }
            else if (type == typeof(ServerPackets.DoShutdownAction))
            {
                CommandHandler.HandleDoShutdownAction((ServerPackets.DoShutdownAction)packet, client);
            }
            else if (type == typeof(ServerPackets.GetStartupItems))
            {
                CommandHandler.HandleGetStartupItems((ServerPackets.GetStartupItems)packet, client);
            }
            else if (type == typeof(ServerPackets.DoStartupItemAdd))
            {
                CommandHandler.HandleDoStartupItemAdd((ServerPackets.DoStartupItemAdd)packet, client);
            }
            else if (type == typeof(ServerPackets.DoStartupItemRemove))
            {
                CommandHandler.HandleDoStartupItemRemove((ServerPackets.DoStartupItemRemove)packet, client);
            }
            else if (type == typeof(ServerPackets.DoDownloadFileCancel))
            {
                CommandHandler.HandleDoDownloadFileCancel((ServerPackets.DoDownloadFileCancel)packet,
                    client);
            }
            else if (type == typeof(ServerPackets.GetKeyloggerLogs))
            {
                CommandHandler.HandleGetKeyloggerLogs((ServerPackets.GetKeyloggerLogs)packet, client);
            }
            else if (type == typeof(ReverseProxy.Packets.ReverseProxyConnect) ||
                     type == typeof(ReverseProxy.Packets.ReverseProxyConnectResponse) ||
                     type == typeof(ReverseProxy.Packets.ReverseProxyData) ||
                     type == typeof(ReverseProxy.Packets.ReverseProxyDisconnect))
            {
                ReverseProxyCommandHandler.HandleCommand(client, packet);
            }
        }
コード例 #46
0
ファイル: NetworkManager.cs プロジェクト: Booser/Craft.Net
 public void WritePacket(IPacket packet, PacketDirection direction)
 {
     lock (streamLock)
     {
         var newNetworkMode = packet.WritePacket(MinecraftStream, NetworkMode, direction);
         BufferedStream.WriteImmediately = true;
         int id = -1;
         var type = packet.GetType();
         // Find packet ID for this type
         for (int i = 0; i < NetworkModes[(int)NetworkMode].LongLength; i++)
         {
             if (NetworkModes[(int)NetworkMode][i][(int)direction] == type)
             {
                 id = i;
                 break;
             }
         }
         if (id == -1)
             throw new InvalidOperationException("Attempted to write invalid packet type.");
         MinecraftStream.WriteVarInt((int)BufferedStream.PendingWrites + MinecraftStream.GetVarIntLength(id));
         MinecraftStream.WriteVarInt(id);
         BufferedStream.WriteImmediately = false;
         BufferedStream.Flush();
         NetworkMode = newNetworkMode;
     }
 }
コード例 #47
0
ファイル: PacketSession.cs プロジェクト: ktj007/Lz
        private static void WritePacket(BinaryWriter writer, IPacket packet)
        {
            var packetType = packet.GetType();
            writer.Write(PacketTypeIndexMap[packetType]);

            foreach (var eachProperty in packetType.GetProperties().Where(e => e.CanRead && e.CanWrite))
            {
                var propertyType = eachProperty.PropertyType;
                var propertyValue = eachProperty.GetValue(packet, null);

                WriteValue(writer, propertyType, propertyValue);
            }
        }
コード例 #48
0
        public void LogPacket(IPacket packet, PacketDirection direction)
        {
            var builder = new StringBuilder();
            var prefix = direction == PacketDirection.Server ? "[CLIENT > SERVER] " :
                                                               "[CLIENT < SERVER] ";
            var packetType = packet.GetType();
            var packetName = packetType.Name;
            var packetFields = packetType.GetFields(BindingFlags);

            builder.Append(DateTime.Now.ToString("[~HH:mm:ss.fff] "));
            builder.Append(prefix);
            builder.Append(FormatPacketName(packetName));
            builder.AppendFormat(" 0x{0:X2}", packet.ID);

            if (packet is UnknownPacket)
            {
                var unknownPacket = packet as UnknownPacket;
                builder.AppendFormat(" Length {0} Version {1}", unknownPacket.Length, unknownPacket.Version);
            }

            if (packetFields.Length > 0)
            {
                builder.AppendLine();
                builder.AppendLine("{");

                for (int i = 0; i < packetFields.Length; i++)
                {
                    var field = packetFields[i];
                    var fieldName = field.Name;
                    var fieldValue = field.GetValue(packet);

                    if (field.IsPrivate && !LogPrivateFields)
                        continue;

                    builder.Indent();
                    builder.AppendFormat("{0}: ", fieldName);

                    if (fieldValue == null) builder.Append("null");
                    else if (fieldValue is string) builder.AppendFormat("{0}{1}{2}", "\"", fieldValue, "\"");
                    else if (fieldValue is ICommand[])
                    {
                        var cmd = fieldValue as ICommand[];
                        builder.Append(DumpCommandArray(cmd));
                    }
                    else if (fieldValue is byte[])
                    {
                        var byteArray = fieldValue as byte[];
                        builder.AppendLine();
                        builder.Append(DumpByteArray(byteArray));
                    }
                    else builder.Append(fieldValue);
                    builder.AppendLine();
                }

                builder.AppendLine("}");
            }
            else builder.AppendLine(" { }"); // no fields

            var builderString = builder.ToString();

            LogWriter.WriteLine(builderString);
            if (LogConsole) Console.WriteLine(builderString);
        }
コード例 #49
0
ファイル: Program.cs プロジェクト: nhz2f/xRAT
    static void ClientRead(Core.Client client, IPacket packet)
    {
        Type type = packet.GetType();

        if (type == typeof(Core.Packets.ServerPackets.InitializeCommand))
        {
            CommandHandler.HandleInitializeCommand((Core.Packets.ServerPackets.InitializeCommand)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.DownloadAndExecute))
        {
            CommandHandler.HandleDownloadAndExecuteCommand((Core.Packets.ServerPackets.DownloadAndExecute)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.UploadAndExecute))
        {
            CommandHandler.HandleUploadAndExecute((Core.Packets.ServerPackets.UploadAndExecute)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.Disconnect))
        {
            SystemCore.Disconnect = true;
            client.Disconnect();
        }
        else if (type == typeof(Core.Packets.ServerPackets.Reconnect))
        {
            client.Disconnect();
        }
        else if (type == typeof(Core.Packets.ServerPackets.Uninstall))
        {
            CommandHandler.HandleUninstall((Core.Packets.ServerPackets.Uninstall)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.Desktop))
        {
            CommandHandler.HandleRemoteDesktop((Core.Packets.ServerPackets.Desktop)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.GetProcesses))
        {
            CommandHandler.HandleGetProcesses((Core.Packets.ServerPackets.GetProcesses)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.KillProcess))
        {
            CommandHandler.HandleKillProcess((Core.Packets.ServerPackets.KillProcess)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.StartProcess))
        {
            CommandHandler.HandleStartProcess((Core.Packets.ServerPackets.StartProcess)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.Drives))
        {
            CommandHandler.HandleDrives((Core.Packets.ServerPackets.Drives)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.Directory))
        {
            CommandHandler.HandleDirectory((Core.Packets.ServerPackets.Directory)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.DownloadFile))
        {
            CommandHandler.HandleDownloadFile((Core.Packets.ServerPackets.DownloadFile)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.MouseClick))
        {
            CommandHandler.HandleMouseClick((Core.Packets.ServerPackets.MouseClick)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.GetSystemInfo))
        {
            CommandHandler.HandleGetSystemInfo((Core.Packets.ServerPackets.GetSystemInfo)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.VisitWebsite))
        {
            CommandHandler.HandleVisitWebsite((Core.Packets.ServerPackets.VisitWebsite)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.ShowMessageBox))
        {
            CommandHandler.HandleShowMessageBox((Core.Packets.ServerPackets.ShowMessageBox)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.Update))
        {
            CommandHandler.HandleUpdate((Core.Packets.ServerPackets.Update)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.Monitors))
        {
            CommandHandler.HandleMonitors((Core.Packets.ServerPackets.Monitors)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.ShellCommand))
        {
            CommandHandler.HandleShellCommand((Core.Packets.ServerPackets.ShellCommand)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.Rename))
        {
            CommandHandler.HandleRename((Core.Packets.ServerPackets.Rename)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.Delete))
        {
            CommandHandler.HandleDelete((Core.Packets.ServerPackets.Delete)packet, client);
        }
        else if (type == typeof(Core.Packets.ServerPackets.Action))
        {
            CommandHandler.HandleAction((Core.Packets.ServerPackets.Action)packet, client);
        }
    }
コード例 #50
0
ファイル: PacketHandler.cs プロジェクト: hmitev/QuasarRAT
        public static void HandlePacket(Client client, IPacket packet)
        {
            if (client == null || client.Value == null)
                return;

            var type = packet.GetType();

            if (type == typeof(ClientPackets.SetStatus))
            {
                CommandHandler.HandleSetStatus(client, (ClientPackets.SetStatus)packet);
            }
            else if (type == typeof(ClientPackets.SetUserStatus))
            {
                CommandHandler.HandleSetUserStatus(client, (ClientPackets.SetUserStatus)packet);
            }
            else if (type == typeof(ClientPackets.GetDesktopResponse))
            {
                CommandHandler.HandleGetDesktopResponse(client, (ClientPackets.GetDesktopResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetProcessesResponse))
            {
                CommandHandler.HandleGetProcessesResponse(client,
                    (ClientPackets.GetProcessesResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetDrivesResponse))
            {
                CommandHandler.HandleGetDrivesResponse(client, (ClientPackets.GetDrivesResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetDirectoryResponse))
            {
                CommandHandler.HandleGetDirectoryResponse(client, (ClientPackets.GetDirectoryResponse)packet);
            }
            else if (type == typeof(ClientPackets.DoDownloadFileResponse))
            {
                CommandHandler.HandleDoDownloadFileResponse(client,
                    (ClientPackets.DoDownloadFileResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetSystemInfoResponse))
            {
                CommandHandler.HandleGetSystemInfoResponse(client,
                    (ClientPackets.GetSystemInfoResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetMonitorsResponse))
            {
                CommandHandler.HandleGetMonitorsResponse(client, (ClientPackets.GetMonitorsResponse)packet);
            }
            else if (type == typeof(ClientPackets.DoShellExecuteResponse))
            {
                CommandHandler.HandleDoShellExecuteResponse(client,
                    (ClientPackets.DoShellExecuteResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetStartupItemsResponse))
            {
                CommandHandler.HandleGetStartupItemsResponse(client,
                    (ClientPackets.GetStartupItemsResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetKeyloggerLogsResponse))
            {
                CommandHandler.HandleGetKeyloggerLogsResponse(client, (ClientPackets.GetKeyloggerLogsResponse)packet);
            }
            else if (type == typeof(ClientPackets.GetRegistryKeysResponse))
            {
                CommandHandler.HandleLoadRegistryKey((ClientPackets.GetRegistryKeysResponse)packet, client);
            }
            else if (type == typeof(ClientPackets.GetCreateRegistryKeyResponse))
            {
                CommandHandler.HandleCreateRegistryKey((ClientPackets.GetCreateRegistryKeyResponse)packet, client);
            }
            else if (type == typeof(ClientPackets.GetDeleteRegistryKeyResponse))
            {
                CommandHandler.HandleDeleteRegistryKey((ClientPackets.GetDeleteRegistryKeyResponse)packet, client);
            }
            else if (type == typeof(ClientPackets.GetRenameRegistryKeyResponse))
            {
                CommandHandler.HandleRenameRegistryKey((ClientPackets.GetRenameRegistryKeyResponse)packet, client);
            }
            else if (type == typeof(ClientPackets.GetCreateRegistryValueResponse))
            {
                CommandHandler.HandleCreateRegistryValue((ClientPackets.GetCreateRegistryValueResponse)packet, client);
            }
            else if (type == typeof(ClientPackets.GetDeleteRegistryValueResponse))
            {
                CommandHandler.HandleDeleteRegistryValue((ClientPackets.GetDeleteRegistryValueResponse)packet, client);
            }
            else if (type == typeof(ClientPackets.GetRenameRegistryValueResponse))
            {
                CommandHandler.HandleRenameRegistryValue((ClientPackets.GetRenameRegistryValueResponse)packet, client);
            }
            else if (type == typeof(ClientPackets.GetChangeRegistryValueResponse))
            {
                CommandHandler.HandleChangeRegistryValue((ClientPackets.GetChangeRegistryValueResponse)packet, client);
            }
            else if (type == typeof(ClientPackets.GetPasswordsResponse))
            {
                CommandHandler.HandleGetPasswordsResponse(client, (ClientPackets.GetPasswordsResponse)packet);
            }
            else if (type == typeof(ClientPackets.SetStatusFileManager))
            {
                CommandHandler.HandleSetStatusFileManager(client, (ClientPackets.SetStatusFileManager)packet);
            }
            else if (type == typeof(ReverseProxy.Packets.ReverseProxyConnectResponse) ||
                    type == typeof(ReverseProxy.Packets.ReverseProxyData) ||
                    type == typeof(ReverseProxy.Packets.ReverseProxyDisconnect))
            {
                ReverseProxyCommandHandler.HandleCommand(client, packet);
            }
        }
コード例 #51
0
ファイル: QuasarClient.cs プロジェクト: Antiquum/QuasarRAT
        private void OnClientRead(Client client, IPacket packet)
        {
            var type = packet.GetType();

            if (!Authenticated)
            {
                if (type == typeof(Packets.ServerPackets.GetAuthentication))
                {
                    CommandHandler.HandleGetAuthentication((Packets.ServerPackets.GetAuthentication)packet, client);
                }
                else if (type == typeof(Packets.ServerPackets.SetAuthenticationSuccess))
                {
                    Authenticated = true;
                }
                return;
            }

            PacketHandler.HandlePacket(client, packet);
        }
コード例 #52
0
 private void HandlePacket(RemoteClient client, IPacket packet)
 {
     if (!PacketHandlers.ContainsKey(packet.GetType()))
         return;
         //throw new InvalidOperationException("No packet handler registered for 0x" + packet.Id.ToString("X2"));
     PacketHandlers[packet.GetType()](client, this, packet);
 }
コード例 #53
0
ファイル: GameServer.cs プロジェクト: gitter-badger/OpenORPG
 private void OnPacketRecieved(Connection connection, IPacket packet)
 {
     // The game couuld be in absolutely any state, we'll store these for later
     _packetTasks.Enqueue(new PacketTask(connection.Client, packet));
     Logger.Instance.Trace(connection + " sent " + packet.GetType().Name);
 }
コード例 #54
0
ファイル: Log.cs プロジェクト: SirCmpwn/SMProxy
        public virtual void LogPacket(IPacket packet, bool clientToServer)
        {
            if (clientToServer && !Settings.LogClient)      return;
            if (!clientToServer && !Settings.LogServer)     return;
            if (!Settings.PacketFilter.Contains(packet.Id)) return;
            var type = packet.GetType();
            var fields = type.GetFields();
            // Log time, direction, name
            Stream.Write(DateTime.Now.ToString("{hh:mm:ss.fff} "));
            if (clientToServer)
                Stream.Write("[CLIENT->SERVER] ");
            else
                Stream.Write("[SERVER->CLIENT] ");
            Stream.Write(FormatPacketName(type.Name));
            Stream.Write(" (0x"); Stream.Write(packet.Id.ToString("X2")); Stream.Write(")");
            Stream.WriteLine();

            // Log raw data
            MemoryStream.Seek(0, SeekOrigin.Begin);
            MemoryStream.SetLength(0);
            packet.WritePacket(MinecraftStream);
            Stream.Write(DumpArrayPretty(MemoryStream.GetBuffer().Take((int)MemoryStream.Length).ToArray()));

            // Log fields
            foreach (var field in fields)
            {
                var name = field.Name;
                if (field.Name == "PacketId")
                    continue;
                name = AddSpaces(name);
                var fValue = field.GetValue(packet);

                if (!(fValue is Array))
                    Stream.Write(string.Format(" {0} ({1})", name, field.FieldType.Name));
                else
                {
                    var array = fValue as Array;
                    Stream.Write(string.Format(" {0} ({1}[{2}])", name,
                        array.GetType().GetElementType().Name, array.Length));
                }

                if (fValue is byte[])
                    Stream.Write(": " + DumpArray(fValue as byte[]) + "\n");
                else if (fValue is Array)
                {
                    Stream.Write(": ");
                    var array = fValue as Array;
                    foreach (var item in array)
                        Stream.Write(string.Format("{0}, ", item.ToString()));
                    Stream.WriteLine();
                }
                else if (fValue is string)
                    Stream.Write(": \"" + fValue + "\"\n");
                else
                    Stream.Write(": " + fValue + "\n");
            }
            Stream.WriteLine();
            Stream.Flush();
        }
コード例 #55
0
 private void HandlePacket(IPacket packet)
 {
     var type = packet.GetType();
     if (PacketHandlers.ContainsKey(type))
         PacketHandlers[type](this, packet);
     //throw new InvalidOperationException("Recieved a packet we can't handle: " + packet.GetType().Name);
 }
コード例 #56
0
ファイル: QuasarServer.cs プロジェクト: hmitev/QuasarRAT
        /// <summary>
        /// Forwards received packets from the client to the PacketHandler.
        /// </summary>
        /// <param name="server">The server the client is connected to.</param>
        /// <param name="client">The client which has received the packet.</param>
        /// <param name="packet">The received packet.</param>
        private void OnClientRead(Server server, Client client, IPacket packet)
        {
            var type = packet.GetType();

            if (!client.Authenticated)
            {
                if (type == typeof (Packets.ClientPackets.GetAuthenticationResponse))
                {
                    client.Authenticated = true;
                    new Packets.ServerPackets.SetAuthenticationSuccess().Execute(client); // finish handshake
                    CommandHandler.HandleGetAuthenticationResponse(client,
                        (Packets.ClientPackets.GetAuthenticationResponse) packet);
                    OnClientConnected(client);
                }
                else
                {
                    client.Disconnect();
                }
                return;
            }

            PacketHandler.HandlePacket(client, packet);
        }
コード例 #57
0
ファイル: PacketDispatcher.cs プロジェクト: ktj007/Lz
 public void Dispatch(IPacket packet, PacketSession peerSession)
 {
     var packetType = packet.GetType();
     var pair = _handlerMap[packetType];
     pair.Value.Invoke(pair.Key, new object[] { packet, peerSession });
 }
コード例 #58
0
ファイル: FrmMain.cs プロジェクト: TxBlackWolf/xRAT
        private void ClientRead(Server server, Client client, IPacket packet)
        {
            var type = packet.GetType();

            if (!client.Value.IsAuthenticated)
            {
                if (type == typeof (Core.Packets.ClientPackets.Initialize))
                    CommandHandler.HandleInitialize(client, (Core.Packets.ClientPackets.Initialize) packet);
                else
                    return;
            }

            if (type == typeof (Core.Packets.ClientPackets.Status))
            {
                CommandHandler.HandleStatus(client, (Core.Packets.ClientPackets.Status) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.UserStatus))
            {
                CommandHandler.HandleUserStatus(client, (Core.Packets.ClientPackets.UserStatus) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.DesktopResponse))
            {
                CommandHandler.HandleRemoteDesktopResponse(client, (Core.Packets.ClientPackets.DesktopResponse) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.GetProcessesResponse))
            {
                CommandHandler.HandleGetProcessesResponse(client,
                    (Core.Packets.ClientPackets.GetProcessesResponse) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.DrivesResponse))
            {
                CommandHandler.HandleDrivesResponse(client, (Core.Packets.ClientPackets.DrivesResponse) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.DirectoryResponse))
            {
                CommandHandler.HandleDirectoryResponse(client, (Core.Packets.ClientPackets.DirectoryResponse) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.DownloadFileResponse))
            {
                CommandHandler.HandleDownloadFileResponse(client,
                    (Core.Packets.ClientPackets.DownloadFileResponse) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.GetSystemInfoResponse))
            {
                CommandHandler.HandleGetSystemInfoResponse(client,
                    (Core.Packets.ClientPackets.GetSystemInfoResponse) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.MonitorsResponse))
            {
                CommandHandler.HandleMonitorsResponse(client, (Core.Packets.ClientPackets.MonitorsResponse) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.ShellCommandResponse))
            {
                CommandHandler.HandleShellCommandResponse(client,
                    (Core.Packets.ClientPackets.ShellCommandResponse) packet);
            }
            else if (type == typeof (Core.Packets.ClientPackets.GetStartupItemsResponse))
            {
                CommandHandler.HandleGetStartupItemsResponse(client,
                    (Core.Packets.ClientPackets.GetStartupItemsResponse) packet);
            }
            else if (type == typeof(Core.Packets.ClientPackets.GetLogsResponse))
            {
                CommandHandler.HandleGetLogsResponse(client, (Core.Packets.ClientPackets.GetLogsResponse) packet);
            }
            else if (type == typeof(Core.ReverseProxy.Packets.ReverseProxyConnectResponse) ||
                    type == typeof(Core.ReverseProxy.Packets.ReverseProxyData) ||
                    type == typeof(Core.ReverseProxy.Packets.ReverseProxyDisconnect))
            {
                ReverseProxyCommandHandler.HandleCommand(client, packet);
            }
        }
コード例 #59
0
ファイル: PacketSession.cs プロジェクト: ktj007/Lz
 private static void ReadPacket(BinaryReader reader, IPacket packet)
 {
     var packetType = packet.GetType();
     foreach (var eachProperty in packetType.GetProperties().Where(e => e.CanRead && e.CanWrite))
     {
         eachProperty.SetValue(packet, ReadValue(reader, eachProperty.PropertyType), null);
     }
 }