title: Preventing DoS attacks from malicious protobuf packets
body: <p>I'm currently writing a client/server application, using Google Protocol Buffers to encode the underlying messages. Since it's a .NET program, I'm using the protobuf-net library: it's fast, portable and well thought.</p>
  
  <p>However, I'm a little concerned about potential DoS attacks. The server application will be facing the internet directly and the underlying protocol will be publicly documented. An attacker can very easily craft a packet to exhaust memory.</p>
  
  <p>A simple example:</p>
  
  <p>Given the following proto definition:</p>
  
  <pre><code>[ProtoContract]
  class Foo {
      [ProtoMember(1)]
      public string Bar { get; set; }
  }
  </code></pre>
  
  <p>The following code will try to allocate a 2GB buffer for the <code>Bar</code> string:</p>
  
  <pre><code>byte[] bytes = { 0x0A, 0xFF, 0xFF, 0xFF, 0xFF, 0x07 };
  Serializer.Deserialize&lt;Foo&gt;(new MemoryStream(bytes));
  </code></pre>
  
  <p>Instantly resulting in a <code>OutOfMemoryException</code>. Of course, here it won't really matter: the runtime won't be able to allocate it (at least in a 32 bits process). Now craft multiple packets each allocating a few hundreds MB of memory, and watch normal operations fail because of the lack of memory. Sure, the memory will be reclaimed rapidly by the GC if the attacker doesn't send anything after the string length, but it's still too easy to increase memory pressure.</p>
  
  <p>I'm aware that this issue isn't really specific to protobuf-net: any protocol using length-prefixed data will probably encounter the same problems. Usually, they're solved using arbitrary quotas. However, I didn't find any way to specify them in protobuf-net. For example, I'd like to specify that a string cannot exceed N characters, that a given list cannot have more M elements, etc.</p>
  
  <p>Is there any easy solution to prevent this problem that I've missed (rather than making my own implementation or fork)?</p>