Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is kind of tricky, but given the source code (or a good python decompiler), you can do this:</p> <p>in 'nine.py':</p> <pre><code>def number_nine(): x = 9 if x == 9: print 'x is Nine!' else: print 'x:', x </code></pre> <p>Your evil code:</p> <pre><code>from nine import number_nine </code></pre> <p>We need to use ast, which is <a href="http://docs.python.org/library/ast.html" rel="nofollow">Abstract Syntax Trees</a>:</p> <pre><code>import inspect import ast </code></pre> <p>Now we get the source and transform it to an ast:</p> <pre><code># Assuming you have the source, we can generate AST from it nine_src = inspect.getsource(number_nine) nine_ast = ast.parse(nine_src) </code></pre> <p>Isolate the specific statement you want to change:</p> <pre><code># This is the Assign object, which represents the 'x = 9' line # Try to run it interactivly and see how it looks... x_assign = nine_ast.body[0].body[0] # Prints 'x' print x_assign.targets[0].id # Prints 9 print x_assign.value.n </code></pre> <p>And alter it as you see fit:</p> <pre><code># Change the value of x # Notice, that we change the assignment itself, a.k.a `x = 9` is now `x = "It's a trap!"` x_assign.value.n = "It's a trap!" </code></pre> <p>Now all that is left to do is to compile your modified ast object to something more useful:</p> <pre><code># Compile the new function new_nine = compile(nine_ast, 'new_nine', 'exec') </code></pre> <p>You can use simple <code>exec</code> (which will replace 'number_nine' if it is in <code>globals</code>), or <code>exec in</code>, and place it in a temp module:</p> <pre><code># Now we need to execute our litle new_nine (which is a code object) # This to create the modified version in 'm' import types m = types.ModuleType('m', 'The m module') exec new_nine in m.__dict__ m.number_nine() # Or this to create it in the global scope exec new_nine number_nine() </code></pre> <p>And bang! it prints <code>x: It's a trap!</code></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload