2

How do I execute linux grep using python? My current attempt is the following

    output = subprocess.run(
        "/bin/grep " + query,
        cwd=path_to_files,
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE,
        shell=True
    )

Which works. Issue however is that query can include untrusted commands (eg. if they append a semicolon in the query, they can possibly run a second command in addition to the initial grep). How could I securely accept user inputs to the grep command?

7
  • 1
    The best way is not trust user input to be safe at all. Especially with shell=True. You need to restrict the query as much as possible. And that will depend on your use-case Commented May 24, 2019 at 7:13
  • I understand that shell=True is what makes this query dangerous. If I remove shell=True, subprocess would not execute by throwing a FileNotFoundError error. I would like to give my users access to use grep on a single folder, recursively. Commented May 24, 2019 at 7:18
  • Remove shell=True. Use chroot jail. Maybe symlink the grep binary to the local directory to get around the FileNotFoundError Commented May 24, 2019 at 7:20
  • Where is the list of filenames to grep? Is that part of query? Commented May 24, 2019 at 7:20
  • Correct. The user would, for example, enter -r "pokedex" */*.html into the input. Which translate to the query variable. Commented May 24, 2019 at 7:22

1 Answer 1

1

Insead of use shell=True, you can send a list to subprocess.run.

import shlex

output = subprocess.run(
    ["/bin/grep "] + shlex.split(query),
    cwd=path_to_files,
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)

This code prevent using ; for shell injection.

Another problem is that the user can access all files in the system.
You can use chroot for prevent a user to go above that the given file or you can modify your code for to be able to check which file the user will open.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.