1

I found that when I put \r\n 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,

In PHP:

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$key = "foo\r\nset bar 0 10 10000\r\n";

echo $m->get($key);
echo $m->get($key); // <- hang here
?>

In Python:

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) # <- hang here

If key is read from the user, a user could execute arbitrary commands in the memcached server, such as to run flush_all to slow down the website or set the password cache for another user.

Why the client library doesn't strip these illegal characters? How to properly prevent it in my code?

lqs
  • 1,434
  • 11
  • 20
  • 2
    How about you don't let your users query for arbitrary keys? – Carsten Jan 23 '13 at 14:41
  • Sometimes I need to use the slug as the key to get the content of the article. An attacker could put `%0D%0A` in the URL. – lqs Jan 23 '13 at 14:46
  • 3
    Well, then filter that. Or rather, only allow the user-given key to consist of characters which are definitely harmless. – Carsten Jan 23 '13 at 14:48

1 Answers1

2

Encode the user value (base64 for example) and use the result as the key, or use the binary protocol.