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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! YubiHSM client: core functionality of this crate.
//!
//! The `Client` type provides a set of methods which map to commands which
//! interface with the HSM.
//!
//! <https://developers.yubico.com/YubiHSM2/Commands/>

#![allow(clippy::too_many_arguments)]

#[macro_use]
mod error;

pub use self::error::{ClientError, ClientErrorKind};

use self::error::ClientErrorKind::*;
use crate::{
    asymmetric::{
        self,
        attestation::{self, commands::*},
        commands::*,
        ecdsa::{self, commands::*},
        ed25519::{self, commands::*},
        PublicKey,
    },
    audit::{commands::*, *},
    authentication::{self, commands::*, Credentials},
    capability::Capability,
    command::{self, Command},
    connector::Connector,
    device::commands::*,
    domain::Domain,
    hmac::{self, commands::*},
    object::{self, commands::*, generate},
    opaque::{self, commands::*},
    otp::{self, commands::*},
    serialization::{deserialize, serialize},
    session::{self, Session},
    uuid,
    wrap::{self, commands::*},
};
use std::time::{Duration, Instant};
#[cfg(feature = "rsa")]
use {
    crate::asymmetric::rsa::{self, pkcs1::commands::*, pss::commands::*},
    byteorder::{BigEndian, ByteOrder},
    sha2::{Digest, Sha256},
};

/// YubiHSM client: main API in this crate for accessing functions of the
/// HSM hardware device.
pub struct Client {
    /// Connector for communicating with the HSM
    connector: Connector,

    /// Encrypted session with the HSM (if we have one open)
    session: Option<Session>,

    /// Cached `Credentials` for reconnecting closed sessions
    credentials: Option<Credentials>,
}

impl Client {
    /// Open a connection via a [Connector] to a YubiHSM, returning a `yubihsm::Client`.
    /// Valid `Connector` types are: [HttpConnector], [UsbConnector], and [MockHsm].
    ///
    /// [Connector]: https://docs.rs/yubihsm/latest/yubihsm/connector/index.html
    /// [HttpConnector]: https://docs.rs/yubihsm/latest/yubihsm/connector/http/struct.HttpConnector.html
    /// [UsbConnector]: https://docs.rs/yubihsm/latest/yubihsm/connector/usb/struct.UsbConnector.html
    /// [MockHsm]: https://docs.rs/yubihsm/latest/yubihsm/mockhsm/struct.MockHsm.html
    pub fn open<C>(
        connector: C,
        credentials: Credentials,
        reconnect: bool,
    ) -> Result<Self, ClientError>
    where
        C: Into<Connector>,
    {
        let mut client = Self::create(connector, credentials)?;
        client.connect()?;

        // Clear credentials if reconnecting has been disabled
        if !reconnect {
            client.credentials = None;
        }

        Ok(client)
    }

    /// Create a `yubihsm::Client`, but defer connecting until `connect()` is called.
    pub fn create<C>(connector: C, credentials: Credentials) -> Result<Self, ClientError>
    where
        C: Into<Connector>,
    {
        let client = Self {
            connector: connector.into(),
            session: None,
            credentials: Some(credentials),
        };

        Ok(client)
    }

    /// Try to make a clone of this client

    /// Connect to the HSM (idempotently, i.e. returns success if we have
    /// an open connection already)
    pub fn connect(&mut self) -> Result<(), ClientError> {
        self.session()?;
        Ok(())
    }

    /// Are we currently connected to the HSM?
    pub fn is_connected(&self) -> bool {
        self.session.as_ref().map(Session::is_open).unwrap_or(false)
    }

    /// Get the current session ID (if we have an open session).
    pub fn session_id(&self) -> Option<session::Id> {
        self.session.as_ref().and_then(|s| Some(s.id()))
    }

    /// Get current `Session` (either opening a new one or returning an already
    /// open one).
    pub fn session(&mut self) -> Result<&mut Session, ClientError> {
        if self.is_connected() {
            return Ok(self.session.as_mut().unwrap());
        }

        let session = Session::open(
            self.connector.clone(),
            self.credentials
                .as_ref()
                .ok_or_else(|| err!(AuthenticationError, "session reconnection disabled"))?,
            session::Timeout::default(),
        )?;

        self.session = Some(session);
        Ok(self.session.as_mut().unwrap())
    }

    /// Ping the HSM, ensuring we have a live connection and returning the
    /// end-to-end latency.
    pub fn ping(&mut self) -> Result<Duration, ClientError> {
        let t = Instant::now();
        let uuid = uuid::new_v4().to_hyphenated().to_string();
        let response = self.echo(uuid.as_bytes())?;

        ensure!(
            uuid.as_bytes() == response.as_slice(),
            ResponseError,
            "expected {}, got {}",
            uuid,
            String::from_utf8_lossy(&response)
        );

        Ok(Instant::now().duration_since(t))
    }

    /// Encrypt a command, send it to the HSM, then read and decrypt the response.
    fn send_command<T: Command>(&mut self, command: T) -> Result<T::ResponseType, ClientError> {
        Ok(self.session()?.send_command(command)?)
    }

    //
    // HSM Commands
    // <https://developers.yubico.com/YubiHSM2/Commands/>
    //

    /// Blink the HSM's LEDs (to identify it) for the given number of seconds.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Blink_Device.html>
    pub fn blink_device(&mut self, num_seconds: u8) -> Result<(), ClientError> {
        self.send_command(BlinkDeviceCommand { num_seconds })?;
        Ok(())
    }

    /// Delete an object of the given ID and type.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Delete_Object.html>
    pub fn delete_object(
        &mut self,
        object_id: object::Id,
        object_type: object::Type,
    ) -> Result<(), ClientError> {
        self.send_command(DeleteObjectCommand {
            object_id,
            object_type,
        })?;
        Ok(())
    }

    /// Get information about the HSM device.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Device_Info.html>
    pub fn device_info(&mut self) -> Result<DeviceInfoResponse, ClientError> {
        Ok(self.send_command(DeviceInfoCommand {})?)
    }

    /// Echo a message sent to the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Echo.html>
    pub fn echo<M>(&mut self, msg: M) -> Result<Vec<u8>, ClientError>
    where
        M: Into<Vec<u8>>,
    {
        Ok(self
            .send_command(EchoCommand {
                message: msg.into(),
            })?
            .0)
    }

    /// Export an encrypted object from the HSM using the given key-wrapping key.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Export_Wrapped.html>
    pub fn export_wrapped(
        &mut self,
        wrap_key_id: object::Id,
        object_type: object::Type,
        object_id: object::Id,
    ) -> Result<wrap::Message, ClientError> {
        Ok(self
            .send_command(ExportWrappedCommand {
                wrap_key_id,
                object_type,
                object_id,
            })?
            .0)
    }

    /// Generate a new asymmetric key within the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Generate_Asymmetric_Key.html>
    pub fn generate_asymmetric_key(
        &mut self,
        key_id: object::Id,
        label: object::Label,
        domains: Domain,
        capabilities: Capability,
        algorithm: asymmetric::Algorithm,
    ) -> Result<object::Id, ClientError> {
        Ok(self
            .send_command(GenAsymmetricKeyCommand(generate::Params {
                key_id,
                label,
                domains,
                capabilities,
                algorithm: algorithm.into(),
            }))?
            .key_id)
    }

    /// Generate a new HMAC key within the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Generate_Hmac_Key.html>
    pub fn generate_hmac_key(
        &mut self,
        key_id: object::Id,
        label: object::Label,
        domains: Domain,
        capabilities: Capability,
        algorithm: hmac::Algorithm,
    ) -> Result<object::Id, ClientError> {
        Ok(self
            .send_command(GenHmacKeyCommand(generate::Params {
                key_id,
                label,
                domains,
                capabilities,
                algorithm: algorithm.into(),
            }))?
            .key_id)
    }

    /// Generate a new wrap key within the HSM.
    ///
    /// Delegated capabilities are the set of `Capability` bits that an object is allowed to have
    /// when imported or exported using the wrap key.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Generate_Wrap_Key.html>
    pub fn generate_wrap_key(
        &mut self,
        key_id: object::Id,
        label: object::Label,
        domains: Domain,
        capabilities: Capability,
        delegated_capabilities: Capability,
        algorithm: wrap::Algorithm,
    ) -> Result<object::Id, ClientError> {
        Ok(self
            .send_command(GenWrapKeyCommand {
                params: generate::Params {
                    key_id,
                    label,
                    domains,
                    capabilities,
                    algorithm: algorithm.into(),
                },
                delegated_capabilities,
            })?
            .key_id)
    }

    /// Get audit logs from the HSM device.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Get_Log_Entries.html>
    pub fn get_log_entries(&mut self) -> Result<LogEntries, ClientError> {
        Ok(self.send_command(GetLogEntriesCommand {})?)
    }

    /// Get information about an object.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Get_Object_Info.html>
    pub fn get_object_info(
        &mut self,
        object_id: object::Id,
        object_type: object::Type,
    ) -> Result<object::Info, ClientError> {
        Ok(self
            .send_command(GetObjectInfoCommand(object::Handle::new(
                object_id,
                object_type,
            )))?
            .0)
    }

    /// Get an opaque object stored in the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Get_Opaque.html>
    pub fn get_opaque(&mut self, object_id: object::Id) -> Result<Vec<u8>, ClientError> {
        Ok(self.send_command(GetOpaqueCommand { object_id })?.0)
    }

    /// Get the audit policy setting for a particular command.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Get_Option.html>
    pub fn get_command_audit_option(
        &mut self,
        command: command::Code,
    ) -> Result<AuditOption, ClientError> {
        let command_audit_options = self.get_commands_audit_options()?;
        Ok(command_audit_options
            .iter()
            .find(|opt| opt.command_type() == command)
            .map(|opt| opt.audit_option())
            .unwrap_or(AuditOption::Off))
    }

    /// Get the audit policy settings for all commands.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Get_Option.html>
    pub fn get_commands_audit_options(&mut self) -> Result<Vec<AuditCommand>, ClientError> {
        let response = self.send_command(GetOptionCommand {
            tag: AuditTag::Command,
        })?;

        Ok(deserialize(&response.0)?)
    }

    /// Get the forced auditing global option: when enabled, the device will
    /// refuse operations if the [log store] becomes full.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Get_Option.html>
    /// [log store]: https://developers.yubico.com/YubiHSM2/Concepts/Logs.html
    pub fn get_force_audit_option(&mut self) -> Result<AuditOption, ClientError> {
        let response = self.send_command(GetOptionCommand {
            tag: AuditTag::Force,
        })?;

        ensure!(
            response.0.len() == 1,
            ProtocolError,
            "expected 1-byte response, got {}",
            response.0.len()
        );

        AuditOption::from_u8(response.0[0]).map_err(|e| err!(ProtocolError, e))
    }

    /// Get some number of bytes of pseudo random data generated on the device.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Get_Pseudo_Random.html>
    pub fn get_pseudo_random(&mut self, bytes: usize) -> Result<Vec<u8>, ClientError> {
        ensure!(
            bytes <= MAX_RAND_BYTES,
            ProtocolError,
            "requested number of bytes too large: {} (max: {})",
            bytes,
            MAX_RAND_BYTES
        );

        Ok(self
            .send_command(GetPseudoRandomCommand {
                bytes: bytes as u16,
            })?
            .bytes)
    }

    /// Get the public key for an asymmetric key stored on the device.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Get_Public_Key.html>
    pub fn get_public_key(&mut self, key_id: object::Id) -> Result<PublicKey, ClientError> {
        Ok(self.send_command(GetPublicKeyCommand { key_id })?.into())
    }

    /// Get storage status (i.e. currently free storage) from the HSM device.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Get_Storage_Info.html>
    pub fn get_storage_info(&mut self) -> Result<GetStorageInfoResponse, ClientError> {
        Ok(self.send_command(GetStorageInfoCommand {})?)
    }

    /// Import an encrypted object from the HSM using the given key-wrapping key.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Import_Wrapped.html>
    pub fn import_wrapped<M>(
        &mut self,
        wrap_key_id: object::Id,
        wrap_message: M,
    ) -> Result<ImportWrappedResponse, ClientError>
    where
        M: Into<wrap::Message>,
    {
        let wrap::Message { nonce, ciphertext } = wrap_message.into();

        Ok(self.send_command(ImportWrappedCommand {
            wrap_key_id,
            nonce,
            ciphertext,
        })?)
    }

    /// List objects visible from the current session.
    ///
    /// Optionally apply a set of provided `filters` which select objects
    /// based on their attributes.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/List_Objects.html>
    pub fn list_objects(
        &mut self,
        filters: &[object::Filter],
    ) -> Result<Vec<object::Entry>, ClientError> {
        let mut filter_bytes = vec![];

        for filter in filters {
            filter.serialize(&mut filter_bytes)?;
        }

        Ok(self.send_command(ListObjectsCommand(filter_bytes))?.0)
    }

    /// Put an existing asymmetric key into the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Put_Asymmetric.html>
    pub fn put_asymmetric_key<K>(
        &mut self,
        key_id: object::Id,
        label: object::Label,
        domains: Domain,
        capabilities: Capability,
        algorithm: asymmetric::Algorithm,
        key_bytes: K,
    ) -> Result<object::Id, ClientError>
    where
        K: Into<Vec<u8>>,
    {
        let data = key_bytes.into();

        if data.len() != algorithm.key_len() {
            fail!(
                ProtocolError,
                "invalid key length for {:?}: {} (expected {})",
                algorithm,
                data.len(),
                algorithm.key_len()
            );
        }

        Ok(self
            .send_command(PutAsymmetricKeyCommand {
                params: object::import::Params {
                    id: key_id,
                    label,
                    domains,
                    capabilities,
                    algorithm: algorithm.into(),
                },
                data,
            })?
            .key_id)
    }

    /// Put an existing `authentication::Key` into the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Put_Authentication_Key.html>
    pub fn put_authentication_key<K>(
        &mut self,
        key_id: object::Id,
        label: object::Label,
        domains: Domain,
        capabilities: Capability,
        delegated_capabilities: Capability,
        algorithm: authentication::Algorithm,
        authentication_key: K,
    ) -> Result<object::Id, ClientError>
    where
        K: Into<authentication::Key>,
    {
        Ok(self
            .send_command(PutAuthenticationKeyCommand {
                params: object::import::Params {
                    id: key_id,
                    label,
                    domains,
                    capabilities,
                    algorithm: algorithm.into(),
                },
                delegated_capabilities,
                authentication_key: authentication_key.into(),
            })?
            .key_id)
    }

    /// Put an existing HMAC key into the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Put_Hmac_Key.html>
    pub fn put_hmac_key<K>(
        &mut self,
        key_id: object::Id,
        label: object::Label,
        domains: Domain,
        capabilities: Capability,
        algorithm: hmac::Algorithm,
        key_bytes: K,
    ) -> Result<object::Id, ClientError>
    where
        K: Into<Vec<u8>>,
    {
        let hmac_key = key_bytes.into();

        if hmac_key.len() < HMAC_MIN_KEY_SIZE || hmac_key.len() > algorithm.max_key_len() {
            fail!(
                ProtocolError,
                "invalid key length for {:?}: {} (min {}, max {})",
                algorithm,
                hmac_key.len(),
                HMAC_MIN_KEY_SIZE,
                algorithm.max_key_len()
            );
        }

        Ok(self
            .send_command(PutHmacKeyCommand {
                params: object::import::Params {
                    id: key_id,
                    label,
                    domains,
                    capabilities,
                    algorithm: algorithm.into(),
                },
                hmac_key,
            })?
            .key_id)
    }

    /// Put an opaque object (X.509 certificate or other bytestring) into the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Put_Opaque.html>
    pub fn put_opaque<B>(
        &mut self,
        object_id: object::Id,
        label: object::Label,
        domains: Domain,
        capabilities: Capability,
        algorithm: opaque::Algorithm,
        opaque_data: B,
    ) -> Result<object::Id, ClientError>
    where
        B: Into<Vec<u8>>,
    {
        Ok(self
            .send_command(PutOpaqueCommand {
                params: object::import::Params {
                    id: object_id,
                    label,
                    domains,
                    capabilities,
                    algorithm: algorithm.into(),
                },
                data: opaque_data.into(),
            })?
            .object_id)
    }

    /// Put an existing OTP AEAD key into the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Put_Otp_Aead_Key.html>
    pub fn put_otp_aead_key<K>(
        &mut self,
        key_id: object::Id,
        label: object::Label,
        domains: Domain,
        capabilities: Capability,
        algorithm: otp::Algorithm,
        key_bytes: K,
    ) -> Result<object::Id, ClientError>
    where
        K: Into<Vec<u8>>,
    {
        let data = key_bytes.into();

        if data.len() != algorithm.key_len() {
            fail!(
                ProtocolError,
                "invalid key length for {:?}: {} (expected {})",
                algorithm,
                data.len(),
                algorithm.key_len()
            );
        }

        Ok(self
            .send_command(PutOTPAEADKeyCommand {
                params: object::import::Params {
                    id: key_id,
                    label,
                    domains,
                    capabilities,
                    algorithm: algorithm.into(),
                },
                data,
            })?
            .key_id)
    }

    /// Put an existing wrap key into the HSM.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Put_Wrap_Key.html>
    pub fn put_wrap_key<K>(
        &mut self,
        key_id: object::Id,
        label: object::Label,
        domains: Domain,
        capabilities: Capability,
        delegated_capabilities: Capability,
        algorithm: wrap::Algorithm,
        key_bytes: K,
    ) -> Result<object::Id, ClientError>
    where
        K: Into<Vec<u8>>,
    {
        let data = key_bytes.into();

        if data.len() != algorithm.key_len() {
            fail!(
                ProtocolError,
                "invalid key length for {:?}: {} (expected {})",
                algorithm,
                data.len(),
                algorithm.key_len()
            );
        }

        Ok(self
            .send_command(PutWrapKeyCommand {
                params: object::import::Params {
                    id: key_id,
                    label,
                    domains,
                    capabilities,
                    algorithm: algorithm.into(),
                },
                delegated_capabilities,
                data,
            })?
            .key_id)
    }

    /// Reset the HSM to a factory default state and reboot, clearing all
    /// stored objects and restoring the default auth key.
    ///
    /// **WARNING:** This wipes all keys and other data from the HSM! Make
    /// absolutely sure you want to use this!
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Reset_Device.html>
    pub fn reset_device(&mut self) -> Result<(), ClientError> {
        // TODO: handle potential errors that occur when resetting
        if let Err(e) = self.send_command(ResetDeviceCommand {}) {
            debug!("error sending reset command: {}", e);
        }

        // Resetting the HSM invalidates our session
        if let Some(ref mut session) = self.session {
            session.abort();
        }

        Ok(())
    }

    /// Configure the audit policy settings for a particular command, e.g. auditing
    /// should be `On`, `Off`, or `Fix` (i.e. fixed permanently on).
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Set_Option.html>
    pub fn set_command_audit_option(
        &mut self,
        command: command::Code,
        audit_option: AuditOption,
    ) -> Result<(), ClientError> {
        self.send_command(SetOptionCommand {
            tag: AuditTag::Command,
            length: 2,
            value: serialize(&AuditCommand(command, audit_option))?,
        })?;

        Ok(())
    }

    /// Put the forced auditing global option: when enabled, the device will
    /// refuse operations if the [log store] becomes full.
    ///
    /// Options are `On`, `Off`, or `Fix` (i.e. fixed permanently on)
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Put_Option.html>
    ///
    /// [log store]: https://developers.yubico.com/YubiHSM2/Concepts/Logs.html
    pub fn set_force_audit_option(&mut self, option: AuditOption) -> Result<(), ClientError> {
        self.send_command(SetOptionCommand {
            tag: AuditTag::Force,
            length: 1,
            value: vec![option.to_u8()],
        })?;

        Ok(())
    }

    /// Set the index of the last consumed index of the HSM audit log.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Set_Log_Index.html>
    pub fn set_log_index(&mut self, log_index: u16) -> Result<(), ClientError> {
        self.send_command(SetLogIndexCommand { log_index })?;
        Ok(())
    }

    /// Obtain an X.509 attestation certificate for a key within the HSM.
    /// This can be used to demonstrate that a given key was generated by
    /// and stored within a HSM in a non-exportable manner.
    ///
    /// The `key_id` is the subject key for which an attestation certificate
    /// is created, and the`attestation_key_id` will be used to sign the
    /// attestation certificate.
    ///
    /// If no attestation key is given, the device's default attestation key
    /// will be used, and can be verified against Yubico's certificate.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Sign_Attestation_Certificate.html>
    pub fn sign_attestation_certificate(
        &mut self,
        key_id: object::Id,
        attestation_key_id: Option<object::Id>,
    ) -> Result<attestation::Certificate, ClientError> {
        Ok(self.send_command(SignAttestationCertificateCommand {
            key_id,
            attestation_key_id: attestation_key_id.unwrap_or(0),
        })?)
    }

    /// Compute an ECDSA signature of the given digest (i.e. a precomputed SHA-2 digest)
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Sign_Ecdsa.html>
    ///
    /// # secp256k1 notes
    ///
    /// The YubiHSM 2 does not produce signatures in "low S" form, which is expected
    /// for most cryptocurrency applications (the typical use case for secp256k1).
    ///
    /// If your application demands this (e.g. Bitcoin), you'll need to normalize
    /// the signatures. One option for this is the `secp256k1` crate's
    /// [Signature::normalize_s] function.
    ///
    /// Normalization functionality is built into the `yubihsm::signatory` API
    /// found in this crate (when the `secp256k1` feature is enabled).
    pub fn sign_ecdsa<T>(
        &mut self,
        key_id: object::Id,
        digest: T,
    ) -> Result<ecdsa::Signature, ClientError>
    where
        T: Into<Vec<u8>>,
    {
        Ok(self
            .send_command(SignEcdsaCommand {
                key_id,
                digest: digest.into(),
            })?
            .into())
    }

    /// Compute an Ed25519 signature with the given key ID.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Sign_Eddsa.html>
    pub fn sign_ed25519<T>(
        &mut self,
        key_id: object::Id,
        data: T,
    ) -> Result<ed25519::Signature, ClientError>
    where
        T: Into<Vec<u8>>,
    {
        Ok(self
            .send_command(SignEddsaCommand {
                key_id,
                data: data.into(),
            })?
            .into())
    }

    /// Compute an HMAC tag of the given data with the given key ID.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Sign_Hmac.html>
    pub fn sign_hmac<M>(&mut self, key_id: object::Id, msg: M) -> Result<hmac::Tag, ClientError>
    where
        M: Into<Vec<u8>>,
    {
        Ok(self
            .send_command(SignHmacCommand {
                key_id,
                data: msg.into(),
            })?
            .into())
    }

    /// Compute an RSASSA-PKCS#1v1.5 signature of the SHA-256 hash of the given data.
    ///
    /// **WARNING**: This method has not been tested and is not confirmed to actually work! Use at your
    /// own risk!
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Sign_Pkcs1.html>
    #[cfg(feature = "rsa")]
    pub fn sign_rsa_pkcs1v15_sha256(
        &mut self,
        key_id: object::Id,
        data: &[u8],
    ) -> Result<rsa::pkcs1::Signature, ClientError> {
        Ok(self
            .send_command(SignPkcs1Command {
                key_id,
                digest: Sha256::digest(data).as_slice().into(),
            })?
            .into())
    }

    /// Compute an RSASSA-PSS signature of the SHA-256 hash of the given data with the given key ID.
    ///
    /// **WARNING**: This method has not been tested and is not confirmed to actually work! Use at your
    /// own risk!
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Sign_Pss.html>
    #[cfg(feature = "rsa")]
    pub fn sign_rsa_pss_sha256(
        &mut self,
        key_id: object::Id,
        data: &[u8],
    ) -> Result<rsa::pss::Signature, ClientError> {
        ensure!(
            data.len() > rsa::pss::MAX_MESSAGE_SIZE,
            ProtocolError,
            "message too large to be signed (max: {})",
            rsa::pss::MAX_MESSAGE_SIZE
        );

        let mut hasher = Sha256::default();

        let mut length = [0u8; 2];
        BigEndian::write_u16(&mut length, data.len() as u16);
        hasher.input(&length);
        hasher.input(data);
        let digest = hasher.result();

        Ok(self
            .send_command(SignPssCommand {
                key_id,
                mgf1_hash_alg: rsa::mgf::Algorithm::SHA256,
                salt_len: digest.as_slice().len() as u16,
                digest: digest.as_slice().into(),
            })?
            .into())
    }

    /// Decrypt data which was encrypted (using AES-CCM) under a wrap key.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Unwrap_Data.html>
    pub fn unwrap_data<M>(
        &mut self,
        wrap_key_id: object::Id,
        wrap_message: M,
    ) -> Result<Vec<u8>, ClientError>
    where
        M: Into<wrap::Message>,
    {
        let wrap::Message { nonce, ciphertext } = wrap_message.into();

        Ok(self
            .send_command(UnwrapDataCommand {
                wrap_key_id,
                nonce,
                ciphertext,
            })?
            .0)
    }

    /// Verify an HMAC tag of the given data with the given key ID.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Verify_Hmac.html>
    pub fn verify_hmac<M, T>(
        &mut self,
        key_id: object::Id,
        msg: M,
        tag: T,
    ) -> Result<(), ClientError>
    where
        M: Into<Vec<u8>>,
        T: Into<hmac::Tag>,
    {
        let result = self.send_command(VerifyHmacCommand {
            key_id,
            tag: tag.into(),
            data: msg.into(),
        })?;

        if result.0 == 1 {
            Ok(())
        } else {
            Err(err!(ResponseError, "HMAC verification failure"))
        }
    }

    /// Encrypt data (with AES-CCM) using the given wrap key.
    ///
    /// <https://developers.yubico.com/YubiHSM2/Commands/Wrap_Data.html>
    pub fn wrap_data(
        &mut self,
        wrap_key_id: object::Id,
        plaintext: Vec<u8>,
    ) -> Result<wrap::Message, ClientError> {
        Ok(self
            .send_command(WrapDataCommand {
                wrap_key_id,
                plaintext,
            })?
            .0)
    }
}