'How to fix command injection issue on Checkmarx for parse_args
I have python code that parses input parameters:
parser=OptionParser()
parser.add_option("-o", dest="out", default=os.getenv('Path',None), help="file path")
parser.add_option("-c", dest="content", default=os.path.abspath(sys.path[0]), help="cont path")
parser.add_option("-t", dest="tool", default=os.getenv('Tool',None), help="tool path")
parser.add_option("-m", dest="man", default=os.getenv('Path',os.getcwd())+os.sep+"man.ini", help="man.ini location")
(opt, agrs)=parser.parse_args()
Checkmarx says the following: The application's main method calls an OS (shell) command with cmd, using an untrusted string with the command to execute.This could allow an attacker to inject an arbitrary command, and enable a Command Injection attack.The attacker may be able to inject the executed command via user input, parse_args... I think I need to strip the unneeded characters like |, & and ; but am unsure how/where to do it. Can I do it before this line "(opt, agrs)=parser.parse_args()"? Thanks
Solution 1:[1]
Your code shows only the source (parsing command line arguments into strings) and not the sync (I assume it is exec). In general - I would advise sanitizing the payload (in this case the string of one/more of the parameters) close to the the executing code, and only what needs to be sanitized.
Trying to sanitize everything beforehand may cause one of the two: missing some edge case and creating vulnerable code, or, limiting the value range of a parameter because of unnecessary sanitation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | S Shahar |