Python - remote object protocols and security

Chris Angelico rosuav at gmail.com
Mon Jul 15 08:51:48 EDT 2013


On Mon, Jul 15, 2013 at 10:41 PM, Jean-Michel Pichavant
<jeanmichel at sequans.com> wrote:
> ----- Original Message -----
>> > What I think I need to care about, is malicious code injections.
>> > Because
>> > both client/server will be in python, would someone capable of
>> > executing
>> > code by changing one side python source ?
>> >
>> > How do I prevent this and still provide the source to everyone ?
>>
>> How complicated are the objects you want to transmit? If they're just
>> strings, integers, floats, and lists or dictionaries of the above,
>> then you could use JSON instead; that's much safer, but (and because)
>> it's majorly restricted. Sometimes it's worth warping your data
>> structure slightly (eg use a dict and global functions instead of a
>> custom object with methods) to improve security.
>>
>> ChrisA
>
> In the end just strings and Int.
> Dave seems to agree with you and JSON is the way to go.
>
> However, I don't want to write net code, I'm lazy and most importantly I'm so bad at it.
> So how would I send Json strings from one machine to a remote ?
> If I'm using http://code.google.com/p/jsonrpclib/, would it still be a Json safe way of sending strings and int ?

To send JSON-encoded data, you:

1) Encode your data in JSON format and some character encoding (eg UTF-8)
2) Transmit the resulting stream of bytes over the network
3) Decode UTF-8 and then JSON

Python provides all this functionality:

>>> data = {"English":"Hello, world","Russian":"Привет, мир"}
>>> json.dumps(data).encode()
b'{"English": "Hello, world", "Russian":
"\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442, \\u043c\\u0438\\u0440"}'

which happens to look very much like the original input, though this
is more coincidence than design. Note that you could leave the
non-ASCII characters as they are, and transmit them as UTF-8
sequences:

>>> json.dumps(data,ensure_ascii=False).encode()
b'{"English": "Hello, world", "Russian":
"\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82,
\xd0\xbc\xd0\xb8\xd1\x80"}'

Take your pick, based on what you want to do at the other end. The
second form is (obviously) a lot more compact than the first.

Decoding is just as easy:

>>> data=b'{"English": "Hello, world", "Russian": "\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82, \xd0\xbc\xd0\xb8\xd1\x80"}'
>>> json.loads(data.decode())
{'English': 'Hello, world', 'Russian': 'Привет, мир'}

So the only bit you still need is: How do you transmit this across the
network? Since it's now all just bytes, that's easy enough to do, eg
with TCP. But that depends on the rest of your system, and is a quite
separate question - and quite probably one you already have the answer
to.

ChrisA



More information about the Python-list mailing list