readpassphrase_3/
lib.rs

1// Copyright 2025
2//	Steven Dee
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions
6// are met:
7//
8// Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//
11// THIS SOFTWARE IS PROVIDED BY STEVEN DEE “AS IS” AND ANY EXPRESS
12// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
13// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14// ARE DISCLAIMED. IN NO EVENT SHALL STEVEN DEE BE LIABLE FOR ANY
15// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
16// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
17// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
18// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
19// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
20// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
21// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22
23//! Lightweight, easy-to-use wrapper around the C [`readpassphrase(3)`][0] function.
24//!
25//! From the man page:
26//! > The `readpassphrase()` function displays a prompt to, and reads in a passphrase from,
27//! > `/dev/tty`. If this file is inaccessible and the [`RPP_REQUIRE_TTY`](Flags::REQUIRE_TTY) flag
28//! > is not set, `readpassphrase()` displays the prompt on the standard error output and reads
29//! > from the standard input.
30//!
31//! # Usage
32//! For the simplest of cases, where you would just like to read a password from the console into a
33//! [`String`] to use elsewhere, you can use [`getpass`]:
34//! ```no_run
35//! use readpassphrase_3::getpass;
36//! let _ = getpass(c"Enter your password: ").expect("failed reading password");
37//! ```
38//!
39//! If you need to pass [`Flags`] or to control the buffer size, then you can use
40//! [`readpassphrase`] or [`readpassphrase_owned`] depending on your ownership requirements:
41//! ```no_run
42//! let mut buf = vec![0u8; 256];
43//! use readpassphrase_3::{Flags, readpassphrase};
44//! let pass: &str = readpassphrase(c"Password: ", &mut buf, Flags::default()).unwrap();
45//!
46//! use readpassphrase_3::readpassphrase_owned;
47//! let pass: String = readpassphrase_owned(c"Pass: ", buf, Flags::FORCELOWER).unwrap();
48//! # _ = pass;
49//! ```
50//!
51//! # Security
52//! The [`readpassphrase(3)` man page][0] says:
53//! > The calling process should zero the passphrase as soon as possible to avoid leaving the
54//! > cleartext passphrase visible in the process's address space.
55//!
56//! It is your job to ensure that this is done with the data you own, i.e.
57//! any [`Vec`] passed to [`readpassphrase`] or any [`String`] received from [`getpass`] or
58//! [`readpassphrase_owned`].
59//!
60//! This crate ships with a minimal [`Zeroize`] trait that may be used for this purpose:
61//! ```no_run
62//! # use readpassphrase_3::{Flags, getpass, readpassphrase, readpassphrase_owned};
63//! use readpassphrase_3::Zeroize;
64//! let mut pass = getpass(c"password: ").unwrap();
65//! // do_something_with(&pass);
66//! pass.zeroize();
67//!
68//! let mut buf = vec![0u8; 256];
69//! let res = readpassphrase(c"password: ", &mut buf, Flags::empty());
70//! // match_something_on(res);
71//! buf.zeroize();
72//!
73//! let mut pass = readpassphrase_owned(c"password: ", buf, Flags::empty()).unwrap();
74//! // do_something_with(&pass);
75//! pass.zeroize();
76//! ```
77//!
78//! ## Zeroizing memory
79//! This crate works well with the [`zeroize`] crate. For example, [`zeroize::Zeroizing`] may be
80//! used to zero buffer contents regardless of a function’s control flow:
81//! ```no_run
82//! # use readpassphrase_3::{Error, Flags, PASSWORD_LEN, getpass, readpassphrase};
83//! use zeroize::Zeroizing;
84//! # fn main() -> Result<(), Error> {
85//! let mut buf = Zeroizing::new(vec![0u8; PASSWORD_LEN]);
86//! let pass = readpassphrase(c"pass: ", &mut buf, Flags::REQUIRE_TTY)?;
87//! // do_something_that_can_fail_with(pass)?;
88//!
89//! // Or alternatively:
90//! let pass = Zeroizing::new(getpass(c"pass: ")?);
91//! // do_something_that_can_fail_with(&pass)?;
92//! # Ok(())
93//! # }
94//! ```
95//!
96//! If this crate’s `zeroize` feature is enabled, then its [`Zeroize`] will be replaced by a
97//! re-export of the upstream [`zeroize::Zeroize`].
98//!
99//! # “Mismatched types” errors
100//! The prompt strings in this API are references to [CStr], not [str]. This is because the
101//! underlying C function assumes that the prompt is a null-terminated string; were we to take
102//! `&str` instead of `&CStr`, we would need to make a copy of the prompt on every call.
103//!
104//! Most of the time, your prompts will be string literals; you can ask Rust to give you a `&CStr`
105//! literal by simply prepending `c` to the string:
106//! ```no_run
107//! # use readpassphrase_3::{Error, getpass};
108//! # fn main() -> Result<(), Error> {
109//! let _ = getpass(c"pass: ")?;
110//! //              ^
111//! //              |
112//! //              like this
113//! # Ok(())
114//! # }
115//! ```
116//!
117//! If you need a dynamic prompt, look at [`CString`](std::ffi::CString).
118//!
119//! # Windows Limitations
120//! The Windows implementation of `readpassphrase(3)` that we are using does not yet support UTF-8
121//! in prompts; they must be ASCII. It also does not yet support flags, and always behaves as
122//! though called with [`Flags::empty()`].
123//!
124//! [0]: https://man.openbsd.org/readpassphrase
125
126use std::{ffi::CStr, fmt::Display, io, mem, str::Utf8Error};
127
128use bitflags::bitflags;
129#[cfg(any(docsrs, not(feature = "zeroize")))]
130pub use our_zeroize::Zeroize;
131#[cfg(all(not(docsrs), feature = "zeroize"))]
132pub use zeroize::Zeroize;
133
134/// Size of buffer used in [`getpass`].
135///
136/// Because `readpassphrase(3)` null-terminates its string, the actual maximum password length for
137/// [`getpass`] is 255.
138pub const PASSWORD_LEN: usize = 256;
139
140bitflags! {
141    /// Flags for controlling readpassphrase.
142    ///
143    /// The default flag `ECHO_OFF` is not represented here because `bitflags` [recommends against
144    /// zero-bit flags][0]; it may be specified as either [`Flags::empty()`] or
145    /// [`Flags::default()`].
146    ///
147    /// Note that the Windows `readpassphrase(3)` implementation always acts like it has been
148    /// passed `ECHO_OFF`, i.e., the flags are ignored.
149    ///
150    /// [0]: https://docs.rs/bitflags/latest/bitflags/#zero-bit-flags
151    #[derive(Default)]
152    pub struct Flags: i32 {
153        /// Leave echo on.
154        const ECHO_ON     = 0x01;
155        /// Fail if there is no tty.
156        const REQUIRE_TTY = 0x02;
157        /// Force input to lower case.
158        const FORCELOWER  = 0x04;
159        /// Force input to upper case.
160        const FORCEUPPER  = 0x08;
161        /// Strip the high bit from input.
162        const SEVENBIT    = 0x10;
163        /// Read from stdin, not `/dev/tty`.
164        const STDIN       = 0x20;
165    }
166}
167
168/// Errors that can occur in readpassphrase.
169#[derive(Debug)]
170pub enum Error {
171    /// `readpassphrase(3)` itself encountered an error.
172    Io(io::Error),
173    /// The entered password was not UTF-8.
174    Utf8(Utf8Error),
175}
176
177/// Reads a passphrase using `readpassphrase(3)`, returning a [`&str`](str).
178///
179/// This function reads a password of up to `buf.len() - 1` bytes into `buf`. If the entered
180/// password is longer, it is truncated to the maximum length. If `readpasspharse(3)` itself fails,
181/// or if the entered password is not valid UTF-8, then [`Error`] is returned.
182///
183/// # Security
184/// The passed buffer might contain sensitive data, even if this function returns an error.
185/// Therefore it should be zeroed as soon as possible. This can be achieved, for example, with
186/// [`zeroize::Zeroizing`]:
187/// ```no_run
188/// # use readpassphrase_3::{PASSWORD_LEN, Error, Flags, readpassphrase};
189/// use zeroize::Zeroizing;
190/// # fn main() -> Result<(), Error> {
191/// let mut buf = Zeroizing::new(vec![0u8; PASSWORD_LEN]);
192/// let pass = readpassphrase(c"Pass: ", &mut buf, Flags::default())?;
193/// # Ok(())
194/// # }
195/// ```
196pub fn readpassphrase<'a>(
197    prompt: &CStr,
198    buf: &'a mut [u8],
199    flags: Flags,
200) -> Result<&'a str, Error> {
201    unsafe {
202        let res = ffi::readpassphrase(
203            prompt.as_ptr(),
204            buf.as_mut_ptr().cast(),
205            buf.len(),
206            flags.bits(),
207        );
208        if res.is_null() {
209            return Err(io::Error::last_os_error().into());
210        }
211    }
212    Ok(CStr::from_bytes_until_nul(buf).unwrap().to_str()?)
213}
214
215/// Reads a passphrase using `readpassphrase(3)`, returning a [`String`].
216///
217/// Internally, this function uses a buffer of [`PASSWORD_LEN`] bytes, allowing for passwords up to
218/// `PASSWORD_LEN - 1` characters (accounting for the C null terminator.) If the entered passphrase
219/// is longer, it will be truncated to the maximum length.
220///
221/// # Security
222/// The returned `String` is owned by the caller, and therefore it is the caller’s responsibility
223/// to clear it when you are done with it:
224/// ```no_run
225/// # use readpassphrase_3::{Error, Zeroize, getpass};
226/// # fn main() -> Result<(), Error> {
227/// let mut pass = getpass(c"Pass: ")?;
228/// _ = pass;
229/// pass.zeroize();
230/// # Ok(())
231/// # }
232/// ```
233pub fn getpass(prompt: &CStr) -> Result<String, Error> {
234    Ok(readpassphrase_owned(
235        prompt,
236        vec![0u8; PASSWORD_LEN],
237        Flags::empty(),
238    )?)
239}
240
241/// An [`Error`] from [`readpassphrase_owned`] containing the passed buffer.
242///
243/// The buffer is accessible via [`OwnedError::take`]. If [`take`](OwnedError::take) is not called,
244/// the buffer is automatically zeroed on drop.
245#[derive(Debug)]
246pub struct OwnedError(Error, Option<Vec<u8>>);
247
248/// Reads a passphrase using `readpassphrase(3)`, returning `buf` as a [`String`].
249///
250/// This function reads a passphrase of up to `buf.capacity() - 1` bytes. If the entered passphrase
251/// is longer, it will be truncated.
252///
253/// The returned [`String`] reuses `buf`’s memory; no copies are made. On error, the original
254/// buffer is instead returned via [`OwnedError`] and may be reused. `OwnedError` converts to
255/// [`Error`], so the `?` operator may be used with functions that return `Error`.
256///
257/// **NB**. Sometimes in Rust the capacity of a vector may be larger than you expect; if you need a
258/// precise limit on the length of the entered password, either use [`readpassphrase`] or truncate
259/// the returned string.
260///
261/// # Security
262/// The returned `String` is owned by the caller, and it is the caller’s responsibility to clear
263/// it. This can be done via [`Zeroize`], e.g.:
264/// ```no_run
265/// # use readpassphrase_3::{
266/// #     PASSWORD_LEN,
267/// #     Error,
268/// #     Flags,
269/// #     readpassphrase_owned,
270/// # };
271/// # use readpassphrase_3::Zeroize;
272/// # fn main() -> Result<(), Error> {
273/// let buf = vec![0u8; PASSWORD_LEN];
274/// let mut pass = readpassphrase_owned(c"Pass: ", buf, Flags::default())?;
275/// _ = pass;
276/// pass.zeroize();
277/// # Ok(())
278/// # }
279/// ```
280pub fn readpassphrase_owned(
281    prompt: &CStr,
282    mut buf: Vec<u8>,
283    flags: Flags,
284) -> Result<String, OwnedError> {
285    readpassphrase_mut(prompt, &mut buf, flags).map_err(|e| {
286        buf.clear();
287        OwnedError(e, Some(buf))
288    })
289}
290
291// Reads a passphrase into `buf`’s maybe-uninitialized capacity and returns it as a `String`
292// reusing `buf`’s memory on success. This function serves to make it possible to write
293// `readpassphrase_owned` without either pre-initializing the buffer or invoking undefined
294// behavior by constructing a maybe-uninitialized slice.
295fn readpassphrase_mut(prompt: &CStr, buf: &mut Vec<u8>, flags: Flags) -> Result<String, Error> {
296    unsafe {
297        let res = ffi::readpassphrase(
298            prompt.as_ptr(),
299            buf.as_mut_ptr().cast(),
300            buf.capacity(),
301            flags.bits(),
302        );
303        if res.is_null() {
304            return Err(io::Error::last_os_error().into());
305        }
306        let res = CStr::from_ptr(res).to_str()?;
307        buf.set_len(res.len());
308        Ok(String::from_utf8_unchecked(mem::take(buf)))
309    }
310}
311
312impl OwnedError {
313    /// Take `buf` out of the error.
314    ///
315    /// Returns empty [`Vec`] after the first call.
316    pub fn take(&mut self) -> Vec<u8> {
317        self.1.take().unwrap_or_default()
318    }
319}
320
321impl Drop for OwnedError {
322    fn drop(&mut self) {
323        self.1.take().as_mut().map(Zeroize::zeroize);
324    }
325}
326
327impl From<OwnedError> for Error {
328    fn from(mut value: OwnedError) -> Self {
329        mem::replace(&mut value.0, Error::Io(io::ErrorKind::Other.into()))
330    }
331}
332
333impl From<io::Error> for Error {
334    fn from(value: io::Error) -> Self {
335        Error::Io(value)
336    }
337}
338
339impl From<Utf8Error> for Error {
340    fn from(value: Utf8Error) -> Self {
341        Error::Utf8(value)
342    }
343}
344
345impl core::error::Error for OwnedError {
346    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
347        Some(&self.0)
348    }
349}
350
351impl Display for OwnedError {
352    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353        self.0.fmt(f)
354    }
355}
356
357impl core::error::Error for Error {
358    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
359        match self {
360            Error::Io(e) => Some(e),
361            Error::Utf8(e) => Some(e),
362        }
363    }
364}
365
366impl Display for Error {
367    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368        match self {
369            Error::Io(e) => e.fmt(f),
370            Error::Utf8(e) => e.fmt(f),
371        }
372    }
373}
374
375#[cfg(any(docsrs, not(feature = "zeroize")))]
376mod our_zeroize {
377    use std::{arch::asm, mem::MaybeUninit};
378
379    /// A minimal in-crate implementation of a subset of [`zeroize::Zeroize`].
380    ///
381    /// This provides compile-fenced memory zeroing for [`String`]s and [`Vec`]s without needing to
382    /// depend on the `zeroize` crate.
383    ///
384    /// If the optional `zeroize` feature is enabled, then the trait is replaced with a re-export of
385    /// `zeroize::Zeroize` itself.
386    pub trait Zeroize {
387        fn zeroize(&mut self);
388    }
389
390    impl Zeroize for Vec<u8> {
391        fn zeroize(&mut self) {
392            self.clear();
393            let buf = self.spare_capacity_mut();
394            buf.fill(MaybeUninit::zeroed());
395            compile_fence(buf);
396        }
397    }
398
399    impl Zeroize for String {
400        fn zeroize(&mut self) {
401            unsafe { self.as_mut_vec() }.zeroize();
402        }
403    }
404
405    impl Zeroize for [u8] {
406        fn zeroize(&mut self) {
407            self.fill(0);
408            compile_fence(self);
409        }
410    }
411
412    fn compile_fence<T>(buf: &[T]) {
413        unsafe {
414            asm!(
415                "/* {ptr} */",
416                ptr = in(reg) buf.as_ptr(),
417                options(nostack, preserves_flags, readonly)
418            );
419        }
420    }
421}
422
423mod ffi {
424    use std::ffi::{c_char, c_int};
425
426    unsafe extern "C" {
427        pub(crate) unsafe fn readpassphrase(
428            prompt: *const c_char,
429            buf: *mut c_char,
430            bufsiz: usize,
431            flags: c_int,
432        ) -> *mut c_char;
433    }
434}