readpassphrase-3 1.0.2

Simple wrapper around readpassphrase(3)
Documentation
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! Lightweight, easy-to-use wrapper around the C [`readpassphrase(3)`][0] function.
//!
//! From the man page:
//! > The `readpassphrase()` function displays a prompt to, and reads in a passphrase from,
//! > `/dev/tty`. If this file is inaccessible and the [`RPP_REQUIRE_TTY`](Flags::REQUIRE_TTY) flag
//! > is not set, `readpassphrase()` displays the prompt on the standard error output and reads
//! > from the standard input.
//!
//! # Usage
//! For the simplest of cases, where you would just like to read a password from the console into a
//! [`String`] to use elsewhere, you can use [`getpass`]:
//! ```no_run
//! use readpassphrase_3::getpass;
//! let _ = getpass(c"Enter your password: ").expect("failed reading password");
//! ```
//!
//! If you need to pass [`Flags`] or to control the buffer size, then you can use
//! [`readpassphrase`] or [`readpassphrase_into`] depending on your ownership requirements:
//! ```no_run
//! let mut buf = vec![0u8; 256];
//! use readpassphrase_3::{Flags, readpassphrase};
//! let pass: &str = readpassphrase(c"Password: ", &mut buf, Flags::default()).unwrap();
//!
//! use readpassphrase_3::readpassphrase_into;
//! let pass: String = readpassphrase_into(c"Pass: ", buf, Flags::FORCELOWER).unwrap();
//! # _ = pass;
//! ```
//!
//! # Security
//! The [`readpassphrase(3)` man page][0] says:
//! > The calling process should zero the passphrase as soon as possible to avoid leaving the
//! > cleartext passphrase visible in the process's address space.
//!
//! It is your job to ensure that this is done with the data you own, i.e.
//! any [`Vec`] passed to [`readpassphrase`] or any [`String`] received from [`getpass`] or
//! [`readpassphrase_into`].
//!
//! This crate ships with a minimal [`Zeroize`] trait that may be used for this purpose:
//! ```no_run
//! # use readpassphrase_3::{Flags, getpass, readpassphrase, readpassphrase_into};
//! use readpassphrase_3::Zeroize;
//! let mut pass = getpass(c"password: ").unwrap();
//! // do_something_with(&pass);
//! pass.zeroize();
//!
//! let mut buf = vec![0u8; 256];
//! let res = readpassphrase(c"password: ", &mut buf, Flags::empty());
//! // match_something_on(res);
//! buf.zeroize();
//!
//! let mut pass = readpassphrase_into(c"password: ", buf, Flags::empty()).unwrap();
//! // do_something_with(&pass);
//! pass.zeroize();
//! ```
//!
//! ## Zeroizing memory
//! This crate works well with the [`zeroize`] crate. For example, [`zeroize::Zeroizing`] may be
//! used to zero buffer contents regardless of a function’s control flow:
//! ```no_run
//! # use readpassphrase_3::{Error, Flags, PASSWORD_LEN, getpass, readpassphrase};
//! use zeroize::Zeroizing;
//! # fn main() -> Result<(), Error> {
//! let mut buf = Zeroizing::new(vec![0u8; PASSWORD_LEN]);
//! let pass = readpassphrase(c"pass: ", &mut buf, Flags::REQUIRE_TTY)?;
//! // do_something_that_can_fail_with(pass)?;
//!
//! // Or alternatively:
//! let pass = Zeroizing::new(getpass(c"pass: ")?);
//! // do_something_that_can_fail_with(&pass)?;
//! # Ok(())
//! # }
//! ```
//!
//! If this crate’s `zeroize` feature is enabled, then its [`Zeroize`] will be replaced by a
//! re-export of the upstream [`zeroize::Zeroize`].
//!
//! # “Mismatched types” errors
//! The prompt strings in this API are <code>&[CStr]</code>, not <code>&[str]</code>.
//! This is because the underlying C function assumes that the prompt is a NUL-terminated string;
//! were we to take `&str` instead of `&CStr`, we would need to make a copy of the prompt on every
//! call.
//!
//! Most of the time, your prompts will be string literals; you can ask Rust to give you a `&CStr`
//! literal by simply prepending `c` to the string:
//! ```no_run
//! # use readpassphrase_3::{Error, getpass};
//! # fn main() -> Result<(), Error> {
//! let _ = getpass(c"pass: ")?;
//! //              ^
//! //              |
//! //              like this
//! # Ok(())
//! # }
//! ```
//!
//! If you need a dynamic prompt, look at [`CString`](std::ffi::CString).
//!
//! # Windows Limitations
//! The Windows implementation of `readpassphrase(3)` that we are using does not yet support UTF-8
//! in prompts; they must be ASCII. It also does not yet support flags, and always behaves as
//! though called with [`Flags::empty()`].
//!
//! [0]: https://man.openbsd.org/readpassphrase
//! [str]: prim@str "str"

use std::{cmp, error, ffi::CStr, fmt, io, mem, str};

use bitflags::bitflags;
#[cfg(any(docsrs, not(feature = "zeroize")))]
pub use our_zeroize::Zeroize;
#[cfg(all(not(docsrs), feature = "zeroize"))]
pub use zeroize::Zeroize;

/// Size of buffer used in [`getpass`].
///
/// Because `readpassphrase(3)` NUL-terminates its string, the actual maximum password length for
/// [`getpass`] is 255.
pub const PASSWORD_LEN: usize = 256;

/// Maximum capacity to use with [`readpassphrase_into`].
///
/// Vectors with allocations larger than this will only have their capacity used up to this limit.
/// (The initialized portion of the input vector is always used regardless of size.)
pub const MAX_CAPACITY: usize = 1 << 12;

bitflags! {
    /// Flags for controlling readpassphrase.
    ///
    /// The default flag `ECHO_OFF` is not represented here because `bitflags` [recommends against
    /// zero-bit flags][0]; it may be specified as either [`Flags::empty()`] or
    /// [`Flags::default()`].
    ///
    /// Note that the Windows `readpassphrase(3)` implementation always acts like it has been
    /// passed `ECHO_OFF`, i.e., the flags are ignored.
    ///
    /// [0]: https://docs.rs/bitflags/latest/bitflags/#zero-bit-flags
    #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
    pub struct Flags: i32 {
        /// Leave echo on.
        const ECHO_ON     = 0x01;
        /// Fail if there is no tty.
        const REQUIRE_TTY = 0x02;
        /// Force input to lower case.
        const FORCELOWER  = 0x04;
        /// Force input to upper case.
        const FORCEUPPER  = 0x08;
        /// Strip the high bit from input.
        const SEVENBIT    = 0x10;
        /// Read from stdin, not `/dev/tty`.
        const STDIN       = 0x20;
    }
}

/// Errors that can occur in readpassphrase.
#[derive(Debug)]
pub enum Error {
    /// `readpassphrase(3)` itself encountered an error.
    Io(io::Error),
    /// The entered password was not UTF-8.
    Utf8(str::Utf8Error),
}

/// Reads a passphrase using `readpassphrase(3)`.
///
/// This function returns a <code>&[str]</code> backed by `buf`, representing a password of up to
/// `buf.len() - 1` bytes. Any additional characters and the terminating newline are discarded.
///
/// # Errors
/// Returns [`Err`] if `readpassphrase(3)` itself failed or if the entered password is not UTF-8.
/// The former will be represented by [`Error::Io`] and the latter by [`Error::Utf8`].
///
/// # Security
/// The passed buffer might contain sensitive data, even if this function returns an error.
/// Therefore it should be zeroed as soon as possible. This can be achieved, for example, with
/// [`zeroize::Zeroizing`]:
/// ```no_run
/// # use readpassphrase_3::{PASSWORD_LEN, Error, Flags, readpassphrase};
/// use zeroize::Zeroizing;
/// # fn main() -> Result<(), Error> {
/// let mut buf = Zeroizing::new(vec![0u8; PASSWORD_LEN]);
/// let pass = readpassphrase(c"Pass: ", &mut buf, Flags::default())?;
/// # Ok(())
/// # }
/// ```
/// [str]: prim@str "str"
pub fn readpassphrase<'a>(
    prompt: &CStr,
    buf: &'a mut [u8],
    flags: Flags,
) -> Result<&'a str, Error> {
    #[cfg(debug_assertions)]
    {
        // Fill `buf` with nonzero bytes to check that `ffi::readpassphrase` wrote a NUL.
        buf.fill(1);
    }
    let prompt = prompt.as_ptr();
    let buf_ptr = buf.as_mut_ptr().cast();
    let bufsiz = buf.len();
    let flags = flags.bits();
    // SAFETY: `prompt` is a NUL-terminated byte sequence, and `buf_ptr` is an allocation of at
    // least `bufsiz` bytes, by construction from `&CStr` and `&mut [u8]` respectively.
    let res = unsafe { ffi::readpassphrase(prompt, buf_ptr, bufsiz, flags) };
    if res.is_null() {
        return Err(io::Error::last_os_error().into());
    }
    Ok(CStr::from_bytes_until_nul(buf).unwrap().to_str()?)
}

/// Reads a passphrase using `readpassphrase(3)`, returning a [`String`].
///
/// Internally, this function uses a buffer of [`PASSWORD_LEN`] bytes, allowing for passwords up to
/// `PASSWORD_LEN - 1` characters (accounting for the C NUL terminator.) Any additional characters
/// and the terminating newline are discarded.
///
/// # Errors
/// Returns [`Err`] if `readpassphrase(3)` itself failed or if the entered password is not UTF-8.
/// The former will be represented by [`Error::Io`] and the latter by [`Error::Utf8`].
///
/// # Security
/// The returned `String` is owned by the caller, and therefore it is the caller’s responsibility
/// to clear it when you are done with it:
/// ```no_run
/// # use readpassphrase_3::{Error, Zeroize, getpass};
/// # fn main() -> Result<(), Error> {
/// let mut pass = getpass(c"Pass: ")?;
/// _ = pass;
/// pass.zeroize();
/// # Ok(())
/// # }
/// ```
pub fn getpass(prompt: &CStr) -> Result<String, Error> {
    let buf = Vec::with_capacity(PASSWORD_LEN);
    Ok(readpassphrase_into(prompt, buf, Flags::empty())?)
}

/// An [`Error`] from [`readpassphrase_into`] containing the passed buffer.
///
/// The buffer is accessible via [`IntoError::into_bytes`][0], and the `Error` via
/// [`IntoError::error`].
///
/// If [`into_bytes`][0] is not called, the buffer is automatically zeroed on drop.
///
/// [0]: IntoError::into_bytes
#[derive(Debug)]
pub struct IntoError(Error, Option<Vec<u8>>);

/// Reads a passphrase using `readpassphrase(3)`, returning `buf` as a [`String`].
///
/// The returned [`String`] reuses `buf`’s memory; no copies are made, and `buf` is never
/// reallocated.
///
/// `buf`’s full allocation will be  used, whether initialized or not, up to [4KiB][MAX_CAPACITY];
/// i.e., the following two statements are equivalent:
/// ```no_run
/// # use readpassphrase_3::{Flags, readpassphrase_into};
/// # let flags = Flags::empty();
/// let _ = readpassphrase_into(c"> ", vec![0u8; 128], flags);
/// let _ = readpassphrase_into(c"> ", Vec::with_capacity(128), flags);
/// ```
///
/// If for some reason you must use this function to read more than 4KiB of text, then you should
/// initialize the buffer to the length you will need.
///
/// # Errors
/// Returns [`Err`] if `readpassphrase(3)` itself failed or if the entered password is not UTF-8.
/// The former will be represented by [`Error::Io`] and the latter by [`Error::Utf8`]. The vector
/// you moved in is also included, and in the case of [`Error::Utf8`], contains the non-UTF8 byte
/// sequence produced by `readpassphrase(3)`.
///
/// See the docs for [`IntoError`] for more details on what you can do with this error.
///
/// # Security
/// The returned `String` is owned by the caller, and it is the caller’s responsibility to clear
/// it. This can be done via [`Zeroize`], e.g.:
/// ```no_run
/// # use readpassphrase_3::{
/// #     PASSWORD_LEN,
/// #     Error,
/// #     Flags,
/// #     readpassphrase_into,
/// # };
/// # use readpassphrase_3::Zeroize;
/// # fn main() -> Result<(), Error> {
/// let buf = vec![0u8; PASSWORD_LEN];
/// let mut pass = readpassphrase_into(c"Pass: ", buf, Flags::default())?;
/// _ = pass;
/// pass.zeroize();
/// # Ok(())
/// # }
/// ```
pub fn readpassphrase_into(
    prompt: &CStr,
    mut buf: Vec<u8>,
    flags: Flags,
) -> Result<String, IntoError> {
    let bufsiz = cmp::max(buf.len(), cmp::min(buf.capacity(), MAX_CAPACITY));
    if cfg!(debug_assertions) {
        // Fill `buf` with nonzero bytes to check that `ffi::readpassphrase` wrote a NUL.
        buf.fill(1);
        buf.resize(bufsiz, 1);
    } else {
        buf.resize(bufsiz, 0);
    }
    let prompt = prompt.as_ptr();
    let buf_ptr = buf.as_mut_ptr().cast();
    let flags = flags.bits();
    // SAFETY: By construction as with `readpassphrase` above.
    let res = unsafe { ffi::readpassphrase(prompt, buf_ptr, bufsiz, flags) };
    if res.is_null() {
        buf.clear();
        return Err(IntoError(io::Error::last_os_error().into(), Some(buf)));
    }
    let len = buf.iter().position(|&b| b == 0).unwrap();
    buf.truncate(len);
    String::from_utf8(buf).map_err(|e| {
        let err = e.utf8_error();
        let buf = e.into_bytes();
        IntoError(Error::Utf8(err), Some(buf))
    })
}

impl IntoError {
    /// Return the [`Error`] corresponding to this.
    pub fn error(&self) -> &Error {
        &self.0
    }

    /// Returns the buffer that was passed to [`readpassphrase_into`].
    ///
    /// # Security
    /// The returned buffer may contain sensitive data in its spare capacity, even if the
    /// buffer’s length is zero. It is the caller’s responsibility to zero it as soon as possible
    /// if needed, e.g. using [`Zeroize`]:
    /// ```no_run
    /// # use std::io::*;
    /// # use readpassphrase_3::{Flags, Zeroize, readpassphrase_into};
    /// # let err = readpassphrase_into(c"", vec![], Flags::empty()).unwrap_err();
    /// let mut buf = err.into_bytes();
    /// // ...
    /// buf.zeroize();
    /// ```
    pub fn into_bytes(mut self) -> Vec<u8> {
        self.1.take().unwrap()
    }
}

impl error::Error for IntoError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        Some(&self.0)
    }
}

impl fmt::Display for IntoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl Drop for IntoError {
    fn drop(&mut self) {
        if let Some(mut buf) = self.1.take() {
            buf.zeroize();
        }
    }
}

impl From<IntoError> for Error {
    fn from(mut value: IntoError) -> Self {
        mem::replace(&mut value.0, Error::Io(io::ErrorKind::Other.into()))
    }
}

impl From<io::Error> for Error {
    fn from(value: io::Error) -> Self {
        Error::Io(value)
    }
}

impl From<str::Utf8Error> for Error {
    fn from(value: str::Utf8Error) -> Self {
        Error::Utf8(value)
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        Some(match self {
            Error::Io(e) => e,
            Error::Utf8(e) => e,
        })
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Io(e) => e.fmt(f),
            Error::Utf8(e) => e.fmt(f),
        }
    }
}

#[cfg(any(docsrs, not(feature = "zeroize")))]
mod our_zeroize {
    use std::{arch::asm, mem::MaybeUninit};

    /// A minimal in-crate implementation of a subset of [`zeroize::Zeroize`].
    ///
    /// This provides compile-fenced memory zeroing for [`String`]s and [`Vec`]s without needing to
    /// depend on the `zeroize` crate.
    ///
    /// If the optional `zeroize` feature is enabled, then the trait is replaced with a re-export of
    /// `zeroize::Zeroize` itself.
    pub trait Zeroize {
        fn zeroize(&mut self);
    }

    impl Zeroize for Vec<u8> {
        fn zeroize(&mut self) {
            self.clear();
            let buf = self.spare_capacity_mut();
            buf.fill(MaybeUninit::zeroed());
            compile_fence(buf);
        }
    }

    impl Zeroize for String {
        fn zeroize(&mut self) {
            // SAFETY: we clear the string.
            unsafe { self.as_mut_vec() }.zeroize();
        }
    }

    impl Zeroize for [u8] {
        fn zeroize(&mut self) {
            self.fill(0);
            compile_fence(self);
        }
    }

    fn compile_fence<T>(buf: &[T]) {
        unsafe {
            asm!(
                "/* {ptr} */",
                ptr = in(reg) buf.as_ptr(),
                options(nostack, preserves_flags, readonly)
            );
        }
    }
}

#[cfg(use_tcm)]
use tcm_readpassphrase_vendored as ffi;
#[cfg(not(use_tcm))]
mod ffi {
    use std::ffi::{c_char, c_int};

    extern "C" {
        pub(crate) fn readpassphrase(
            prompt: *const c_char,
            buf: *mut c_char,
            bufsiz: usize,
            flags: c_int,
        ) -> *mut c_char;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty() {
        let err = readpassphrase_into(c"pass", Vec::new(), Flags::empty()).unwrap_err();
        let Error::Io(err) = err.into() else {
            panic!();
        };
        #[cfg(not(windows))]
        assert_eq!(io::ErrorKind::InvalidInput, err.kind());
        #[cfg(windows)]
        {
            _ = err
        };

        let mut buf = Vec::new();
        let err = readpassphrase(c"pass", &mut buf, Flags::empty()).unwrap_err();
        let Error::Io(err) = err else {
            panic!();
        };
        #[cfg(not(windows))]
        assert_eq!(io::ErrorKind::InvalidInput, err.kind());
        #[cfg(windows)]
        {
            _ = err
        };
    }

    #[test]
    fn test_zeroize() {
        let mut buf = "test".to_string();
        buf.zeroize();
        assert_eq!(0, buf.len());
        unsafe { buf.as_mut_vec().set_len(4) };
        assert_eq!("\0\0\0\0", &buf);
        let mut buf = vec![1u8; 15];
        unsafe { buf.set_len(0) };
        let x = buf.spare_capacity_mut()[0];
        assert_eq!(unsafe { x.assume_init() }, 1);
        buf.zeroize();
        unsafe { buf.set_len(15) };
        assert_eq!(vec![0u8; 15], buf);
        let mut buf = vec![1u8; 2];
        unsafe { buf.set_len(1) };
        let slice = &mut *buf;
        slice.zeroize();
        unsafe { buf.set_len(2) };
        assert_eq!(vec![0u8, 1], buf);
    }
}