diff --git a/Assets/Mirror/Runtime/NetworkConnection.cs b/Assets/Mirror/Runtime/NetworkConnection.cs index 1c6e079b9..193951f27 100644 --- a/Assets/Mirror/Runtime/NetworkConnection.cs +++ b/Assets/Mirror/Runtime/NetworkConnection.cs @@ -225,22 +225,42 @@ public bool InvokeHandler(T msg) where T : IMessageBase // and in NetworkServer/Client Update. HandleBytes already takes exactly one. public virtual void TransportReceive(byte[] buffer) { - // unpack message - NetworkReader reader = new NetworkReader(buffer); - if (MessagePacker.UnpackMessage(reader, out int msgType)) + // protect against DOS attacks if attackers try to send invalid + // data packets to crash the server/client. there are a thousand + // ways to cause an exception in data handling: + // - invalid headers + // - invalid message ids + // - invalid data causing exceptions + // - negative ReadBytesAndSize prefixes + // - invalid utf8 strings + // - etc. + // + // let's catch them all and then disconnect that connection to avoid + // further attacks. + try { - if (logNetworkMessages) + // unpack message + NetworkReader reader = new NetworkReader(buffer); + if (MessagePacker.UnpackMessage(reader, out int msgType)) { - Debug.Log("ConnectionRecv con:" + connectionId + " msgType:" + msgType + " content:" + BitConverter.ToString(buffer)); - } + if (logNetworkMessages) + { + Debug.Log("ConnectionRecv con:" + connectionId + " msgType:" + msgType + " content:" + BitConverter.ToString(buffer)); + } - // try to invoke the handler for that message - if (InvokeHandler(msgType, reader)) - { - lastMessageTime = Time.time; + // try to invoke the handler for that message + if (InvokeHandler(msgType, reader)) + { + lastMessageTime = Time.time; + } } + else Debug.LogError("HandleBytes UnpackMessage failed for: " + BitConverter.ToString(buffer)); + } + catch (Exception exception) + { + Disconnect(); + Debug.LogWarning("Closed connection: " + connectionId + ". This can happen if the other side accidentally (or an attacker intentionally) sent invalid data. Reason: " + exception); } - else Debug.LogError("HandleBytes UnpackMessage failed for: " + BitConverter.ToString(buffer)); } public virtual bool TransportSend(int channelId, byte[] bytes, out byte error)