简体   繁体   中英

Secure way to update UNIX account password using Python as root user?

Consider a UNIX account jdoe . I want to update jdoe 's password using python script running as root . Currently, I am using:

cmd = 'echo "' + username + ":" + new_pass + '" | chpasswd '
os.system(cmd)

However, that is an unsafe method. If someone were to enter new_pass as pass"; rm -rf / # , that would be disasterous.

Is there a safe and secure way to do it?

I'd modify it so the entered password gets hashed (sha512 is standard on modern Linux systems) and then pass the hashes value to your cmd.

cmd = 'echo "' + username + ":" + new_pass + '" | chpasswd -e'
os.system(cmd)

Note the -e after chpasswd

Fleshing the above suggestion out a little more:

import crypt
entered_password = 'pass"; rm -rf / #'
new_password = crypt.crypt(entered_password, '$6$' + 'salt1234')

If you're concerned about untrusted input, it's better to avoid using os.system , since that invokes the shell, and in general, you don't want the shell anywhere near untrusted input. In addition, you typically want to avoid putting secrets into command-line arguments since they can be read by other users, although since echo is usually a built-in, this isn't strictly a concern here.

To do this securely, you can use subprocess.Popen instead, like so:

import subprocess

proc = subprocess.Popen(['chpasswd'], stdin=subprocess.PIPE)
proc.stdin.write(b"username:password")

Note that if you need to pass additional arguments to chpasswd , you'd do that by adding arguments to the array:

proc = subprocess.Popen(['chpasswd', '-c', 'SHA512'], stdin=subprocess.PIPE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM