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
// Copyright (C) 2021-2022 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT

//! Client library for Nitrokey 3 devices.
//!
//! # Quickstart
//!
//! ```no_run
//! # fn try_main() -> Result<(), nitrokey3::Error> {
//! let hidapi = hidapi::HidApi::new()?;
//! let devices = nitrokey3::list(&hidapi)?;
//! println!("Found {} Nitrokey 3 devices", devices.len());
//! for device in devices {
//!     let device = device.connect()?;
//!     println!("- Nitrokey 3 with firmware version {}", device.firmware_version()?);
//! }
//! #     Ok(())
//! # }
//! ```

#![warn(
    missing_copy_implementations,
    missing_debug_implementations,
    missing_docs,
    non_ascii_idents,
    trivial_casts,
    unused,
    unused_qualifications
)]
#![deny(unsafe_code)]

use std::{
    convert::{TryFrom, TryInto},
    error, fmt, ops,
};

const VID_NITROKEY_3: u16 = 0x20a0;
const PID_NITROKEY_3: u16 = 0x42b2;

mod commands {
    use ctaphid_types::VendorCommand;

    pub const UPDATE: VendorCommand = VendorCommand::H51;
    pub const REBOOT: VendorCommand = VendorCommand::H53;
    pub const RNG: VendorCommand = VendorCommand::H60;
    pub const VERSION: VendorCommand = VendorCommand::H61;
    pub const UUID: VendorCommand = VendorCommand::H62;
}

/// A collection of available Nitrokey 3 devices.
#[derive(Clone, Debug)]
pub struct Devices<'a> {
    device_infos: Vec<DeviceInfo<'a>>,
}

impl<'a> Devices<'a> {
    fn new(hidapi: &'a hidapi::HidApi) -> Self {
        let device_infos = hidapi
            .device_list()
            .filter(|device| device.vendor_id() == VID_NITROKEY_3)
            .filter(|device| device.product_id() == PID_NITROKEY_3)
            .map(|device_info| DeviceInfo {
                hidapi,
                device_info,
            })
            .collect();
        Devices { device_infos }
    }
}

impl<'a> IntoIterator for Devices<'a> {
    type Item = DeviceInfo<'a>;
    type IntoIter = std::vec::IntoIter<DeviceInfo<'a>>;

    fn into_iter(self) -> Self::IntoIter {
        self.device_infos.into_iter()
    }
}

impl<'a> ops::Deref for Devices<'a> {
    type Target = [DeviceInfo<'a>];

    fn deref(&self) -> &Self::Target {
        &self.device_infos
    }
}

/// A firmware version number.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Version {
    /// The major part of the version number.
    pub major: u16,
    /// The minor part of the version number.
    pub minor: u16,
    /// The patch part of the version number.
    pub patch: u8,
}

impl From<[u8; 4]> for Version {
    fn from(version: [u8; 4]) -> Self {
        u32::from_be_bytes(version).into()
    }
}

impl From<u32> for Version {
    fn from(version: u32) -> Self {
        let major = (version >> 22) as u16;
        let minor = ((version >> 6) & 0b1111_1111_1111_1111) as u16;
        let patch = (version & 0b11_1111) as u8;
        Self {
            major,
            minor,
            patch,
        }
    }
}

impl TryFrom<Vec<u8>> for Version {
    type Error = CommandError;

    fn try_from(version: Vec<u8>) -> Result<Self, Self::Error> {
        <[u8; 4]>::try_from(version)
            .map(From::from)
            .map_err(|_| CommandError::InvalidResponseLength)
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "v{}.{}.{}", self.major, self.minor, self.patch)
    }
}

/// An available Nitrokey 3 device.
#[derive(Copy, Clone)]
pub struct DeviceInfo<'a> {
    hidapi: &'a hidapi::HidApi,
    device_info: &'a hidapi::DeviceInfo,
}

impl<'a> DeviceInfo<'a> {
    /// Connects to this Nitrokey 3 device.
    pub fn connect(&self) -> Result<Device<hidapi::HidDevice>, Error> {
        let device = self.device_info.open_device(self.hidapi)?;
        let device = ctaphid::Device::new(device, self.device_info.to_owned())?;
        Ok(Device::new(device))
    }
}

impl<'a> fmt::Debug for DeviceInfo<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DeviceInfo")
            .field("device_info", &self.device_info)
            .finish()
    }
}

/// A connected Nitrokey 3 device.
#[derive(Debug)]
pub struct Device<H: ctaphid::HidDevice> {
    device: ctaphid::Device<H>,
}

impl<H: ctaphid::HidDevice> Device<H> {
    /// Creates a new Nitrokey 3 instance from the given [`ctaphid::Device`][], assuming that it is
    /// a Nitrokey 3 device.
    ///
    /// Use [`list`][] to get a list of all available Nitrokey 3 devices and
    /// [`DeviceInfo::connect`][] to connect to one of them.
    pub fn new(device: ctaphid::Device<H>) -> Self {
        Self { device }
    }

    /// Queries the firmware version of the device.
    pub fn firmware_version(&self) -> Result<Version, Error> {
        self.device
            .vendor_command(commands::VERSION, &[])?
            .try_into()
            .map_err(From::from)
    }

    /// Queries the UUID of the device.
    ///
    /// This command requires the firmware version v1.0.1.
    pub fn uuid(&self) -> Result<Uuid, Error> {
        // TODO: what to do on firmware version <v1.0.1?
        self.device
            .vendor_command(commands::UUID, &[])?
            .try_into()
            .map_err(From::from)
    }

    /// Generates random data on the device.
    pub fn rng(&self) -> Result<Vec<u8>, Error> {
        self.device
            .vendor_command(commands::RNG, &[])
            .map_err(From::from)
    }

    /// Reboots the device into the given boot mode.
    pub fn reboot(&self, mode: BootMode) -> Result<(), Error> {
        let command = match mode {
            BootMode::Firmware => commands::REBOOT,
            BootMode::Bootrom => commands::UPDATE,
        };
        self.device
            .vendor_command(command, &[])
            .map(|_| ())
            .or_else(ignore_closed_connection)
    }

    /// Executes the wink command.
    ///
    /// For devices with firmware v1.0.1 or newer, this causes the LED to blink.  For older
    /// firmware versions, this does nothing.
    pub fn wink(&self) -> Result<(), Error> {
        self.device.wink().map_err(From::from)
    }
}

fn ignore_closed_connection(error: ctaphid::error::Error) -> Result<(), Error> {
    use ctaphid::error::{Error as CtaphidError, ResponseError};
    if let CtaphidError::ResponseError(ResponseError::PacketReceivingFailed(_)) = error {
        // TODO: limit ignored errors?
        Ok(())
    } else {
        Err(Error::from(error))
    }
}

/// The boot mode for a reboot command.
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum BootMode {
    /// Boot into the Nitrokey 3 firmware.
    Firmware,
    /// Boot into the bootrom that can be used to apply firmware updates.
    Bootrom,
}

/// The UUID for a Nitrokey 3 device.
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Uuid(u128);

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

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

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

impl From<[u8; 16]> for Uuid {
    fn from(uuid: [u8; 16]) -> Self {
        u128::from_be_bytes(uuid).into()
    }
}

impl From<u128> for Uuid {
    fn from(uuid: u128) -> Self {
        Self(uuid)
    }
}

impl From<Uuid> for u128 {
    fn from(uuid: Uuid) -> Self {
        uuid.0
    }
}

impl TryFrom<Vec<u8>> for Uuid {
    type Error = CommandError;

    fn try_from(uuid: Vec<u8>) -> Result<Self, Self::Error> {
        <[u8; 16]>::try_from(uuid)
            .map(From::from)
            .map_err(|_| CommandError::InvalidResponseLength)
    }
}

/// Lists all available Nitrokey 3 devices.
pub fn list(hidapi: &hidapi::HidApi) -> Result<Devices<'_>, Error> {
    Ok(Devices::new(hidapi))
}

/// Error type for Nitrokey 3 operations.
#[derive(Debug)]
pub enum Error {
    /// An error that occured during the CTAPHID communication.
    CtaphidError(ctaphid::error::Error),
    /// A command-specific error.
    CommandError(CommandError),
    /// An error that occured during the hidapi device connection.
    HidapiError(hidapi::HidError),
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::CtaphidError(error) => Some(error),
            Self::CommandError(error) => Some(error),
            Self::HidapiError(error) => Some(error),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CtaphidError(_) => "CTAPHID communication failed",
            Self::CommandError(_) => "command execution failed",
            Self::HidapiError(_) => "hidapi connection failed",
        }
        .fmt(f)
    }
}

impl From<CommandError> for Error {
    fn from(error: CommandError) -> Self {
        Self::CommandError(error)
    }
}

impl From<ctaphid::error::Error> for Error {
    fn from(error: ctaphid::error::Error) -> Self {
        Self::CtaphidError(error)
    }
}

impl From<hidapi::HidError> for Error {
    fn from(error: hidapi::HidError) -> Self {
        Self::HidapiError(error)
    }
}

/// A command-specific error.
#[derive(Clone, Copy, Debug)]
pub enum CommandError {
    /// The response data does not have the expected length.
    InvalidResponseLength,
}

impl error::Error for CommandError {}

impl fmt::Display for CommandError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidResponseLength => "the response data does not have the expected length",
        }
        .fmt(f)
    }
}