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::{
127    error,
128    ffi::CStr,
129    fmt::{self, Display},
130    io, mem,
131    str::Utf8Error,
132};
133
134use bitflags::bitflags;
135#[cfg(any(docsrs, not(feature = "zeroize")))]
136pub use our_zeroize::Zeroize;
137#[cfg(all(not(docsrs), feature = "zeroize"))]
138pub use zeroize::Zeroize;
139
140/// Size of buffer used in [`getpass`].
141///
142/// Because `readpassphrase(3)` null-terminates its string, the actual maximum password length for
143/// [`getpass`] is 255.
144pub const PASSWORD_LEN: usize = 256;
145
146bitflags! {
147    /// Flags for controlling readpassphrase.
148    ///
149    /// The default flag `ECHO_OFF` is not represented here because `bitflags` [recommends against
150    /// zero-bit flags][0]; it may be specified as either [`Flags::empty()`] or
151    /// [`Flags::default()`].
152    ///
153    /// Note that the Windows `readpassphrase(3)` implementation always acts like it has been
154    /// passed `ECHO_OFF`, i.e., the flags are ignored.
155    ///
156    /// [0]: https://docs.rs/bitflags/latest/bitflags/#zero-bit-flags
157    #[derive(Default)]
158    pub struct Flags: i32 {
159        /// Leave echo on.
160        const ECHO_ON     = 0x01;
161        /// Fail if there is no tty.
162        const REQUIRE_TTY = 0x02;
163        /// Force input to lower case.
164        const FORCELOWER  = 0x04;
165        /// Force input to upper case.
166        const FORCEUPPER  = 0x08;
167        /// Strip the high bit from input.
168        const SEVENBIT    = 0x10;
169        /// Read from stdin, not `/dev/tty`.
170        const STDIN       = 0x20;
171    }
172}
173
174/// Errors that can occur in readpassphrase.
175#[derive(Debug)]
176pub enum Error {
177    /// `readpassphrase(3)` itself encountered an error.
178    Io(io::Error),
179    /// The entered password was not UTF-8.
180    Utf8(Utf8Error),
181}
182
183/// Reads a passphrase using `readpassphrase(3)`, returning a [`&str`](str).
184///
185/// This function reads a password of up to `buf.len() - 1` bytes into `buf`. If the entered
186/// password is longer, it is truncated to the maximum length. If `readpasspharse(3)` itself fails,
187/// or if the entered password is not valid UTF-8, then [`Error`] is returned.
188///
189/// # Security
190/// The passed buffer might contain sensitive data, even if this function returns an error.
191/// Therefore it should be zeroed as soon as possible. This can be achieved, for example, with
192/// [`zeroize::Zeroizing`]:
193/// ```no_run
194/// # use readpassphrase_3::{PASSWORD_LEN, Error, Flags, readpassphrase};
195/// use zeroize::Zeroizing;
196/// # fn main() -> Result<(), Error> {
197/// let mut buf = Zeroizing::new(vec![0u8; PASSWORD_LEN]);
198/// let pass = readpassphrase(c"Pass: ", &mut buf, Flags::default())?;
199/// # Ok(())
200/// # }
201/// ```
202pub fn readpassphrase<'a>(
203    prompt: &CStr,
204    buf: &'a mut [u8],
205    flags: Flags,
206) -> Result<&'a str, Error> {
207    unsafe {
208        let res = ffi::readpassphrase(
209            prompt.as_ptr(),
210            buf.as_mut_ptr().cast(),
211            buf.len(),
212            flags.bits(),
213        );
214        if res.is_null() {
215            return Err(io::Error::last_os_error().into());
216        }
217    }
218    Ok(CStr::from_bytes_until_nul(buf).unwrap().to_str()?)
219}
220
221/// Reads a passphrase using `readpassphrase(3)`, returning a [`String`].
222///
223/// Internally, this function uses a buffer of [`PASSWORD_LEN`] bytes, allowing for passwords up to
224/// `PASSWORD_LEN - 1` characters (accounting for the C null terminator.) If the entered passphrase
225/// is longer, it will be truncated to the maximum length.
226///
227/// # Security
228/// The returned `String` is owned by the caller, and therefore it is the caller’s responsibility
229/// to clear it when you are done with it:
230/// ```no_run
231/// # use readpassphrase_3::{Error, Zeroize, getpass};
232/// # fn main() -> Result<(), Error> {
233/// let mut pass = getpass(c"Pass: ")?;
234/// _ = pass;
235/// pass.zeroize();
236/// # Ok(())
237/// # }
238/// ```
239pub fn getpass(prompt: &CStr) -> Result<String, Error> {
240    Ok(readpassphrase_owned(
241        prompt,
242        vec![0u8; PASSWORD_LEN],
243        Flags::empty(),
244    )?)
245}
246
247/// An [`Error`] from [`readpassphrase_owned`] containing the passed buffer.
248///
249/// The buffer is accessible via [`OwnedError::take`]. If [`take`](OwnedError::take) is not called,
250/// the buffer is automatically zeroed on drop.
251#[derive(Debug)]
252pub struct OwnedError(Error, Option<Vec<u8>>);
253
254/// Reads a passphrase using `readpassphrase(3)`, returning `buf` as a [`String`].
255///
256/// This function reads a passphrase of up to `buf.capacity() - 1` bytes. If the entered passphrase
257/// is longer, it will be truncated.
258///
259/// The returned [`String`] reuses `buf`’s memory; no copies are made. On error, the original
260/// buffer is instead returned via [`OwnedError`] and may be reused. `OwnedError` converts to
261/// [`Error`], so the `?` operator may be used with functions that return `Error`.
262///
263/// **NB**. Sometimes in Rust the capacity of a vector may be larger than you expect; if you need a
264/// precise limit on the length of the entered password, either use [`readpassphrase`] or truncate
265/// the returned string.
266///
267/// # Security
268/// The returned `String` is owned by the caller, and it is the caller’s responsibility to clear
269/// it. This can be done via [`Zeroize`], e.g.:
270/// ```no_run
271/// # use readpassphrase_3::{
272/// #     PASSWORD_LEN,
273/// #     Error,
274/// #     Flags,
275/// #     readpassphrase_owned,
276/// # };
277/// # use readpassphrase_3::Zeroize;
278/// # fn main() -> Result<(), Error> {
279/// let buf = vec![0u8; PASSWORD_LEN];
280/// let mut pass = readpassphrase_owned(c"Pass: ", buf, Flags::default())?;
281/// _ = pass;
282/// pass.zeroize();
283/// # Ok(())
284/// # }
285/// ```
286pub fn readpassphrase_owned(
287    prompt: &CStr,
288    mut buf: Vec<u8>,
289    flags: Flags,
290) -> Result<String, OwnedError> {
291    readpassphrase_mut(prompt, &mut buf, flags).map_err(|e| {
292        buf.clear();
293        OwnedError(e, Some(buf))
294    })
295}
296
297// Reads a passphrase into `buf`’s maybe-uninitialized capacity and returns it as a `String`
298// reusing `buf`’s memory on success. This function serves to make it possible to write
299// `readpassphrase_owned` without either pre-initializing the buffer or invoking undefined
300// behavior by constructing a maybe-uninitialized slice.
301fn readpassphrase_mut(prompt: &CStr, buf: &mut Vec<u8>, flags: Flags) -> Result<String, Error> {
302    unsafe {
303        let res = ffi::readpassphrase(
304            prompt.as_ptr(),
305            buf.as_mut_ptr().cast(),
306            buf.capacity(),
307            flags.bits(),
308        );
309        if res.is_null() {
310            return Err(io::Error::last_os_error().into());
311        }
312        let res = CStr::from_ptr(res).to_str()?;
313        buf.set_len(res.len());
314        Ok(String::from_utf8_unchecked(mem::take(buf)))
315    }
316}
317
318impl OwnedError {
319    /// Take `buf` out of the error.
320    ///
321    /// Returns empty [`Vec`] after the first call.
322    pub fn take(&mut self) -> Vec<u8> {
323        self.1.take().unwrap_or_default()
324    }
325}
326
327impl Drop for OwnedError {
328    fn drop(&mut self) {
329        self.1.take().as_mut().map(Zeroize::zeroize);
330    }
331}
332
333impl From<OwnedError> for Error {
334    fn from(mut value: OwnedError) -> Self {
335        mem::replace(&mut value.0, Error::Io(io::ErrorKind::Other.into()))
336    }
337}
338
339impl From<io::Error> for Error {
340    fn from(value: io::Error) -> Self {
341        Error::Io(value)
342    }
343}
344
345impl From<Utf8Error> for Error {
346    fn from(value: Utf8Error) -> Self {
347        Error::Utf8(value)
348    }
349}
350
351impl error::Error for OwnedError {
352    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
353        Some(&self.0)
354    }
355}
356
357impl Display for OwnedError {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        self.0.fmt(f)
360    }
361}
362
363impl error::Error for Error {
364    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
365        Some(match self {
366            Error::Io(e) => e,
367            Error::Utf8(e) => e,
368        })
369    }
370}
371
372impl Display for Error {
373    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374        match self {
375            Error::Io(e) => e.fmt(f),
376            Error::Utf8(e) => e.fmt(f),
377        }
378    }
379}
380
381#[cfg(any(docsrs, not(feature = "zeroize")))]
382mod our_zeroize {
383    use std::{arch::asm, mem::MaybeUninit};
384
385    /// A minimal in-crate implementation of a subset of [`zeroize::Zeroize`].
386    ///
387    /// This provides compile-fenced memory zeroing for [`String`]s and [`Vec`]s without needing to
388    /// depend on the `zeroize` crate.
389    ///
390    /// If the optional `zeroize` feature is enabled, then the trait is replaced with a re-export of
391    /// `zeroize::Zeroize` itself.
392    pub trait Zeroize {
393        fn zeroize(&mut self);
394    }
395
396    impl Zeroize for Vec<u8> {
397        fn zeroize(&mut self) {
398            self.clear();
399            let buf = self.spare_capacity_mut();
400            buf.fill(MaybeUninit::zeroed());
401            compile_fence(buf);
402        }
403    }
404
405    impl Zeroize for String {
406        fn zeroize(&mut self) {
407            unsafe { self.as_mut_vec() }.zeroize();
408        }
409    }
410
411    impl Zeroize for [u8] {
412        fn zeroize(&mut self) {
413            self.fill(0);
414            compile_fence(self);
415        }
416    }
417
418    fn compile_fence<T>(buf: &[T]) {
419        unsafe {
420            asm!(
421                "/* {ptr} */",
422                ptr = in(reg) buf.as_ptr(),
423                options(nostack, preserves_flags, readonly)
424            );
425        }
426    }
427}
428
429mod ffi {
430    use std::ffi::{c_char, c_int};
431
432    extern "C" {
433        pub(crate) fn readpassphrase(
434            prompt: *const c_char,
435            buf: *mut c_char,
436            bufsiz: usize,
437            flags: c_int,
438        ) -> *mut c_char;
439    }
440}