How to fix security issue in python?

最后都变了- 提交于 2020-05-15 16:34:08

问题


I have used os.system('cls' if os.name == 'nt' else 'clear') to clear the ouput while running scripts but on codacy i am getting one securiy issue

Starting a process with a shell, possible injection detected, security issue.

How to resolve the issue?

Script link: https://www.codacy.com/app/vaibhavsingh97/StalkPy/file/9458582870/issues/source?bid=5189215&fileBranchId=5189215#l43


回答1:


It has security issues just when you run the function with arguments taken from users. For example:

import os
def do_clear(command): # Notice command is sent as argument from outside world and hence this makes it vulnerable
    os.system(command)

If the method is called with for example

do_clear('rm -f */*')

Then it is possible that it deletes all the files of current directory. But if the 'clear' command is to be directly used, you do not have to worry about the security issue, as only 'clear' is run in all conditions. So the following function is secure enough.

def do_clear(): # Notice command is not sent as argument from outside world
    os.system('cls' if os.name == 'nt' else 'clear') # This is not risky as os.system takes clear/cls command always.



回答2:


From os.system

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

I recommend a test with one of the subprocess passing as parameter shell=False and see if that work on codacy. subprocess.run(['clear']) worked in my local Python interpreter, you would have to test it on codacy.

If Python 2.x, you can try:

subprocess.call(['clear'])


来源:https://stackoverflow.com/questions/45912088/how-to-fix-security-issue-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!