0

My question is theoretical, and not bound to python - but for the sake of simplicity, I'll use Python code snippet.

Let's assume I have the following code:

import os
import sys

if os.path.exist(sys.argv[1]):
    os.system(f"echo {sys.argv[1]}")

Is there a way to do a command injection attack in the scenario when the unsanitized input is a path to a valid file?

  • Windows or Linux? – user202729 Oct 6 at 4:45
  • Either of them interseting – macro_controller Oct 6 at 7:05
  • 2
    How is this related to RE? – sudhackar Oct 8 at 6:42
  • Also yes. It can lead to code execution example – sudhackar Oct 8 at 6:48
  • @sudhackar sorry, this is not code execution. the lol executable in your example is executed by the shell, even before python runs. The first correct example that comes to mind is a file with a name like "abcde;ls" where ls will be executed. – w s Oct 17 at 18:17
0

On GNU/Linux, system passes any arguments to /bin/sh -c "<command>". Any shell metacharacters (e.g. &, |, `, $, ; etc.) in the command will be interpreted. So, commands can be run using `command` or $(command) to use a subshell, or with other logic.

If a file has those characters, commands could be run:

$ ls itworks
$ touch '$(touch itworks)'
$ ./myscript.py '$(touch itworks)'
$ ls itworks
itworks

Since the file exists, it will be passed to system, and any nested commands executed. You may be limited in what commands and arguments can be passed, since / cannot be used in the filename.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.