rpassword-7.2.0/.cargo_vcs_info.json0000644000000001600000000000100130630ustar { "git": { "sha1": "a8f24b3357b753f198cda1892ed2e19a4da1cf15" }, "path_in_vcs": "projects/rpassword" }rpassword-7.2.0/.github/FUNDING.yml000064400000000000000000000000341046102023000150300ustar 00000000000000liberapay: conradkleinespel rpassword-7.2.0/.github/workflows/rpassword-rust-tests.yml000064400000000000000000000015301046102023000221540ustar 00000000000000name: rpassword rust tests on: pull_request jobs: rust-linux-tests: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 name: Install rust with: toolchain: stable - uses: actions-rs/cargo@v1 name: Run cargo test with: command: test args: --all-targets --all-features --manifest-path Cargo.toml rust-windows-tests: runs-on: windows-latest steps: - name: Checkout code uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 name: Install rust with: toolchain: stable - uses: actions-rs/cargo@v1 name: Run cargo test with: command: test args: --all-targets --all-features --manifest-path Cargo.toml rpassword-7.2.0/.gitignore000064400000000000000000000000241046102023000136420ustar 00000000000000/target/ /Cargo.lockrpassword-7.2.0/CONTRIBUTING.md000064400000000000000000000023031046102023000141050ustar 00000000000000# Contributing Development for this project takes place in the [conradkleinespel/duck](https://github.com/conradkleinespel/duck) repository, a mono-repo that makes code reuse easier. You are welcome to contribute to this project, following a couple of guidelines. The main principle is that we want to respect each other's time. ## Bug reports Bug reports should include instructions for how to reproduce step-by-step, include useful information such as operating system, version of Rust and Cargo used to compile, screenshots, log output, etc. Bug reports that do not give sufficient information to understand and reproduce the bug will be closed. If you have the necessary skills, you should always attempt to fix the bug yourself. Whenever possible, you should add a unit or integration test so that we don't accidentally reintroduce the bug later. ## New features Before working on a new feature, open an issue to discuss your plans. We'll tell you if we think it falls into the scope of this project, so you only spend time implementing changes we're willing to review and merge. New features should include unit tests and integration tests if applicable, so that future development don't break your code. rpassword-7.2.0/Cargo.toml0000644000000023650000000000100110720ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.60" name = "rpassword" version = "7.2.0" authors = ["Conrad Kleinespel "] description = "Read passwords in console applications." homepage = "https://github.com/conradkleinespel/rpassword" documentation = "https://docs.rs/rpassword/" readme = "README.md" keywords = [ "read", "password", "security", "pass", "getpass", ] license = "Apache-2.0" repository = "https://github.com/conradkleinespel/rpassword" [dependencies.rtoolbox] version = "0.0" [target."cfg(unix)".dependencies.libc] version = "0.2" [target."cfg(windows)".dependencies.winapi] version = "0.3" features = [ "std", "winnt", "fileapi", "processenv", "winbase", "handleapi", "consoleapi", "minwindef", "wincon", ] rpassword-7.2.0/Cargo.toml.orig000064400000000000000000000013771046102023000145550ustar 00000000000000[package] name = "rpassword" version = "7.2.0" authors = ["Conrad Kleinespel "] description = "Read passwords in console applications." license = "Apache-2.0" homepage = "https://github.com/conradkleinespel/rpassword" repository = "https://github.com/conradkleinespel/rpassword" documentation = "https://docs.rs/rpassword/" readme = "README.md" keywords = ["read", "password", "security", "pass", "getpass"] edition = "2018" rust-version = "1.60" [target.'cfg(unix)'.dependencies] libc = "0.2" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["std", "winnt", "fileapi", "processenv", "winbase", "handleapi", "consoleapi", "minwindef", "wincon"] } [dependencies] rtoolbox = { path = "../rtoolbox", version = "0.0" } rpassword-7.2.0/LICENSE-APACHE000064400000000000000000000236751046102023000136170ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS rpassword-7.2.0/README.md000064400000000000000000000034101046102023000131330ustar 00000000000000# Rustastic Password `rpassword` makes it easy to read passwords in a console application on all platforms, Unix, Windows, WASM, etc. `rpassword` is made available free of charge. You can support its development through [Liberapay](https://liberapay.com/conradkleinespel/) 💪 ## Usage Add `rpassword` as a dependency in Cargo.toml: ```toml [dependencies] rpassword = "7.2" ``` See examples and docs at [https://docs.rs/rpassword](https://docs.rs/rpassword). ## Contributors We welcome contribution from everyone. Feel free to open an issue or a pull request at any time. Here's a list of existing `rpassword` contributors: * [@BlackHoleFox](https://github.com/BlackHoleFox) * [@C4K3](https://github.com/C4K3) * [@conradkleinespel](https://github.com/conradkleinespel) * [@DaveLancaster](https://github.com/DaveLancaster) * [@dcuddeback](https://github.com/dcuddeback) * [@Draphar](https://github.com/Draphar) * [@dvermd](https://github.com/dvermd) * [@equalsraf](https://github.com/equalsraf) * [@Heliozoa](https://github.com/Heliozoa) * [@JanLikar](https://github.com/JanLikar) * [@john-sharratt](https://github.com/john-sharratt) * [@joshuef](https://github.com/joshuef) * [@longshorej](https://github.com/longshorej) * [@LSchallot](https://github.com/LSchallot) * [@nicokoch](https://github.com/nicokoch) * [@NovaliX-Dev](https://github.com/NovaliX-Dev) * [@petevine](https://github.com/petevine) * [@psych0d0g](https://github.com/psych0d0g) * [@retep998](https://github.com/retep998) * [@steveatinfincia](https://github.com/steveatinfincia) * [@teythoon](https://github.com/teythoon) * [@tov](https://github.com/tov) * [@yandexx](https://github.com/yandexx) Thank you very much for your help! :smiley: :heart: ## License The source code is released under the Apache 2.0 license. rpassword-7.2.0/src/lib.rs000064400000000000000000000230321046102023000135610ustar 00000000000000//! This library makes it easy to read passwords in a console application on all platforms, Unix, //! Windows, WASM, etc. //! //! Here's how you can read a password: //! ```no_run //! let password = rpassword::read_password().unwrap(); //! println!("Your password is {}", password); //! ``` //! //! You can also prompt for a password: //! ```no_run //! let password = rpassword::prompt_password("Your password: ").unwrap(); //! println!("Your password is {}", password); //! ``` //! //! Finally, in unit tests, you might want to pass a `Cursor`, which implements `BufRead`. In that //! case, you can use `read_password_from_bufread` and `prompt_password_from_bufread`: //! ``` //! use std::io::Cursor; //! //! let mut mock_input = Cursor::new("my-password\n".as_bytes().to_owned()); //! let password = rpassword::read_password_from_bufread(&mut mock_input).unwrap(); //! println!("Your password is {}", password); //! //! let mut mock_input = Cursor::new("my-password\n".as_bytes().to_owned()); //! let mut mock_output = Cursor::new(Vec::new()); //! let password = rpassword::prompt_password_from_bufread(&mut mock_input, &mut mock_output, "Your password: ").unwrap(); //! println!("Your password is {}", password); //! ``` use rtoolbox::fix_line_issues::fix_line_issues; use rtoolbox::print_tty::{print_tty, print_writer}; use rtoolbox::safe_string::SafeString; use std::io::{BufRead, Write}; #[cfg(target_family = "wasm")] mod wasm { use std::io::{self, BufRead}; /// Reads a password from the TTY pub fn read_password() -> std::io::Result { let tty = std::fs::File::open("/dev/tty")?; let mut reader = io::BufReader::new(tty); read_password_from_fd_with_hidden_input(&mut reader) } /// Reads a password from a given file descriptor fn read_password_from_fd_with_hidden_input( reader: &mut impl BufRead, ) -> std::io::Result { let mut password = super::SafeString::new(); reader.read_line(&mut password)?; super::fix_line_issues(password.into_inner()) } } #[cfg(target_family = "unix")] mod unix { use libc::{c_int, tcsetattr, termios, ECHO, ECHONL, TCSANOW}; use std::io::{self, BufRead}; use std::mem; use std::os::unix::io::AsRawFd; struct HiddenInput { fd: i32, term_orig: termios, } impl HiddenInput { fn new(fd: i32) -> io::Result { // 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(fd)?; let term_orig = safe_tcgetattr(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(fd, TCSANOW, &term) })?; Ok(HiddenInput { fd, term_orig }) } } impl Drop for HiddenInput { fn drop(&mut self) { // Set the the mode back to normal unsafe { tcsetattr(self.fd, TCSANOW, &self.term_orig); } } } /// 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 { let mut term = mem::MaybeUninit::::uninit(); io_result(unsafe { ::libc::tcgetattr(fd, term.as_mut_ptr()) })?; Ok(unsafe { term.assume_init() }) } /// Reads a password from the TTY pub fn read_password() -> std::io::Result { let tty = std::fs::File::open("/dev/tty")?; let fd = tty.as_raw_fd(); let mut reader = io::BufReader::new(tty); read_password_from_fd_with_hidden_input(&mut reader, fd) } /// Reads a password from a given file descriptor fn read_password_from_fd_with_hidden_input( reader: &mut impl BufRead, fd: i32, ) -> std::io::Result { let mut password = super::SafeString::new(); let hidden_input = HiddenInput::new(fd)?; reader.read_line(&mut password)?; std::mem::drop(hidden_input); super::fix_line_issues(password.into_inner()) } } #[cfg(target_family = "windows")] mod windows { use std::io::{self, BufReader}; use std::io::{BufRead, StdinLock}; use std::os::windows::io::FromRawHandle; use winapi::shared::minwindef::LPDWORD; use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode}; use winapi::um::fileapi::{CreateFileA, GetFileType, OPEN_EXISTING}; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::processenv::GetStdHandle; use winapi::um::winbase::{FILE_TYPE_PIPE, STD_INPUT_HANDLE}; use winapi::um::wincon::{ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT}; use winapi::um::winnt::{ FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE, HANDLE, }; struct HiddenInput { mode: u32, handle: HANDLE, } impl HiddenInput { fn new(handle: HANDLE) -> io::Result { let mut mode = 0; // Get the old mode so we can reset back to it when we are done 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()); } Ok(HiddenInput { mode, handle }) } } impl Drop for HiddenInput { fn drop(&mut self) { // Set the the mode back to normal unsafe { SetConsoleMode(self.handle, self.mode); } } } /// Reads a password from the TTY pub fn read_password() -> std::io::Result { let handle = unsafe { CreateFileA( b"CONIN$\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 = BufReader::new(unsafe { std::fs::File::from_raw_handle(handle) }); read_password_from_handle_with_hidden_input(&mut stream, handle) } /// Reads a password from a given file handle fn read_password_from_handle_with_hidden_input( reader: &mut impl BufRead, handle: HANDLE, ) -> io::Result { let mut password = super::SafeString::new(); let hidden_input = HiddenInput::new(handle)?; let reader_return = reader.read_line(&mut password); // Newline for windows which otherwise prints on the same line. println!(); if reader_return.is_err() { return Err(reader_return.unwrap_err()); } std::mem::drop(hidden_input); super::fix_line_issues(password.into_inner()) } } #[cfg(target_family = "unix")] pub use unix::read_password; #[cfg(target_family = "wasm")] pub use wasm::read_password; #[cfg(target_family = "windows")] pub use windows::read_password; /// Reads a password from anything that implements BufRead pub fn read_password_from_bufread(reader: &mut impl BufRead) -> std::io::Result { let mut password = SafeString::new(); reader.read_line(&mut password)?; fix_line_issues(password.into_inner()) } /// Prompts on the TTY and then reads a password from anything that implements BufRead pub fn prompt_password_from_bufread( reader: &mut impl BufRead, writer: &mut impl Write, prompt: impl ToString, ) -> std::io::Result { print_writer(writer, prompt.to_string().as_str()) .and_then(|_| read_password_from_bufread(reader)) } /// Prompts on the TTY and then reads a password from TTY pub fn prompt_password(prompt: impl ToString) -> std::io::Result { print_tty(prompt.to_string().as_str()).and_then(|_| read_password()) } #[cfg(test)] mod tests { use std::io::Cursor; fn mock_input_crlf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\r\nAnother mocked response.\r\n"[..]) } fn mock_input_lf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\nAnother mocked response.\n"[..]) } #[test] fn can_read_from_redirected_input_many_times() { let mut reader_crlf = mock_input_crlf(); let response = super::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "A mocked response."); let response = super::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "Another mocked response."); let mut reader_lf = mock_input_lf(); let response = super::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "A mocked response."); let response = super::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "Another mocked response."); } } rpassword-7.2.0/tests/no-terminal.rs000064400000000000000000000037771046102023000156310ustar 00000000000000//! This test checks whether or not we can read from a reader when //! stdin is not a terminal. use std::io::Cursor; use rpassword::read_password_from_bufread; #[cfg(unix)] #[cfg(unix)] fn close_stdin() { unsafe { libc::close(libc::STDIN_FILENO); } } #[cfg(windows)] #[cfg(windows)] fn close_stdin() { use winapi::um::handleapi::CloseHandle; use winapi::um::processenv::GetStdHandle; use winapi::um::winbase::STD_INPUT_HANDLE; unsafe { CloseHandle(GetStdHandle(STD_INPUT_HANDLE)); } } #[cfg(not(any(unix, windows)))] fn close_stdin() { unimplemented!() } fn mock_input_crlf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\r\nAnother mocked response.\r\n"[..]) } fn mock_input_lf() -> Cursor<&'static [u8]> { Cursor::new(&b"A mocked response.\nAnother mocked response.\n"[..]) } #[test] fn can_read_from_redirected_input_many_times() { close_stdin(); let mut reader_crlf = mock_input_crlf(); let response = crate::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::read_password_from_bufread(&mut reader_crlf).unwrap(); assert_eq!(response, "Another mocked response."); let mut reader_lf = mock_input_lf(); let response = crate::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "A mocked response."); let response = crate::read_password_from_bufread(&mut reader_lf).unwrap(); assert_eq!(response, "Another mocked response."); } #[test] fn can_read_from_input_ctrl_u() { close_stdin(); let mut reader_ctrl_u = Cursor::new(&b"A mocked response.Another mocked response.\n"[..]); let response = crate::read_password_from_bufread(&mut reader_ctrl_u).unwrap(); assert_eq!(response, "Another mocked response."); let mut reader_ctrl_u_at_end = Cursor::new(&b"A mocked response.\n"[..]); let response = crate::read_password_from_bufread(&mut reader_ctrl_u_at_end).unwrap(); assert_eq!(response, ""); }