4

I would like to securely ask a password to a user and then pass it to subprocess.Popen to run a command that requires it.

I have seen this question and that one, but I wonder if I can securely pass the password via the subprocess environment like that:

import subprocess, os
user_password = input("what is you password?")
my_env = os.environ.copy()
my_env["userpass"] = user_password
my_command = "python --version"
subprocess.Popen(my_command, env=my_env)

Will the password be flushed once the python script is closed ? I have look at the subprocess documentation but it's not explained.

When I add this line print(os.environ['userpass']) at the end of my code to print the OS environment, I can retrieve the user password. Do it means that the password can be access by the other running processes ?

Edit: I can't pipe the password as the command I use doesn't read its password from standard input

MagTun
  • 5,619
  • 5
  • 63
  • 104
  • 2
    I'd pipe it into the subprocess. Trying to hide it in the environment is maybe marginally better than on the cmdline, but it's still accessible `/proc//environ` (in linux at least). – jedwards Nov 09 '18 at 20:26
  • It looks like the environment trick is just as risky on Windows too, btw ([here](https://stackoverflow.com/questions/2255968/view-environment-variable-of-process-on-windows)) – jedwards Nov 09 '18 at 20:30
  • Thanks for your help! Regarding cmdline. When you say cmdline, you mean this: I run the command directly in Windows command prompt, wait for the command to ask the password and then I type it? Is this unsafe? – MagTun Nov 09 '18 at 20:48
  • regarding pipe: do you mean doing something like this https://stackoverflow.com/a/41094357/3154274 – MagTun Nov 09 '18 at 20:49
  • (a) no that's safe, I mean when you first type the name of your program to call it -- *that's* the line I was referring to, not anything you enter subsequently. (b) Yes, that's what I mean re: piping it. – jedwards Nov 09 '18 at 20:51
  • @jedwards, thanks for suggesting the stdin way but the command I use doesn't read its password from standard input – MagTun Nov 10 '18 at 18:22
  • @jedwards Still, the environment also in ´/proc//environ/` is only readable by the current user and `root` so it is not accessible to other users, at least. But I agree that it is less safe, and better alternatives are normally available. – JohanL Nov 11 '18 at 05:48
  • What ways can passwords be entered into the command you use? Apparently it can read environment variables but not over `stdin`? Are there other ways, e.g. from a `pty´? In that case, have a look at `pexpect´? (Or potentially roll your own input function using `pty` directly.) – JohanL Nov 11 '18 at 05:50
  • @JohanL, sorry for the delay, I need to send the password to rclone and I think the only way is by setting the environment cf https://stackoverflow.com/questions/49588368 – MagTun Nov 16 '18 at 18:29

0 Answers0