4

Apologies if this is an abstract question - I'll try to be as specific as possible.

When I'm at the bash shell and switch to a different account via su - foo, I'm prompted for a password. The characters I type at this password prompt are hidden from the screen with no indication of how many characters I'm typing or what they are. How is bash (or Linux in general) doing this?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Mike B
  • 8,769
  • 24
  • 70
  • 96

2 Answers2

8

What you type is displayed in the terminal because the terminal "echoes" it back. When asking for password, the echoing is turned off. See also help read and its -s option.

choroba
  • 45,735
  • 7
  • 84
  • 110
6

I believed that su probably opened /dev/tty, changed the terminal driver settings to not echo, and then read from /dev/tty's file descriptor.

To test this belief, I ran strace -o su.out su - on my Arch linux laptop. The relevant part of the strace output:

ioctl(0, SNDCTL_TMR_CONTINUE or TCSETSF, {B38400 opost isig icanon -echo ...}) = 0
write(2, "Password: ", 10)              = 10
read(0, "hahanotthis\n", 511)                = 7
ioctl(0, SNDCTL_TMR_STOP or TCSETSW, {B38400 opost isig icanon echo ...}) = 0

I was not 100% wrong. su does in fact read from stdin, but it does turn off echoing on stdin using a terminal control ioctl(). After I put in the password, su turns echoing back on, again with ioctl() system call.

I know that some other programs, the ftp client in particular, do use /dev/tty to read passwords, which means you can't put a password on the command line, or in a "here document", you have to use some shenanigans.