Python security coding and code auditing (1)
1 Preface
Currently, the general web development framework security has been quite good. For example, django is commonly used, but some nonstandard development methods will still cause some common security problems, the following is a summary of these common problems. For the preparation of code audit, see php code audit. This document mainly describes common error scenarios, which are basically errors made by our own developers and sensitive information has been removed.
2 XSS
Input and output are not filtered. Scenario:
def xss_test(request): name = request.GET['name'] return HttpResponse('hello %s' %(name))
A search in the code finds that a large number of places are used. The correct method is as follows:
def xss_test(request): name = request.GET['name'] #return HttpResponse('hello %s' %(name))
Return render_to_response('hello.html ', {'name': name })
It is better to restrict the input, such as a regular expression range, and use the correct api or filter the output.
3 CSRF
Perform CSRF protection for important operations in the system, such as logon, shutdown, and scanning. Django provides the CSRF middleware django. middleware. csrf. CsrfViewMiddleware and writes it to the middleware of settings. py. Add the @ csrf_exempt modifier before the function.
4. Command Injection
Some bad habits of writing code are found in the audit code process. The most serious manifestation is the functionality that can be completed by some function libraries of python itself in terms of command injection, however, the OS must be called. to be honest, this is the most annoying way to write code. The following is a simple example:
def myserve(request, filename, dirname): re = serve(request=request,path=filename,document_root=dirname,show_indexes=True) filestr='authExport.dat' re['Content-Disposition'] = 'attachment; filename="' + urlquote(filestr) +'"'fullname=os.path.join(dirname,filename) os.system('sudo rm -f %s'%fullname) return re
Obviously, this code is problematic because fullname is controllable. The correct method is to change the OS. system interface to the python library function, so as to avoid command injection. Python deletes files in three ways:
(1) Delete A folder and all files in shutil. rmtree
(2) Delete an empty directory from OS. rmdir
(3) OS. remove, unlink delete an object
After using the above interface, you must note that you cannot traverse the directory. Otherwise, the entire system may be deleted. Common functions with risky command execution are as follows:
OS. system, OS. popen, OS. spaw *, OS .exe c *, OS. open, OS. popen *, commands. call, commands. getoutput, Popen *
We recommend that you use the subprocess module and make sure that shell = True is not set. Otherwise, there is a risk of injection.