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::{error, ffi::CStr, fmt, 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 let prompt = prompt.as_ptr();
202 let buf_ptr = buf.as_mut_ptr().cast();
203 let bufsiz = buf.len();
204 let flags = flags.bits();
205 let res = unsafe { ffi::readpassphrase(prompt, buf_ptr, bufsiz, flags) };
206 if res.is_null() {
207 return Err(io::Error::last_os_error().into());
208 }
209 Ok(CStr::from_bytes_until_nul(buf).unwrap().to_str()?)
210}
211
212/// Reads a passphrase using `readpassphrase(3)`, returning a [`String`].
213///
214/// Internally, this function uses a buffer of [`PASSWORD_LEN`] bytes, allowing for passwords up to
215/// `PASSWORD_LEN - 1` characters (accounting for the C null terminator.) If the entered passphrase
216/// is longer, it will be truncated to the maximum length.
217///
218/// # Security
219/// The returned `String` is owned by the caller, and therefore it is the caller’s responsibility
220/// to clear it when you are done with it:
221/// ```no_run
222/// # use readpassphrase_3::{Error, Zeroize, getpass};
223/// # fn main() -> Result<(), Error> {
224/// let mut pass = getpass(c"Pass: ")?;
225/// _ = pass;
226/// pass.zeroize();
227/// # Ok(())
228/// # }
229/// ```
230pub fn getpass(prompt: &CStr) -> Result<String, Error> {
231 let buf = vec![0u8; PASSWORD_LEN];
232 Ok(readpassphrase_owned(prompt, buf, Flags::empty())?)
233}
234
235/// An [`Error`] from [`readpassphrase_owned`] containing the passed buffer.
236///
237/// The buffer is accessible via [`OwnedError::take`]. If [`take`](OwnedError::take) is not called,
238/// the buffer is automatically zeroed on drop.
239#[derive(Debug)]
240pub struct OwnedError(Error, Option<Vec<u8>>);
241
242/// Reads a passphrase using `readpassphrase(3)`, returning `buf` as a [`String`].
243///
244/// This function reads a passphrase of up to `buf.capacity() - 1` bytes. If the entered passphrase
245/// is longer, it will be truncated.
246///
247/// The returned [`String`] reuses `buf`’s memory; no copies are made. On error, the original
248/// buffer is instead returned via [`OwnedError`] and may be reused. `OwnedError` converts to
249/// [`Error`], so the `?` operator may be used with functions that return `Error`.
250///
251/// **NB**. Sometimes in Rust the capacity of a vector may be larger than you expect; if you need a
252/// precise limit on the length of the entered password, either use [`readpassphrase`] or truncate
253/// the returned string.
254///
255/// # Security
256/// The returned `String` is owned by the caller, and it is the caller’s responsibility to clear
257/// it. This can be done via [`Zeroize`], e.g.:
258/// ```no_run
259/// # use readpassphrase_3::{
260/// # PASSWORD_LEN,
261/// # Error,
262/// # Flags,
263/// # readpassphrase_owned,
264/// # };
265/// # use readpassphrase_3::Zeroize;
266/// # fn main() -> Result<(), Error> {
267/// let buf = vec![0u8; PASSWORD_LEN];
268/// let mut pass = readpassphrase_owned(c"Pass: ", buf, Flags::default())?;
269/// _ = pass;
270/// pass.zeroize();
271/// # Ok(())
272/// # }
273/// ```
274pub fn readpassphrase_owned(
275 prompt: &CStr,
276 mut buf: Vec<u8>,
277 flags: Flags,
278) -> Result<String, OwnedError> {
279 readpassphrase_mut(prompt, &mut buf, flags).map_err(|e| {
280 buf.clear();
281 OwnedError(e, Some(buf))
282 })
283}
284
285// Reads a passphrase into `buf`’s maybe-uninitialized capacity and returns it as a `String`
286// reusing `buf`’s memory on success. This function serves to make it possible to write
287// `readpassphrase_owned` without either pre-initializing the buffer or invoking undefined
288// behavior by constructing a maybe-uninitialized slice.
289fn readpassphrase_mut(prompt: &CStr, buf: &mut Vec<u8>, flags: Flags) -> Result<String, Error> {
290 let prompt = prompt.as_ptr();
291 let buf_ptr = buf.as_mut_ptr().cast();
292 let bufsiz = buf.capacity();
293 let flags = flags.bits();
294 let res = unsafe { ffi::readpassphrase(prompt, buf_ptr, bufsiz, flags) };
295 if res.is_null() {
296 return Err(io::Error::last_os_error().into());
297 }
298 let res = unsafe { CStr::from_ptr(buf_ptr) }.to_str()?;
299 assert!(res.len() < bufsiz);
300 unsafe {
301 buf.set_len(res.len());
302 }
303 let buf = mem::take(buf);
304 Ok(unsafe { String::from_utf8_unchecked(buf) })
305}
306
307impl OwnedError {
308 /// Take `buf` out of the error.
309 ///
310 /// Returns empty [`Vec`] after the first call.
311 pub fn take(&mut self) -> Vec<u8> {
312 self.1.take().unwrap_or_default()
313 }
314}
315
316impl Drop for OwnedError {
317 fn drop(&mut self) {
318 self.1.take().as_mut().map(Zeroize::zeroize);
319 }
320}
321
322impl From<OwnedError> for Error {
323 fn from(mut value: OwnedError) -> Self {
324 mem::replace(&mut value.0, Error::Io(io::ErrorKind::Other.into()))
325 }
326}
327
328impl From<io::Error> for Error {
329 fn from(value: io::Error) -> Self {
330 Error::Io(value)
331 }
332}
333
334impl From<Utf8Error> for Error {
335 fn from(value: Utf8Error) -> Self {
336 Error::Utf8(value)
337 }
338}
339
340impl error::Error for OwnedError {
341 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
342 Some(&self.0)
343 }
344}
345
346impl fmt::Display for OwnedError {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 self.0.fmt(f)
349 }
350}
351
352impl error::Error for Error {
353 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
354 Some(match self {
355 Error::Io(e) => e,
356 Error::Utf8(e) => e,
357 })
358 }
359}
360
361impl fmt::Display for Error {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 match self {
364 Error::Io(e) => e.fmt(f),
365 Error::Utf8(e) => e.fmt(f),
366 }
367 }
368}
369
370#[cfg(any(docsrs, not(feature = "zeroize")))]
371mod our_zeroize {
372 use std::{arch::asm, mem::MaybeUninit};
373
374 /// A minimal in-crate implementation of a subset of [`zeroize::Zeroize`].
375 ///
376 /// This provides compile-fenced memory zeroing for [`String`]s and [`Vec`]s without needing to
377 /// depend on the `zeroize` crate.
378 ///
379 /// If the optional `zeroize` feature is enabled, then the trait is replaced with a re-export of
380 /// `zeroize::Zeroize` itself.
381 pub trait Zeroize {
382 fn zeroize(&mut self);
383 }
384
385 impl Zeroize for Vec<u8> {
386 fn zeroize(&mut self) {
387 self.clear();
388 let buf = self.spare_capacity_mut();
389 buf.fill(MaybeUninit::zeroed());
390 compile_fence(buf);
391 }
392 }
393
394 impl Zeroize for String {
395 fn zeroize(&mut self) {
396 unsafe { self.as_mut_vec() }.zeroize();
397 }
398 }
399
400 impl Zeroize for [u8] {
401 fn zeroize(&mut self) {
402 self.fill(0);
403 compile_fence(self);
404 }
405 }
406
407 fn compile_fence<T>(buf: &[T]) {
408 unsafe {
409 asm!(
410 "/* {ptr} */",
411 ptr = in(reg) buf.as_ptr(),
412 options(nostack, preserves_flags, readonly)
413 );
414 }
415 }
416}
417
418mod ffi {
419 use std::ffi::{c_char, c_int};
420
421 extern "C" {
422 pub(crate) fn readpassphrase(
423 prompt: *const c_char,
424 buf: *mut c_char,
425 bufsiz: usize,
426 flags: c_int,
427 ) -> *mut c_char;
428 }
429}