summaryrefslogtreecommitdiff
path: root/src/pinentry.rs
blob: f538a477136d497dc47624f757aae4d63fb5a4c0 (plain)
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
// pinentry.rs

// *************************************************************************
// * Copyright (C) 2017-2020 Daniel Mueller (deso@posteo.net)              *
// *                                                                       *
// * This program is free software: you can redistribute it and/or modify  *
// * it under the terms of the GNU General Public License as published by  *
// * the Free Software Foundation, either version 3 of the License, or     *
// * (at your option) any later version.                                   *
// *                                                                       *
// * This program is distributed in the hope that it will be useful,       *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
// * GNU General Public License for more details.                          *
// *                                                                       *
// * You should have received a copy of the GNU General Public License     *
// * along with this program.  If not, see <http://www.gnu.org/licenses/>. *
// *************************************************************************

use std::borrow;
use std::fmt;
use std::process;
use std::str;

use anyhow::Context as _;

use crate::args;
use crate::ExecCtx;

type CowStr = borrow::Cow<'static, str>;

/// A trait representing a secret to be entered by the user.
pub trait SecretEntry: fmt::Debug {
  /// The cache ID to use for this secret.
  fn cache_id(&self) -> Option<CowStr>;
  /// The prompt to display when asking for the secret.
  fn prompt(&self) -> CowStr;
  /// The description to display when asking for the secret.
  fn description(&self, mode: Mode) -> CowStr;
  /// The minimum number of characters the secret needs to have.
  fn min_len(&self) -> u8;
}

#[derive(Debug)]
pub struct PinEntry {
  pin_type: args::PinType,
  model: nitrokey::Model,
  serial: nitrokey::SerialNumber,
}

impl PinEntry {
  pub fn from<'mgr, D>(pin_type: args::PinType, device: &D) -> anyhow::Result<Self>
  where
    D: nitrokey::Device<'mgr>,
  {
    let model = device.get_model();
    let serial = device
      .get_serial_number()
      .context("Failed to retrieve serial number")?;

    Ok(Self {
      pin_type,
      model,
      serial,
    })
  }

  pub fn pin_type(&self) -> args::PinType {
    self.pin_type
  }
}

impl SecretEntry for PinEntry {
  fn cache_id(&self) -> Option<CowStr> {
    let model = self.model.to_string().to_lowercase();
    let suffix = format!("{}:{}", model, self.serial);
    let cache_id = match self.pin_type {
      args::PinType::Admin => format!("nitrocli:admin:{}", suffix),
      args::PinType::User => format!("nitrocli:user:{}", suffix),
    };
    Some(cache_id.into())
  }

  fn prompt(&self) -> CowStr {
    match self.pin_type {
      args::PinType::Admin => "Admin PIN",
      args::PinType::User => "User PIN",
    }
    .into()
  }

  fn description(&self, mode: Mode) -> CowStr {
    format!(
      "{} for\rNitrokey {} {}",
      match self.pin_type {
        args::PinType::Admin => match mode {
          Mode::Choose => "Please enter a new admin PIN",
          Mode::Confirm => "Please confirm the new admin PIN",
          Mode::Query => "Please enter the admin PIN",
        },
        args::PinType::User => match mode {
          Mode::Choose => "Please enter a new user PIN",
          Mode::Confirm => "Please confirm the new user PIN",
          Mode::Query => "Please enter the user PIN",
        },
      },
      self.model,
      self.serial,
    )
    .into()
  }

  fn min_len(&self) -> u8 {
    match self.pin_type {
      args::PinType::Admin => 8,
      args::PinType::User => 6,
    }
  }
}

#[derive(Debug)]
pub struct PwdEntry {
  model: nitrokey::Model,
  serial: nitrokey::SerialNumber,
}

impl PwdEntry {
  pub fn from<'mgr, D>(device: &D) -> anyhow::Result<Self>
  where
    D: nitrokey::Device<'mgr>,
  {
    let model = device.get_model();
    let serial = device
      .get_serial_number()
      .context("Failed to retrieve serial number")?;

    Ok(Self { model, serial })
  }
}

impl SecretEntry for PwdEntry {
  fn cache_id(&self) -> Option<CowStr> {
    None
  }

  fn prompt(&self) -> CowStr {
    "Password".into()
  }

  fn description(&self, mode: Mode) -> CowStr {
    format!(
      "{} for\rNitrokey {} {}",
      match mode {
        Mode::Choose => "Please enter a new hidden volume password",
        Mode::Confirm => "Please confirm the new hidden volume password",
        Mode::Query => "Please enter a hidden volume password",
      },
      self.model,
      self.serial,
    )
    .into()
  }

  fn min_len(&self) -> u8 {
    // More or less arbitrary minimum length based on the fact that the
    // manual mentions six letter passwords in examples. Users
    // *probably* should go longer than that, but we don't want to be
    // too opinionated.
    6
  }
}

/// Secret entry mode for pinentry.
///
/// This enum describes the context of the pinentry query, for example
/// prompting for the current secret or requesting a new one. The mode
/// may affect the pinentry description and whether a quality bar is
/// shown.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Mode {
  /// Let the user choose a new secret.
  Choose,
  /// Let the user confirm the previously chosen secret.
  Confirm,
  /// Query an existing secret.
  Query,
}

impl Mode {
  fn show_quality_bar(self) -> bool {
    self == Mode::Choose
  }
}

fn parse_pinentry_pin<R>(response: R) -> anyhow::Result<String>
where
  R: AsRef<str>,
{
  let string = response.as_ref();
  let lines: Vec<&str> = string.lines().collect();

  // We expect the response to be of the form:
  // > D passphrase
  // > OK
  // or potentially:
  // > ERR 83886179 Operation cancelled <Pinentry>
  if lines.len() == 2 && lines[1] == "OK" && lines[0].starts_with("D ") {
    // We got the only valid answer we accept.
    let (_, pass) = lines[0].split_at(2);
    return Ok(pass.to_string());
  }

  // Check if we are dealing with a special "ERR " line and report that
  // specially.
  if !lines.is_empty() && lines[0].starts_with("ERR ") {
    let (_, error) = lines[0].split_at(4);
    anyhow::bail!("{}", error);
  }
  anyhow::bail!("Unexpected response: {}", string)
}

/// Inquire a secret from the user.
///
/// This function inquires a secret from the user or returns a cached
/// entry, if available (and if caching is not disabled for the given
/// execution context). If an error message is set, it is displayed in
/// the entry dialog. The mode describes the context of the pinentry
/// dialog. It is used to choose an appropriate description and to
/// decide whether a quality bar is shown in the dialog.
pub fn inquire<E>(
  ctx: &mut ExecCtx<'_>,
  entry: &E,
  mode: Mode,
  error_msg: Option<&str>,
) -> anyhow::Result<String>
where
  E: SecretEntry,
{
  let cache_id = entry
    .cache_id()
    .and_then(|id| if ctx.config.no_cache { None } else { Some(id) })
    // "X" is a sentinel value indicating that no caching is desired.
    .unwrap_or_else(|| "X".into())
    .into();

  let error_msg = error_msg
    .map(|msg| msg.replace(" ", "+"))
    .unwrap_or_else(|| String::from("+"));
  let prompt = entry.prompt().replace(" ", "+");
  let description = entry.description(mode).replace(" ", "+");

  let args = vec![cache_id, error_msg, prompt, description].join(" ");
  let mut command = "GET_PASSPHRASE --data ".to_string();
  if mode.show_quality_bar() {
    command += "--qualitybar ";
  }
  command += &args;
  // An error reported for the GET_PASSPHRASE command does not actually
  // cause gpg-connect-agent to exit with a non-zero error code, we have
  // to evaluate the output to determine success/failure.
  let output = process::Command::new("gpg-connect-agent")
    .arg(command)
    .arg("/bye")
    .output()
    .context("Failed to invoke gpg-connect-agent")?;

  let response =
    str::from_utf8(&output.stdout).context("Failed to parse gpg-connect-agent output as UTF-8")?;
  parse_pinentry_pin(response).context("Failed to parse pinentry secret")
}

fn check<E>(entry: &E, secret: &str) -> anyhow::Result<()>
where
  E: SecretEntry,
{
  if secret.len() < usize::from(entry.min_len()) {
    anyhow::bail!(
      "The secret must be at least {} characters long",
      entry.min_len()
    )
  } else {
    Ok(())
  }
}

pub fn choose<E>(ctx: &mut ExecCtx<'_>, entry: &E) -> anyhow::Result<String>
where
  E: SecretEntry,
{
  clear(entry)?;
  let chosen = inquire(ctx, entry, Mode::Choose, None)?;
  clear(entry)?;
  check(entry, &chosen)?;

  let confirmed = inquire(ctx, entry, Mode::Confirm, None)?;
  clear(entry)?;

  if chosen != confirmed {
    anyhow::bail!("Entered secrets do not match")
  } else {
    Ok(chosen)
  }
}

fn parse_pinentry_response<R>(response: R) -> anyhow::Result<()>
where
  R: AsRef<str>,
{
  let string = response.as_ref();
  let lines = string.lines().collect::<Vec<_>>();

  if lines.len() == 1 && lines[0] == "OK" {
    // We got the only valid answer we accept.
    return Ok(());
  }
  anyhow::bail!("Unexpected response: {}", string)
}

/// Clear the cached secret represented by the given entry.
pub fn clear<E>(entry: &E) -> anyhow::Result<()>
where
  E: SecretEntry,
{
  if let Some(cache_id) = entry.cache_id() {
    let command = format!("CLEAR_PASSPHRASE {}", cache_id);
    let output = process::Command::new("gpg-connect-agent")
      .arg(command)
      .arg("/bye")
      .output()
      .context("Failed to invoke gpg-connect-agent")?;

    let response = str::from_utf8(&output.stdout)
      .context("Failed to parse gpg-connect-agent output as UTF-8")?;

    parse_pinentry_response(response).context("Failed to parse pinentry response")
  } else {
    Ok(())
  }
}

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

  #[test]
  fn parse_pinentry_pin_good() {
    let response = "D passphrase\nOK\n";
    let expected = "passphrase";

    assert_eq!(parse_pinentry_pin(response).unwrap(), expected)
  }

  #[test]
  fn parse_pinentry_pin_error() {
    let error = "83886179 Operation cancelled";
    let response = "ERR ".to_string() + error + "\n";
    let expected = error;

    let error = parse_pinentry_pin(response).unwrap_err();
    assert_eq!(error.to_string(), expected)
  }

  #[test]
  fn parse_pinentry_pin_unexpected() {
    let response = "foobar\n";
    let expected = format!("Unexpected response: {}", response);
    let error = parse_pinentry_pin(response).unwrap_err();
    assert_eq!(error.to_string(), expected)
  }

  #[test]
  fn parse_pinentry_response_ok() {
    assert!(parse_pinentry_response("OK\n").is_ok())
  }

  #[test]
  fn parse_pinentry_response_ok_no_newline() {
    assert!(parse_pinentry_response("OK").is_ok())
  }

  #[test]
  fn parse_pinentry_response_unexpected() {
    let response = "ERR 42";
    let expected = format!("Unexpected response: {}", response);
    let error = parse_pinentry_response(response).unwrap_err();
    assert_eq!(error.to_string(), expected)
  }
}