1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Copyright 2014-2017 The Rpassword Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[cfg(unix)]
extern crate libc;

#[cfg(windows)]
extern crate winapi;

use std::io::Write;

mod zero_on_drop;
use zero_on_drop::ZeroOnDrop;

/// Removes the \n from the read line
fn fixes_newline(password: &mut ZeroOnDrop) {
    // We may not have a newline, e.g. if user sent CTRL-D or if
    // this is not a TTY.

    if password.ends_with('\n') {
        // Remove the \n from the line if present
        password.pop();

        // Remove the \r from the line if present
        if password.ends_with('\r') {
            password.pop();
        }
    }
}

/// Reads a password from STDIN
pub fn read_password() -> ::std::io::Result<String> {
    read_password_with_reader(None::<::std::io::Empty>)
}

#[cfg(unix)]
mod unix {
    use libc::{c_int, termios, isatty, tcsetattr, TCSANOW, ECHO, ECHONL, STDIN_FILENO};
    use std::io::{self, BufRead, Write};
    use std::mem;
    use std::os::unix::io::AsRawFd;

    /// Turns a C function return into an IO Result
    fn io_result(ret: c_int) -> ::std::io::Result<()> {
        match ret {
            0 => Ok(()),
            _ => Err(::std::io::Error::last_os_error()),
        }
    }

    fn safe_tcgetattr(fd: c_int) -> ::std::io::Result<termios> {
        let mut term = mem::MaybeUninit::<::unix::termios>::uninit();
        io_result(unsafe { ::libc::tcgetattr(fd, term.as_mut_ptr()) })?;
        Ok(unsafe { term.assume_init() })
    }

    /// Reads a password from stdin
    pub fn read_password_from_stdin(open_tty: bool) -> ::std::io::Result<String> {
        let mut password = super::ZeroOnDrop::new();

        enum Source {
            Tty(io::BufReader<::std::fs::File>),
            Stdin(io::Stdin),
        }

        let (tty_fd, mut source) = if open_tty {
            let tty = ::std::fs::File::open("/dev/tty")?;
            (tty.as_raw_fd(), Source::Tty(io::BufReader::new(tty)))
        } else {
            (STDIN_FILENO, Source::Stdin(io::stdin()))
        };

        let input_is_tty = unsafe { isatty(tty_fd) } == 1;

        // When we ask for a password in a terminal, we'll want to hide the password as it is
        // typed by the user
        if input_is_tty {
            // Make two copies of the terminal settings. The first one will be modified
            // and the second one will act as a backup for when we want to set the
            // terminal back to its original state.
            let mut term      = safe_tcgetattr(tty_fd)?;
            let     term_orig = safe_tcgetattr(tty_fd)?;

            // Hide the password. This is what makes this function useful.
            term.c_lflag &= !ECHO;

            // But don't hide the NL character when the user hits ENTER.
            term.c_lflag |= ECHONL;

            // Save the settings for now.
            io_result(unsafe { tcsetattr(tty_fd, TCSANOW, &term) })?;

            // Read the password.
            let input = match source {
                Source::Tty(ref mut tty) => tty.read_line(&mut password),
                Source::Stdin(ref mut stdin) => stdin.read_line(&mut password),
            };

            // Check the response.
            match input {
                Ok(_) => {}
                Err(err) => {
                    // Reset the terminal and quit.
                    io_result(unsafe { tcsetattr(tty_fd, TCSANOW, &term_orig) })?;

                    return Err(err);
                }
            };

            // Reset the terminal.
            io_result(unsafe { tcsetattr(tty_fd, TCSANOW, &term_orig) })?;
        } else {
            // If we don't have a TTY, the input was piped so we bypass
            // terminal hiding code
            match source {
                Source::Tty(mut tty) => tty.read_line(&mut password)?,
                Source::Stdin(stdin) => stdin.read_line(&mut password)?,
            };
        }

        super::fixes_newline(&mut password);

        Ok(password.into_inner())
    }

    /// Displays a prompt on the terminal
    pub fn display_on_tty(prompt: &str) -> ::std::io::Result<()> {
        let mut stream =
            ::std::fs::OpenOptions::new().write(true).open("/dev/tty")?;
        write!(stream, "{}", prompt)?;
        stream.flush()
    }
}

#[cfg(windows)]
mod windows {
    use std::ptr;
    use std::io::{self, Write};
    use std::os::windows::io::{FromRawHandle, AsRawHandle};
    use winapi::um::winnt::{
        GENERIC_READ, GENERIC_WRITE, FILE_SHARE_READ, FILE_SHARE_WRITE,
    };
    use winapi::um::fileapi::{CreateFileA, OPEN_EXISTING};
    use winapi::um::processenv::GetStdHandle;
    use winapi::um::winbase::STD_INPUT_HANDLE;
    use winapi::um::handleapi::INVALID_HANDLE_VALUE;
    use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode};
    use winapi::shared::minwindef::LPDWORD;
    use winapi::um::wincon::{ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT};

    /// Reads a password from stdin
    pub fn read_password_from_stdin(open_tty: bool) -> io::Result<String> {
        let mut password = super::ZeroOnDrop::new();

        // Get the stdin handle
        let handle = if open_tty {
            unsafe {
                CreateFileA(b"CONIN$\x00".as_ptr() as *const i8,
                                      GENERIC_READ | GENERIC_WRITE,
                                      FILE_SHARE_READ | FILE_SHARE_WRITE,
                                      ptr::null_mut(), OPEN_EXISTING, 0,
                                      ptr::null_mut())
            }
        } else {
            unsafe {
                GetStdHandle(STD_INPUT_HANDLE)
            }
        };
        if handle == INVALID_HANDLE_VALUE {
            return Err(::std::io::Error::last_os_error());
        }

        // Get the old mode so we can reset back to it when we are done
        let mut mode = 0;
        if unsafe { GetConsoleMode(handle, &mut mode as LPDWORD) } == 0 {
            return Err(::std::io::Error::last_os_error());
        }

        // We want to be able to read line by line, and we still want backspace to work
        let new_mode_flags = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
        if unsafe { SetConsoleMode(handle, new_mode_flags) } == 0 {
            return Err(::std::io::Error::last_os_error());
        }

        // Read the password.
        let source = io::stdin();
        let input = source.read_line(&mut password);
        let handle = source.as_raw_handle();

        // Check the response.
        let _ = input?;

        // Set the the mode back to normal
        if unsafe { SetConsoleMode(handle, mode) } == 0 {
            return Err(::std::io::Error::last_os_error());
        }

        super::fixes_newline(&mut password);

		// Newline for windows which otherwise prints on the same line.
		println!();

        Ok(password.into_inner())
    }

    /// Displays a prompt on the terminal
    pub fn display_on_tty(prompt: &str) -> ::std::io::Result<()> {
        let handle = unsafe {
            CreateFileA(b"CONOUT$\x00".as_ptr() as *const i8,
                                  GENERIC_READ | GENERIC_WRITE,
                                  FILE_SHARE_READ | FILE_SHARE_WRITE,
                                  ::std::ptr::null_mut(), OPEN_EXISTING, 0,
                                  ::std::ptr::null_mut())
        };
        if handle == INVALID_HANDLE_VALUE {
            return Err(::std::io::Error::last_os_error());
        }

        let mut stream = unsafe {
            ::std::fs::File::from_raw_handle(handle)
        };

        write!(stream, "{}", prompt)?;
        stream.flush()
    }
}


#[cfg(unix)]
use unix::{read_password_from_stdin, display_on_tty};
#[cfg(windows)]
use windows::{read_password_from_stdin, display_on_tty};

/// Reads a password from anything that implements BufRead
pub fn read_password_with_reader<T>(source: Option<T>) -> ::std::io::Result<String>
    where T: ::std::io::BufRead {
    match source {
        Some(mut reader) => {
            let mut password = ZeroOnDrop::new();
            if let Err(err) = reader.read_line(&mut password) {
                Err(err)
            } else {
                fixes_newline(&mut password);
                Ok(password.into_inner())
            }
        },
        None => read_password_from_stdin(false),
    }
}

/// Reads a password from the terminal
pub fn read_password_from_tty(prompt: Option<&str>)
                              -> ::std::io::Result<String> {
    if let Some(prompt) = prompt {
        display_on_tty(prompt)?;
    }
    read_password_from_stdin(true)
}

/// Prompts for a password on STDOUT and reads it from STDIN
pub fn prompt_password_stdout(prompt: &str) -> std::io::Result<String> {
    let mut stdout = std::io::stdout();

    write!(stdout, "{}", prompt)?;
    stdout.flush()?;
    read_password()
}

/// Prompts for a password on STDERR and reads it from STDIN
pub fn prompt_password_stderr(prompt: &str) -> std::io::Result<String> {
    let mut stderr = std::io::stderr();

    write!(stderr, "{}", prompt)?;
    stderr.flush()?;
    read_password()
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    fn mock_input_crlf() -> Cursor<&'static [u8]> {
        Cursor::new(&b"A mocked response.\r\n"[..])
    }

    fn mock_input_lf() -> Cursor<&'static [u8]> {
        Cursor::new(&b"A mocked response.\n"[..])
    }

    #[test]
    fn can_read_from_redirected_input() {
        let response = ::read_password_with_reader(Some(mock_input_crlf())).unwrap();
        assert_eq!(response, "A mocked response.");
        let response = ::read_password_with_reader(Some(mock_input_lf())).unwrap();
        assert_eq!(response, "A mocked response.");
    }
}