nitrokey/device/
storage.rs

1// Copyright (C) 2019-2020 Robin Krahl <robin.krahl@ireas.org>
2// SPDX-License-Identifier: MIT
3
4use std::convert::TryFrom as _;
5use std::fmt;
6use std::ops;
7
8use crate::device::{Device, FirmwareVersion, Model, SerialNumber, Status};
9use crate::error::{CommandError, Error};
10use crate::otp::GenerateOtp;
11use crate::util::{get_command_result, get_cstring, get_last_error, get_struct};
12
13/// A Nitrokey Storage device without user or admin authentication.
14///
15/// Use the [`connect`][] method to obtain an instance wrapper or the [`connect_storage`] method to
16/// directly obtain an instance.  If you want to execute a command that requires user or admin
17/// authentication, use [`authenticate_admin`][] or [`authenticate_user`][].
18///
19/// # Examples
20///
21/// Authentication with error handling:
22///
23/// ```no_run
24/// use nitrokey::{Authenticate, User, Storage};
25/// # use nitrokey::Error;
26///
27/// fn perform_user_task<'a>(device: &User<'a, Storage<'a>>) {}
28/// fn perform_other_task(device: &Storage) {}
29///
30/// # fn try_main() -> Result<(), Error> {
31/// let mut manager = nitrokey::take()?;
32/// let device = manager.connect_storage()?;
33/// let device = match device.authenticate_user("123456") {
34///     Ok(user) => {
35///         perform_user_task(&user);
36///         user.device()
37///     },
38///     Err((device, err)) => {
39///         eprintln!("Could not authenticate as user: {}", err);
40///         device
41///     },
42/// };
43/// perform_other_task(&device);
44/// #     Ok(())
45/// # }
46/// ```
47///
48/// [`authenticate_admin`]: trait.Authenticate.html#method.authenticate_admin
49/// [`authenticate_user`]: trait.Authenticate.html#method.authenticate_user
50/// [`connect`]: struct.Manager.html#method.connect
51/// [`connect_storage`]: struct.Manager.html#method.connect_storage
52#[derive(Debug)]
53pub struct Storage<'a> {
54    manager: Option<&'a mut crate::Manager>,
55}
56
57/// The access mode of a volume on the Nitrokey Storage.
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub enum VolumeMode {
60    /// A read-only volume.
61    ReadOnly,
62    /// A read-write volume.
63    ReadWrite,
64}
65
66impl fmt::Display for VolumeMode {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(match *self {
69            VolumeMode::ReadOnly => "read-only",
70            VolumeMode::ReadWrite => "read-write",
71        })
72    }
73}
74
75/// The status of a volume on a Nitrokey Storage device.
76#[derive(Debug)]
77pub struct VolumeStatus {
78    /// Indicates whether the volume is read-only.
79    pub read_only: bool,
80    /// Indicates whether the volume is active.
81    pub active: bool,
82}
83
84/// Information about the SD card in a Storage device.
85#[derive(Debug)]
86pub struct SdCardData {
87    /// The serial number of the SD card.
88    pub serial_number: u32,
89    /// The size of the SD card in GB.
90    pub size: u8,
91    /// The year the card was manufactured, e. g. 17 for 2017.
92    pub manufacturing_year: u8,
93    /// The month the card was manufactured.
94    pub manufacturing_month: u8,
95    /// The OEM ID.
96    pub oem: u16,
97    /// The manufacturer ID.
98    pub manufacturer: u8,
99}
100
101/// Production information for a Storage device.
102#[derive(Debug)]
103pub struct StorageProductionInfo {
104    /// The firmware version.
105    pub firmware_version: FirmwareVersion,
106    /// The internal firmware version.
107    pub firmware_version_internal: u8,
108    /// The serial number of the CPU.
109    pub serial_number_cpu: u32,
110    /// Information about the SD card.
111    pub sd_card: SdCardData,
112}
113
114/// The status of a Nitrokey Storage device.
115#[derive(Debug)]
116pub struct StorageStatus {
117    /// The status of the unencrypted volume.
118    pub unencrypted_volume: VolumeStatus,
119    /// The status of the encrypted volume.
120    pub encrypted_volume: VolumeStatus,
121    /// The status of the hidden volume.
122    pub hidden_volume: VolumeStatus,
123    /// The firmware version.
124    pub firmware_version: FirmwareVersion,
125    /// Indicates whether the firmware is locked.
126    pub firmware_locked: bool,
127    /// The serial number of the SD card in the Storage stick.
128    pub serial_number_sd_card: u32,
129    /// The serial number of the smart card in the Storage stick.
130    pub serial_number_smart_card: u32,
131    /// The number of remaining login attempts for the user PIN.
132    pub user_retry_count: u8,
133    /// The number of remaining login attempts for the admin PIN.
134    pub admin_retry_count: u8,
135    /// Indicates whether a new SD card was found.
136    pub new_sd_card_found: bool,
137    /// Indicates whether the SD card is filled with random characters.
138    pub filled_with_random: bool,
139    /// Indicates whether the stick has been initialized by generating
140    /// the AES keys.
141    pub stick_initialized: bool,
142}
143
144/// The progress of a background operation on the Nitrokey.
145///
146/// Some commands may start a background operation during which no other commands can be executed.
147/// This enum stores the status of a background operation:  Ongoing with a relative progress (up to
148/// 100), or idle, i. e. no background operation has been started or the last one has been
149/// finished.
150#[derive(Clone, Copy, Debug, PartialEq)]
151pub enum OperationStatus {
152    /// A background operation with its progress value (less than or equal to 100).
153    Ongoing(u8),
154    /// No backgrund operation.
155    Idle,
156}
157
158impl<'a> Storage<'a> {
159    pub(crate) fn new(manager: &'a mut crate::Manager) -> Storage<'a> {
160        Storage {
161            manager: Some(manager),
162        }
163    }
164
165    /// Changes the update PIN.
166    ///
167    /// The update PIN is used to enable firmware updates.  Unlike the user and the admin PIN, the
168    /// update PIN is not managed by the OpenPGP smart card but by the Nitrokey firmware.  There is
169    /// no retry counter as with the other PIN types.
170    ///
171    /// # Errors
172    ///
173    /// - [`InvalidString`][] if one of the provided passwords contains a null byte
174    /// - [`WrongPassword`][] if the current update password is wrong
175    ///
176    /// # Example
177    ///
178    /// ```no_run
179    /// # use nitrokey::Error;
180    ///
181    /// # fn try_main() -> Result<(), Error> {
182    /// let mut manager = nitrokey::take()?;
183    /// let mut device = manager.connect_storage()?;
184    /// match device.change_update_pin("12345678", "87654321") {
185    ///     Ok(()) => println!("Updated update PIN."),
186    ///     Err(err) => eprintln!("Failed to update update PIN: {}", err),
187    /// };
188    /// #     Ok(())
189    /// # }
190    /// ```
191    ///
192    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
193    /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword
194    pub fn change_update_pin(&mut self, current: &str, new: &str) -> Result<(), Error> {
195        let current_string = get_cstring(current)?;
196        let new_string = get_cstring(new)?;
197        get_command_result(unsafe {
198            nitrokey_sys::NK_change_update_password(current_string.as_ptr(), new_string.as_ptr())
199        })
200    }
201
202    /// Enables the firmware update mode.
203    ///
204    /// During firmware update mode, the Nitrokey can no longer be accessed using HID commands.
205    /// To resume normal operation, run `dfu-programmer at32uc3a3256s launch`.  In order to enter
206    /// the firmware update mode, you need the update password that can be changed using the
207    /// [`change_update_pin`][] method.
208    ///
209    /// # Errors
210    ///
211    /// - [`InvalidString`][] if one of the provided passwords contains a null byte
212    /// - [`WrongPassword`][] if the current update password is wrong
213    ///
214    /// # Example
215    ///
216    /// ```no_run
217    /// # use nitrokey::Error;
218    ///
219    /// # fn try_main() -> Result<(), Error> {
220    /// let mut manager = nitrokey::take()?;
221    /// let mut device = manager.connect_storage()?;
222    /// match device.enable_firmware_update("12345678") {
223    ///     Ok(()) => println!("Nitrokey entered update mode."),
224    ///     Err(err) => eprintln!("Could not enter update mode: {}", err),
225    /// };
226    /// #     Ok(())
227    /// # }
228    /// ```
229    ///
230    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
231    /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword
232    pub fn enable_firmware_update(&mut self, update_pin: &str) -> Result<(), Error> {
233        let update_pin_string = get_cstring(update_pin)?;
234        get_command_result(unsafe {
235            nitrokey_sys::NK_enable_firmware_update(update_pin_string.as_ptr())
236        })
237    }
238
239    /// Enables the encrypted storage volume.
240    ///
241    /// Once the encrypted volume is enabled, it is presented to the operating system as a block
242    /// device.  The API does not provide any information on the name or path of this block device.
243    ///
244    /// # Errors
245    ///
246    /// - [`InvalidString`][] if the provided password contains a null byte
247    /// - [`WrongPassword`][] if the provided user password is wrong
248    ///
249    /// # Example
250    ///
251    /// ```no_run
252    /// # use nitrokey::Error;
253    ///
254    /// # fn try_main() -> Result<(), Error> {
255    /// let mut manager = nitrokey::take()?;
256    /// let mut device = manager.connect_storage()?;
257    /// match device.enable_encrypted_volume("123456") {
258    ///     Ok(()) => println!("Enabled the encrypted volume."),
259    ///     Err(err) => eprintln!("Could not enable the encrypted volume: {}", err),
260    /// };
261    /// #     Ok(())
262    /// # }
263    /// ```
264    ///
265    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
266    /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword
267    pub fn enable_encrypted_volume(&mut self, user_pin: &str) -> Result<(), Error> {
268        let user_pin = get_cstring(user_pin)?;
269        get_command_result(unsafe { nitrokey_sys::NK_unlock_encrypted_volume(user_pin.as_ptr()) })
270    }
271
272    /// Disables the encrypted storage volume.
273    ///
274    /// Once the volume is disabled, it can be no longer accessed as a block device.  If the
275    /// encrypted volume has not been enabled, this method still returns a success.
276    ///
277    /// # Example
278    ///
279    /// ```no_run
280    /// # use nitrokey::Error;
281    ///
282    /// fn use_volume() {}
283    ///
284    /// # fn try_main() -> Result<(), Error> {
285    /// let mut manager = nitrokey::take()?;
286    /// let mut device = manager.connect_storage()?;
287    /// match device.enable_encrypted_volume("123456") {
288    ///     Ok(()) => {
289    ///         println!("Enabled the encrypted volume.");
290    ///         use_volume();
291    ///         match device.disable_encrypted_volume() {
292    ///             Ok(()) => println!("Disabled the encrypted volume."),
293    ///             Err(err) => {
294    ///                 eprintln!("Could not disable the encrypted volume: {}", err);
295    ///             },
296    ///         };
297    ///     },
298    ///     Err(err) => eprintln!("Could not enable the encrypted volume: {}", err),
299    /// };
300    /// #     Ok(())
301    /// # }
302    /// ```
303    pub fn disable_encrypted_volume(&mut self) -> Result<(), Error> {
304        get_command_result(unsafe { nitrokey_sys::NK_lock_encrypted_volume() })
305    }
306
307    /// Enables a hidden storage volume.
308    ///
309    /// This function will only succeed if the encrypted storage ([`enable_encrypted_volume`][]) or
310    /// another hidden volume has been enabled previously.  Once the hidden volume is enabled, it
311    /// is presented to the operating system as a block device and any previously opened encrypted
312    /// or hidden volumes are closed.  The API does not provide any information on the name or path
313    /// of this block device.
314    ///
315    /// Note that the encrypted and the hidden volumes operate on the same storage area, so using
316    /// both at the same time might lead to data loss.
317    ///
318    /// The hidden volume to unlock is selected based on the provided password.
319    ///
320    /// # Errors
321    ///
322    /// - [`AesDecryptionFailed`][] if the encrypted storage has not been opened before calling
323    ///   this method or the AES key has not been built
324    /// - [`InvalidString`][] if the provided password contains a null byte
325    ///
326    /// # Example
327    ///
328    /// ```no_run
329    /// # use nitrokey::Error;
330    ///
331    /// # fn try_main() -> Result<(), Error> {
332    /// let mut manager = nitrokey::take()?;
333    /// let mut device = manager.connect_storage()?;
334    /// device.enable_encrypted_volume("123445")?;
335    /// match device.enable_hidden_volume("hidden-pw") {
336    ///     Ok(()) => println!("Enabled a hidden volume."),
337    ///     Err(err) => eprintln!("Could not enable the hidden volume: {}", err),
338    /// };
339    /// #     Ok(())
340    /// # }
341    /// ```
342    ///
343    /// [`enable_encrypted_volume`]: #method.enable_encrypted_volume
344    /// [`AesDecryptionFailed`]: enum.CommandError.html#variant.AesDecryptionFailed
345    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
346    pub fn enable_hidden_volume(&mut self, volume_password: &str) -> Result<(), Error> {
347        let volume_password = get_cstring(volume_password)?;
348        get_command_result(unsafe {
349            nitrokey_sys::NK_unlock_hidden_volume(volume_password.as_ptr())
350        })
351    }
352
353    /// Disables a hidden storage volume.
354    ///
355    /// Once the volume is disabled, it can be no longer accessed as a block device.  If no hidden
356    /// volume has been enabled, this method still returns a success.
357    ///
358    /// # Example
359    ///
360    /// ```no_run
361    /// # use nitrokey::Error;
362    ///
363    /// fn use_volume() {}
364    ///
365    /// # fn try_main() -> Result<(), Error> {
366    /// let mut manager = nitrokey::take()?;
367    /// let mut device = manager.connect_storage()?;
368    /// device.enable_encrypted_volume("123445")?;
369    /// match device.enable_hidden_volume("hidden-pw") {
370    ///     Ok(()) => {
371    ///         println!("Enabled the hidden volume.");
372    ///         use_volume();
373    ///         match device.disable_hidden_volume() {
374    ///             Ok(()) => println!("Disabled the hidden volume."),
375    ///             Err(err) => {
376    ///                 eprintln!("Could not disable the hidden volume: {}", err);
377    ///             },
378    ///         };
379    ///     },
380    ///     Err(err) => eprintln!("Could not enable the hidden volume: {}", err),
381    /// };
382    /// #     Ok(())
383    /// # }
384    /// ```
385    pub fn disable_hidden_volume(&mut self) -> Result<(), Error> {
386        get_command_result(unsafe { nitrokey_sys::NK_lock_hidden_volume() })
387    }
388
389    /// Creates a hidden volume.
390    ///
391    /// The volume is crated in the given slot and in the given range of the available memory,
392    /// where `start` is the start position as a percentage of the available memory, and `end` is
393    /// the end position as a percentage of the available memory.  The volume will be protected by
394    /// the given password.
395    ///
396    /// Note that the encrypted and the hidden volumes operate on the same storage area, so using
397    /// both at the same time might lead to data loss.
398    ///
399    /// According to the libnitrokey documentation, this function only works if the encrypted
400    /// storage has been opened.
401    ///
402    /// # Errors
403    ///
404    /// - [`AesDecryptionFailed`][] if the encrypted storage has not been opened before calling
405    ///   this method or the AES key has not been built
406    /// - [`InvalidString`][] if the provided password contains a null byte
407    ///
408    /// # Example
409    ///
410    /// ```no_run
411    /// # use nitrokey::Error;
412    ///
413    /// # fn try_main() -> Result<(), Error> {
414    /// let mut manager = nitrokey::take()?;
415    /// let mut device = manager.connect_storage()?;
416    /// device.enable_encrypted_volume("123445")?;
417    /// device.create_hidden_volume(0, 0, 100, "hidden-pw")?;
418    /// #     Ok(())
419    /// # }
420    /// ```
421    ///
422    /// [`AesDecryptionFailed`]: enum.CommandError.html#variant.AesDecryptionFailed
423    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
424    pub fn create_hidden_volume(
425        &mut self,
426        slot: u8,
427        start: u8,
428        end: u8,
429        password: &str,
430    ) -> Result<(), Error> {
431        let password = get_cstring(password)?;
432        get_command_result(unsafe {
433            nitrokey_sys::NK_create_hidden_volume(slot, start, end, password.as_ptr())
434        })
435    }
436
437    /// Sets the access mode of the unencrypted volume.
438    ///
439    /// This command will reconnect the unencrypted volume so buffers should be flushed before
440    /// calling it.  Since firmware version v0.51, this command requires the admin PIN.  Older
441    /// firmware versions are not supported.
442    ///
443    /// # Errors
444    ///
445    /// - [`InvalidString`][] if the provided password contains a null byte
446    /// - [`WrongPassword`][] if the provided admin password is wrong
447    ///
448    /// # Example
449    ///
450    /// ```no_run
451    /// # use nitrokey::Error;
452    /// use nitrokey::VolumeMode;
453    ///
454    /// # fn try_main() -> Result<(), Error> {
455    /// let mut manager = nitrokey::take()?;
456    /// let mut device = manager.connect_storage()?;
457    /// match device.set_unencrypted_volume_mode("12345678", VolumeMode::ReadWrite) {
458    ///     Ok(()) => println!("Set the unencrypted volume to read-write mode."),
459    ///     Err(err) => eprintln!("Could not set the unencrypted volume to read-write mode: {}", err),
460    /// };
461    /// #     Ok(())
462    /// # }
463    /// ```
464    ///
465    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
466    /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword
467    pub fn set_unencrypted_volume_mode(
468        &mut self,
469        admin_pin: &str,
470        mode: VolumeMode,
471    ) -> Result<(), Error> {
472        let admin_pin = get_cstring(admin_pin)?;
473        let result = match mode {
474            VolumeMode::ReadOnly => unsafe {
475                nitrokey_sys::NK_set_unencrypted_read_only_admin(admin_pin.as_ptr())
476            },
477            VolumeMode::ReadWrite => unsafe {
478                nitrokey_sys::NK_set_unencrypted_read_write_admin(admin_pin.as_ptr())
479            },
480        };
481        get_command_result(result)
482    }
483
484    /// Sets the access mode of the encrypted volume.
485    ///
486    /// This command will reconnect the encrypted volume so buffers should be flushed before
487    /// calling it.  It is only available in firmware version 0.49.
488    ///
489    /// # Errors
490    ///
491    /// - [`InvalidString`][] if the provided password contains a null byte
492    /// - [`WrongPassword`][] if the provided admin password is wrong
493    ///
494    /// # Example
495    ///
496    /// ```no_run
497    /// # use nitrokey::Error;
498    /// use nitrokey::VolumeMode;
499    ///
500    /// # fn try_main() -> Result<(), Error> {
501    /// let mut manager = nitrokey::take()?;
502    /// let mut device = manager.connect_storage()?;
503    /// match device.set_encrypted_volume_mode("12345678", VolumeMode::ReadWrite) {
504    ///     Ok(()) => println!("Set the encrypted volume to read-write mode."),
505    ///     Err(err) => eprintln!("Could not set the encrypted volume to read-write mode: {}", err),
506    /// };
507    /// #     Ok(())
508    /// # }
509    /// ```
510    ///
511    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
512    /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword
513    pub fn set_encrypted_volume_mode(
514        &mut self,
515        admin_pin: &str,
516        mode: VolumeMode,
517    ) -> Result<(), Error> {
518        let admin_pin = get_cstring(admin_pin)?;
519        let result = match mode {
520            VolumeMode::ReadOnly => unsafe {
521                nitrokey_sys::NK_set_encrypted_read_only(admin_pin.as_ptr())
522            },
523            VolumeMode::ReadWrite => unsafe {
524                nitrokey_sys::NK_set_encrypted_read_write(admin_pin.as_ptr())
525            },
526        };
527        get_command_result(result)
528    }
529
530    /// Returns the status of the connected storage device.
531    ///
532    /// # Example
533    ///
534    /// ```no_run
535    /// # use nitrokey::Error;
536    ///
537    /// fn use_volume() {}
538    ///
539    /// # fn try_main() -> Result<(), Error> {
540    /// let mut manager = nitrokey::take()?;
541    /// let device = manager.connect_storage()?;
542    /// match device.get_storage_status() {
543    ///     Ok(status) => {
544    ///         println!("SD card ID: {:#x}", status.serial_number_sd_card);
545    ///     },
546    ///     Err(err) => eprintln!("Could not get Storage status: {}", err),
547    /// };
548    /// #     Ok(())
549    /// # }
550    /// ```
551    pub fn get_storage_status(&self) -> Result<StorageStatus, Error> {
552        get_struct(|out| unsafe { nitrokey_sys::NK_get_status_storage(out) })
553    }
554
555    /// Returns the production information for the connected storage device.
556    ///
557    /// # Example
558    ///
559    /// ```no_run
560    /// # use nitrokey::Error;
561    ///
562    /// fn use_volume() {}
563    ///
564    /// # fn try_main() -> Result<(), Error> {
565    /// let mut manager = nitrokey::take()?;
566    /// let device = manager.connect_storage()?;
567    /// match device.get_production_info() {
568    ///     Ok(data) => {
569    ///         println!("SD card ID:   {:#x}", data.sd_card.serial_number);
570    ///         println!("SD card size: {} GB", data.sd_card.size);
571    ///     },
572    ///     Err(err) => eprintln!("Could not get Storage production info: {}", err),
573    /// };
574    /// #     Ok(())
575    /// # }
576    /// ```
577    pub fn get_production_info(&self) -> Result<StorageProductionInfo, Error> {
578        get_struct(|out| unsafe { nitrokey_sys::NK_get_storage_production_info(out) })
579    }
580
581    /// Clears the warning for a new SD card.
582    ///
583    /// The Storage status contains a field for a new SD card warning.  After a factory reset, the
584    /// field is set to true.  After filling the SD card with random data, it is set to false.
585    /// This method can be used to set it to false without filling the SD card with random data.
586    ///
587    /// # Errors
588    ///
589    /// - [`InvalidString`][] if the provided password contains a null byte
590    /// - [`WrongPassword`][] if the provided admin password is wrong
591    ///
592    /// # Example
593    ///
594    /// ```no_run
595    /// # use nitrokey::Error;
596    ///
597    /// # fn try_main() -> Result<(), Error> {
598    /// let mut manager = nitrokey::take()?;
599    /// let mut device = manager.connect_storage()?;
600    /// match device.clear_new_sd_card_warning("12345678") {
601    ///     Ok(()) => println!("Cleared the new SD card warning."),
602    ///     Err(err) => eprintln!("Could not set the clear the new SD card warning: {}", err),
603    /// };
604    /// #     Ok(())
605    /// # }
606    /// ```
607    ///
608    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
609    /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword
610    pub fn clear_new_sd_card_warning(&mut self, admin_pin: &str) -> Result<(), Error> {
611        let admin_pin = get_cstring(admin_pin)?;
612        get_command_result(unsafe {
613            nitrokey_sys::NK_clear_new_sd_card_warning(admin_pin.as_ptr())
614        })
615    }
616
617    /// Returns a range of the SD card that has not been used to during this power cycle.
618    ///
619    /// The Nitrokey Storage tracks read and write access to the SD card during a power cycle.
620    /// This method returns a range of the SD card that has not been accessed during this power
621    /// cycle.  The range is relative to the total size of the SD card, so both values are less
622    /// than or equal to 100.  This can be used as a guideline when creating a hidden volume.
623    ///
624    /// # Example
625    ///
626    /// ```no_run
627    /// let mut manager = nitrokey::take()?;
628    /// let storage = manager.connect_storage()?;
629    /// let usage = storage.get_sd_card_usage()?;
630    /// println!("SD card usage: {}..{}", usage.start, usage.end);
631    /// # Ok::<(), nitrokey::Error>(())
632    /// ```
633    pub fn get_sd_card_usage(&self) -> Result<ops::Range<u8>, Error> {
634        let mut usage_data = nitrokey_sys::NK_SD_usage_data::default();
635        let result = unsafe { nitrokey_sys::NK_get_SD_usage_data(&mut usage_data) };
636        match get_command_result(result) {
637            Ok(_) => {
638                if usage_data.write_level_min > usage_data.write_level_max
639                    || usage_data.write_level_max > 100
640                {
641                    Err(Error::UnexpectedError("Invalid write levels".to_owned()))
642                } else {
643                    Ok(ops::Range {
644                        start: usage_data.write_level_min,
645                        end: usage_data.write_level_max,
646                    })
647                }
648            }
649            Err(err) => Err(err),
650        }
651    }
652
653    /// Blinks the red and green LED alternatively and infinitely until the device is reconnected.
654    pub fn wink(&mut self) -> Result<(), Error> {
655        get_command_result(unsafe { nitrokey_sys::NK_wink() })
656    }
657
658    /// Returns the status of an ongoing background operation on the Nitrokey Storage.
659    ///
660    /// Some commands may start a background operation during which no other commands can be
661    /// executed.  This method can be used to check whether such an operation is ongoing.
662    ///
663    /// Currently, this is only used by the [`fill_sd_card`][] method.
664    ///
665    /// [`fill_sd_card`]: #method.fill_sd_card
666    pub fn get_operation_status(&self) -> Result<OperationStatus, Error> {
667        let status = unsafe { nitrokey_sys::NK_get_progress_bar_value() };
668        match status {
669            0..=100 => u8::try_from(status)
670                .map(OperationStatus::Ongoing)
671                .map_err(|_| {
672                    Error::UnexpectedError("Cannot create u8 from operation status".to_owned())
673                }),
674            -1 => Ok(OperationStatus::Idle),
675            -2 => Err(get_last_error()),
676            _ => Err(Error::UnexpectedError(
677                "Invalid operation status".to_owned(),
678            )),
679        }
680    }
681
682    /// Overwrites the SD card with random data.
683    ///
684    /// Ths method starts a background operation that overwrites the SD card with random data.
685    /// While this operation is ongoing, no other commands can be executed.  Use the
686    /// [`get_operation_status`][] function to check the progress of the operation.
687    ///
688    /// # Errors
689    ///
690    /// - [`InvalidString`][] if one of the provided passwords contains a null byte
691    /// - [`WrongPassword`][] if the admin password is wrong
692    ///
693    /// # Example
694    ///
695    /// ```no_run
696    /// use nitrokey::OperationStatus;
697    ///
698    /// let mut manager = nitrokey::take()?;
699    /// let mut storage = manager.connect_storage()?;
700    /// storage.fill_sd_card("12345678")?;
701    /// loop {
702    ///     match storage.get_operation_status()? {
703    ///         OperationStatus::Ongoing(progress) => println!("{}/100", progress),
704    ///         OperationStatus::Idle => {
705    ///             println!("Done!");
706    ///             break;
707    ///         }
708    ///     }
709    /// }
710    /// # Ok::<(), nitrokey::Error>(())
711    /// ```
712    ///
713    /// [`get_operation_status`]: #method.get_operation_status
714    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
715    /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword
716    pub fn fill_sd_card(&mut self, admin_pin: &str) -> Result<(), Error> {
717        let admin_pin_string = get_cstring(admin_pin)?;
718        get_command_result(unsafe {
719            nitrokey_sys::NK_fill_SD_card_with_random_data(admin_pin_string.as_ptr())
720        })
721        .or_else(|err| match err {
722            // libnitrokey’s C API returns a LongOperationInProgressException with the same error
723            // code as the WrongCrc command error, so we cannot distinguish them.
724            Error::CommandError(CommandError::WrongCrc) => Ok(()),
725            err => Err(err),
726        })
727    }
728
729    /// Exports the firmware to the unencrypted volume.
730    ///
731    /// This command requires the admin PIN.  The unencrypted volume must be in read-write mode
732    /// when this command is executed.  Otherwise, it will still return `Ok` but not write the
733    /// firmware.
734    ///
735    /// This command unmounts the unencrypted volume if it has been mounted, so all buffers should
736    /// be flushed.  The firmware is written to the `firmware.bin` file on the unencrypted volume.
737    ///
738    /// # Errors
739    ///
740    /// - [`InvalidString`][] if one of the provided passwords contains a null byte
741    /// - [`WrongPassword`][] if the admin password is wrong
742    ///
743    /// [`InvalidString`]: enum.LibraryError.html#variant.InvalidString
744    /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword
745    pub fn export_firmware(&mut self, admin_pin: &str) -> Result<(), Error> {
746        let admin_pin_string = get_cstring(admin_pin)?;
747        get_command_result(unsafe { nitrokey_sys::NK_export_firmware(admin_pin_string.as_ptr()) })
748    }
749}
750
751impl<'a> Drop for Storage<'a> {
752    fn drop(&mut self) {
753        unsafe {
754            nitrokey_sys::NK_logout();
755        }
756    }
757}
758
759impl<'a> Device<'a> for Storage<'a> {
760    fn into_manager(mut self) -> &'a mut crate::Manager {
761        self.manager.take().unwrap()
762    }
763
764    fn get_model(&self) -> Model {
765        Model::Storage
766    }
767
768    fn get_status(&self) -> Result<Status, Error> {
769        // Currently, the GET_STATUS command does not report the correct firmware version and
770        // serial number on the Nitrokey Storage, see [0].  Until this is fixed in libnitrokey, we
771        // have to manually execute the GET_DEVICE_STATUS command (get_storage_status) and complete
772        // the missing data, see [1].
773        // [0] https://github.com/Nitrokey/nitrokey-storage-firmware/issues/96
774        // [1] https://github.com/Nitrokey/libnitrokey/issues/166
775
776        let mut status: Status = get_struct(|out| unsafe { nitrokey_sys::NK_get_status(out) })?;
777
778        let storage_status = self.get_storage_status()?;
779        status.firmware_version = storage_status.firmware_version;
780        status.serial_number = SerialNumber::new(storage_status.serial_number_smart_card);
781
782        Ok(status)
783    }
784}
785
786impl<'a> GenerateOtp for Storage<'a> {}
787
788impl From<nitrokey_sys::NK_storage_ProductionTest> for StorageProductionInfo {
789    fn from(data: nitrokey_sys::NK_storage_ProductionTest) -> Self {
790        Self {
791            firmware_version: FirmwareVersion {
792                major: data.FirmwareVersion_au8[0],
793                minor: data.FirmwareVersion_au8[1],
794            },
795            firmware_version_internal: data.FirmwareVersionInternal_u8,
796            serial_number_cpu: data.CPU_CardID_u32,
797            sd_card: SdCardData {
798                serial_number: data.SD_CardID_u32,
799                size: data.SD_Card_Size_u8,
800                manufacturing_year: data.SD_Card_ManufacturingYear_u8,
801                manufacturing_month: data.SD_Card_ManufacturingMonth_u8,
802                oem: data.SD_Card_OEM_u16,
803                manufacturer: data.SD_Card_Manufacturer_u8,
804            },
805        }
806    }
807}
808
809impl From<nitrokey_sys::NK_storage_status> for StorageStatus {
810    fn from(status: nitrokey_sys::NK_storage_status) -> Self {
811        StorageStatus {
812            unencrypted_volume: VolumeStatus {
813                read_only: status.unencrypted_volume_read_only,
814                active: status.unencrypted_volume_active,
815            },
816            encrypted_volume: VolumeStatus {
817                read_only: status.encrypted_volume_read_only,
818                active: status.encrypted_volume_active,
819            },
820            hidden_volume: VolumeStatus {
821                read_only: status.hidden_volume_read_only,
822                active: status.hidden_volume_active,
823            },
824            firmware_version: FirmwareVersion {
825                major: status.firmware_version_major,
826                minor: status.firmware_version_minor,
827            },
828            firmware_locked: status.firmware_locked,
829            serial_number_sd_card: status.serial_number_sd_card,
830            serial_number_smart_card: status.serial_number_smart_card,
831            user_retry_count: status.user_retry_count,
832            admin_retry_count: status.admin_retry_count,
833            new_sd_card_found: status.new_sd_card_found,
834            filled_with_random: status.filled_with_random,
835            stick_initialized: status.stick_initialized,
836        }
837    }
838}