Statement 'if 0: return' not failing with error - ebranca/owasp-pysec GitHub Wiki

Classification

  • Affected Components : builtins

  • Operating System : Linux

  • Python Versions : 2.6.x, 2.7.x, 3.1.x, 3.2.x

  • Reproducible : Yes

Source code


# TEST1
# should return sintax error as return is outside a function
try:
    if 0:
        return
    print("TEST1-FAIL")
except Exception as e:
    print("TEST1-PASS")
    pass

# TEST2
# should return sintax error as return is outside a function
try:
    if False:
        return
    print("TEST2-FAIL")
except Exception as e:
    print("TEST2-PASS")
    pass

Steps to Produce/Reproduce

To reproduce the problem copy the source code in a file and execute the script using the following command syntax:

$ python -OOBRtt test.py

Alternatively you can open python in interactive mode:

$ python -OOBRtt <press enter>

Then copy the lines of code into the interpreter.

Description

Python has different behaviors based on how conditions are expressed and on which version of python is used.

The source code used for this example has been tailored to test python behavior in two conditions:

  1. if 0: return
  2. if False: return

In both cases the code is a bad example of broken code and should generate "SyntaxError" but this is not the case.

TEST 1

Should return SyntaxError as return is outside a function.

*** Expected: *** SyntaxError: 'return' outside function

  • Python 2.6.5 32bit --> "TEST1-FAIL" (WRONG)

  • Python 2.7.4 32bit --> "TEST1-FAIL" (WRONG)

  • Python 3.1.2 32bit --> "TEST1-FAIL" (WRONG)

TEST 2

Should return SyntaxError as return is outside a function.

*** Expected: *** SyntaxError: 'return' outside function

  • Test Results:

-- Python 2.6.5 32bit --> "SyntaxError: 'return' outside function" (CORRECT)

-- Python 2.7.4 32bit --> "SyntaxError: 'return' outside function" (CORRECT)

-- Python 3.1.2 32bit --> "TEST2-FAIL" (WRONG)

The interpreter eliminates the block if 0 and correctly emits the else clause if present, but in this case the ```return''' statement is not optimized away.

In Python 3.x this condition has not been fixed but the problem has been ignored, "if 0: return" at module level is plainly ignored and does not raises a Syntaxerror but is still there.

Workaround

We are not aware on any easy solution other than trying to avoind using constructs like if 0: or while 0:.

Secure Implementation

WORK IN PROGRESS

References

[Simple Statements][01] [01]:https://docs.python.org/2/reference/simple_stmts.html

[Compound Statements][02] [02]:https://docs.python.org/2/reference/compound_stmts.html

[Python bug 1875][03] [03]:http://bugs.python.org/issue1875

[Control Flow][04] [04]:https://docs.python.org/2/tutorial/controlflow.html

[Python bug 1920][05] [05]:http://bugs.python.org/issue1920