title: How to properly prevent memcached "protocol injection"?
body: <p>I found that when I put <code>\r\n</code> in the key to get the value from memcached server, it can be used to inject the memcached protocol to run another command. Following is the code example,</p>
  
  <p>In PHP:</p>
  
  <pre><code>&lt;?php
  $m = new Memcached();
  $m-&gt;addServer('localhost', 11211);
  
  $key = "foo\r\nset bar 0 10 10000\r\n";
  
  echo $m-&gt;get($key);
  echo $m-&gt;get($key); // &lt;- hang here
  ?&gt;
  </code></pre>
  
  <p>In Python:</p>
  
  <pre><code>import pylibmc
  
  mc = pylibmc.Client(['127.0.0.1:11211'])
  
  key = 'foo\r\nset bar 0 10 10000\r\n';
  print mc.get(key)
  print mc.get(key) # &lt;- hang here
  </code></pre>
  
  <p>If <code>key</code> is read from the user, a user could execute arbitrary commands in the memcached server, such as to run <code>flush_all</code> to slow down the website or set the password cache for another user.</p>
  
  <p>Why the client library doesn't strip these illegal characters? How to properly prevent it in my code?</p>