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
//! Library for invoking [`pinentry`](https://www.gnupg.org/related_software/pinentry/index.en.html) to get password
//! input
//!
//! # Example
//!
//! ```
//! # extern crate pinentry_rs;
//! # extern crate secstr;
//! use pinentry_rs::pinentry;
//! use secstr::SecStr;
//!
//! # use pinentry_rs::Result;
//! # fn read_pw() -> Result<SecStr> {
//! // Read a password into a `SecStr`
//! let pw = pinentry().pin("Please enter password:".to_string())?;
//! # Ok(pw)
//! # }
//!
//! ```

#![deny(warnings)]
#![warn(unused_must_use)]
extern crate secstr;

/// Assuan protocol used by pinentry
///
/// _Note_ the module is deliberately left private currently
mod assuan;

use std::error;
use std::ffi::OsStr;
use std::fmt::{Display, Formatter};
use std::io;
use std::io::{BufRead, BufReader};
use std::process::{Child, Command, Stdio};
use std::result;

use secstr::SecStr;

use assuan::{AssuanCommand, AssuanResponse, Button};

pub type Result<T> = result::Result<T, Error>;

/// Errors that can occur while interacting with pinentry
#[derive(Debug)]
pub enum Error {
    /// IO error (command not found, broken pipe, etc.)
    IoError(io::Error),
    /// Protocol error (unable to parse protocol, broken pinentry output, etc.)
    ProtocolError(String),
}

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

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::IoError(ref cause) => write!(f, "Pinentry I/O error: {}", cause),
            Error::ProtocolError(ref cause) => write!(f, "A pinentry protocol error has occurred: {}", cause),
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::IoError(ref cause) => Some(cause),
            _ => None,
        }
    }
}

/// Create a builder for invoking `pinentry`
pub fn pinentry() -> PinentryBuilder {
    PinentryBuilder::default()
}

/// Builder for pinentry execution
pub struct PinentryBuilder {
    description: Option<String>,
    error_text: Option<String>,
    exe: String,
    label_cancel: Option<String>,
    label_notok: Option<String>,
    label_ok: Option<String>,
    timeout: Option<u32>,
    window_title: Option<String>,
}

impl PinentryBuilder {
    /// Set the descriptive text of the prompt
    pub fn description(mut self, desc: String) -> Self {
        self.description = Some(desc);
        self
    }

    /// Set the text that gets the displayed in case of error
    pub fn error_text(mut self, error_text: String) -> Self {
        self.error_text = Some(error_text);
        self
    }

    /// Override the path to the `pinentry` executable (by default just `pinentry`, looked up using `PATH` environment
    /// variable)
    pub fn exe(mut self, exe: String) -> Self {
        self.exe = exe;
        self
    }

    /// Set the label of the 'Cancel' button
    pub fn label_cancel(mut self, label: String) -> Self {
        self.label_cancel = Some(label);
        self
    }

    /// Set the label of the 'Not OK' button
    pub fn label_notok(mut self, label: String) -> Self {
        self.label_notok = Some(label);
        self
    }

    /// Set the label of the 'OK' button
    pub fn label_ok(mut self, label: String) -> Self {
        self.label_ok = Some(label);
        self
    }

    /// Set timeout for prompt (in seconds)
    pub fn timeout(mut self, secs: u32) -> Self {
        self.timeout = Some(secs);
        self
    }

    /// Set the window title of the prompt
    pub fn window_title(mut self, title: String) -> Self {
        self.window_title = Some(title);
        self
    }

    /// Prompt for confirmation
    ///
    /// The text for the confirmation should be set using `.description()`
    pub fn confirm_yes_no(mut self) -> Result<bool> {
        let mut commands = self.build_commands();
        commands.push(AssuanCommand::Confirm);

        let pinentry = start_pinentry(&self.exe)?;

        let res = process_commands(pinentry, &commands)?;
        match res {
            AssuanResponse::OK => Ok(true),
            AssuanResponse::NOTOK(_) => Ok(false),
            x => panic!("BUG: unexpected response {:?}", x),
        }
    }

    /// Prompt for a PIN
    pub fn pin(mut self, prompt: String) -> Result<SecStr> {
        let mut commands = self.build_commands();
        commands.push(AssuanCommand::SetPrompt(prompt));
        commands.push(AssuanCommand::GetPin);

        let pinentry = start_pinentry(&self.exe)?;

        let res = process_commands(pinentry, &commands)?;
        match res {
            AssuanResponse::PIN(pin) => Ok(pin),
            AssuanResponse::NOTOK(error) => Err(Error::ProtocolError(error)),
            AssuanResponse::OK => panic!("BUG: got OK result but asked for PIN"),
        }
    }

    /// Show a message
    ///
    /// The text for the message should be set using `.description()`
    pub fn show_message(mut self) -> Result<()> {
        let mut commands = self.build_commands();
        commands.push(AssuanCommand::ShowMessage);

        let pinentry = start_pinentry(&self.exe)?;

        let res = process_commands(pinentry, &commands)?;
        match res {
            AssuanResponse::OK => Ok(()),
            x => panic!("BUG: unexpected response {:?}", x),
        }
    }

    fn build_commands(&mut self) -> Vec<AssuanCommand> {
        let mut cmds = Vec::new();

        if let Some(desc) = self.description.take() {
            cmds.push(AssuanCommand::SetDescriptiveText(desc));
        }
        if let Some(text) = self.error_text.take() {
            cmds.push(AssuanCommand::SetErrorText(text));
        }
        if let Some(cancel_label) = self.label_cancel.take() {
            cmds.push(AssuanCommand::SetButtonLabel(Button::CANCEL, cancel_label));
        }
        if let Some(notok_label) = self.label_notok.take() {
            cmds.push(AssuanCommand::SetButtonLabel(Button::NOTOK, notok_label));
        }
        if let Some(ok_label) = self.label_ok.take() {
            cmds.push(AssuanCommand::SetButtonLabel(Button::OK, ok_label));
        }
        if let Some(timeout) = self.timeout {
            cmds.push(AssuanCommand::SetTimeout(timeout));
        }
        if let Some(title) = self.window_title.take() {
            cmds.push(AssuanCommand::SetWindowTitle(title));
        }

        cmds
    }
}

impl Default for PinentryBuilder {
    fn default() -> Self {
        PinentryBuilder {
            description: None,
            error_text: None,
            exe: "pinentry".to_string(),
            label_cancel: None,
            label_notok: None,
            label_ok: None,
            timeout: None,
            window_title: None,
        }
    }
}

fn start_pinentry<S: AsRef<OsStr>>(exe: S) -> Result<Child> {
    let mut pinentry = Command::new(exe)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("failed to execute pinentry");

    {
        // Check whether next line starts with OK
        let stdout = pinentry.stdout.as_mut().expect("failed to get stdout");
        let mut reader = BufReader::new(stdout);

        let mut line = String::with_capacity(32);
        let _ = reader.read_line(&mut line)?;
        if !line.starts_with("OK") {
            return Err(Error::ProtocolError(line));
        }
    }

    Ok(pinentry)
}

fn process_commands(mut pinentry: Child, cmds: &[AssuanCommand]) -> Result<AssuanResponse> {
    let res = {
        let mut stdout = BufReader::new(pinentry.stdout.as_mut().expect("failed to get stdout"));
        let stdin = pinentry.stdin.as_mut().expect("failed to get stdin");

        assuan::process_commands(cmds.iter(), stdin, &mut stdout)?
    };
    pinentry.kill()?;
    Ok(res)
}