How to sanitize a file name (protect against shell injection)?

What is the usual practice for disinfecting a file name from an external source (for example, an xml file) before using it as part of a subprocess (shell = False)?

Update: Before posting some parsed lines around, I would like to do some basic security checks. In this example, mpg123 (command line audio player) is used remotely to play the sound file.

filename = child.find("filename").text # e.g.: filename = "sound.mp3"
pid = subprocess.Popen(["mpg123"],"-R"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
command = "L "+filename+"\n"  
pid.stdin.write(command.encode())
+3
source share
2 answers

File names do not need to be sanitized unless you use a shell or do nothing. Pythons open () will not execute any commands in the specified file name.

, , , , , , .

, , , . . , mp3- , , , .

+1

, .

, . , . , os.path.isfile.

"" , , . , . "" ( ).

"" - . , (. ). , "" , , , , . , . , , .

+3

Source: https://habr.com/ru/post/1786380/


All Articles