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
// Copyright 2018 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use types::*;

use failure::Error;
use yubihsm_sys::{self, yh_algorithm, yh_capabilities, yh_object_descriptor, yh_object_type,
                  yh_session};

use std::cell::Cell;
use std::ffi::{CStr, CString};
use std::ops::Deref;
use std::os::raw::c_char;
use std::ptr;
use std::sync::Arc;
use std::sync::atomic::{AtomicPtr, Ordering};

macro_rules! generate_key {
    ($name:ident, $yh_func:ident) => (
        pub fn $name(
            &self,
            key_id: u16,
            label: &str,
            domains: &[Domain],
            capabilities: &[Capability],
            algorithm: Algorithm
        ) -> Result<(), Error> {
            let mut key_id_ptr = key_id;
            let c_label = CString::new(label)?;
            let lib_domains = DomainParam::from(domains);
            let lib_caps = yh_capabilities::from(capabilities);

            unsafe {
                match ReturnCode::from(yubihsm_sys::$yh_func(
                    self.this.load(Ordering::Relaxed),
                    &mut key_id_ptr,
                    c_label.as_ptr(),
                    lib_domains.0,
                    &lib_caps,
                    algorithm.into(),
                )) {
                    ReturnCode::Success => Ok(()),
                    e => Err(format_err!("$name failed: {}", e)),
                }
            }
        }
    )
}

// In order to implement `Drop` correctly here, we need to move the `AtomicPtr<yh_session>` into
// its own type. This lets us avoid relying on `Arc::strong_count()`. According to the Rust docs on
// `Arc::strong_count()`:
//      This method by itself is safe, but using it correctly requires extra care. Another thread
//      can change the strong count at any time, including potentially between calling this method
//      and acting on the result.
// So, we need to run the session-teardown functions when the Arc drops its contents, instead of
// trying to reimplement part of Arc's `Drop`.
#[derive(Debug)]
struct SessionPtr(AtomicPtr<yh_session>);

impl Drop for SessionPtr {
    fn drop(&mut self) {
        unsafe {
            yubihsm_sys::yh_util_close_session(self.0.load(Ordering::Relaxed));
            yubihsm_sys::yh_destroy_session(&mut self.0.load(Ordering::Relaxed));
        }
    }
}

impl Deref for SessionPtr {
    type Target = AtomicPtr<yh_session>;

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

/// Represents a `Session` with the HSM.
///
/// The `Session` is where the bulk of the YubiHSM's functionality is found. A `Session` is needed
/// to perform any cryptographic or device administration tasks.
#[derive(Clone, Debug)]
pub struct Session {
    this: Arc<SessionPtr>,
    _unsync_marker: Cell<()>,
}

impl Session {
    pub(crate) fn new(this: *mut yh_session) -> Session {
        Session {
            this: Arc::new(SessionPtr(AtomicPtr::new(this))),
            _unsync_marker: Cell::new(()),
        }
    }

    /// Reset the device to factory settings and reboot.
    ///
    /// Note that since the device reboots when this function is called, this function is far more
    /// likely to return a `ReturnCode::NetError` upon success, since it will vanish out from
    /// underneath the connector. However, it is left to library consumers to decide whether or not
    /// this is an acceptable result.
    pub fn reset(self) -> Result<(), Error> {
        match ReturnCode::from(unsafe {
            yubihsm_sys::yh_util_reset(self.this.load(Ordering::Relaxed))
        }) {
            ReturnCode::Success => Ok(()),
            rc => Err(rc.into()),
        }
    }

    pub fn list_objects(&self) -> ListObjectsQuery {
        ListObjectsQuery::new(&self)
    }

    fn list_objects_query(
        &self,
        id: u16,
        object_type: yh_object_type,
        domains: DomainParam,
        capabilities: yh_capabilities,
        algorithm: yh_algorithm,
        label: *const c_char,
        limit: usize,
    ) -> Result<Vec<ObjectInfo>, Error> {
        let mut objects: Vec<yh_object_descriptor> = Vec::with_capacity(limit);
        let mut n_objects = objects.capacity();

        let rc = unsafe {
            ReturnCode::from(yubihsm_sys::yh_util_list_objects(
                self.this.load(Ordering::Relaxed),
                id,
                object_type,
                domains.0,
                &capabilities,
                algorithm,
                label,
                objects.as_mut_ptr(),
                &mut n_objects,
            ))
        };

        if rc != ReturnCode::Success {
            bail!("yh_util_list_objects failed: {}", rc);
        }

        unsafe { objects.set_len(n_objects) };
        objects.shrink_to_fit();

        objects
            .into_iter()
            .map(ObjectInfo::try_from_yh_object_descriptor)
            .collect::<Result<Vec<_>, Error>>()
    }

    pub fn get_object_info(&self, id: u16, object_type: ObjectType) -> Result<ObjectInfo, Error> {
        let mut object = yh_object_descriptor {
            capabilities: yh_capabilities {
                capabilities: [0; 8],
            },
            id: 0,
            len: 0,
            domains: 0,
            type_: 0,
            algorithm: 0,
            sequence: 0,
            origin: 0,
            label: [0; 41],
            delegated_capabilities: yh_capabilities {
                capabilities: [0; 8],
            },
        };

        let rc = unsafe {
            ReturnCode::from(yubihsm_sys::yh_util_get_object_info(
                self.this.load(Ordering::Relaxed),
                id,
                object_type.into(),
                &mut object,
            ))
        };

        if rc != ReturnCode::Success {
            bail!("yh_util_get_object_info failed: {}", rc);
        }

        ObjectInfo::try_from_yh_object_descriptor(object)
    }

    pub fn delete_object(&self, obj_id: u16, obj_type: ObjectType) -> Result<(), Error> {
        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_delete_object(
                self.this.load(Ordering::Relaxed),
                obj_id,
                obj_type.into(),
            )) {
                ReturnCode::Success => Ok(()),
                e => bail!("util_delete_object failed: {}", e),
            }
        }
    }

    pub fn get_random(&self, len: usize) -> Result<Vec<u8>, Error> {
        let mut out: Vec<u8> = Vec::with_capacity(len);
        let mut out_size: usize = len;

        unsafe {
            let ret = ReturnCode::from(yubihsm_sys::yh_util_get_random(
                self.this.load(Ordering::Relaxed),
                len,
                out.as_mut_ptr(),
                &mut out_size,
            ));

            if ret != ReturnCode::Success {
                bail!("yh_util_get_random failed: {}", ret);
            }

            if out_size != len {
                bail!("data sizes didn't match");
            }

            out.set_len(out_size);
        }

        Ok(out)
    }

    pub fn sign_ecdsa<T: AsRef<[u8]>>(&self, key_id: u16, data: T) -> Result<Vec<u8>, Error> {
        // The libyubihsm documentation makes no mention of how large this buffer should be, and
        // there don't appear to be any constants related to signature size, so this is just a
        // rough guess.
        let mut out_size: usize = 512;
        let mut out: Vec<u8> = Vec::with_capacity(out_size);

        let data_slice = data.as_ref();

        unsafe {
            let ret = ReturnCode::from(yubihsm_sys::yh_util_sign_ecdsa(
                self.this.load(Ordering::Relaxed),
                key_id,
                data_slice.as_ptr(),
                data_slice.len(),
                out.as_mut_ptr(),
                &mut out_size,
            ));

            if ret != ReturnCode::Success {
                bail!("couldn't sign_ecdsa: {}", ret);
            }

            out.set_len(out_size);
        }

        Ok(out)
    }

    pub fn sign_eddsa<T: AsRef<[u8]>>(&self, key_id: u16, data: T) -> Result<Vec<u8>, Error> {
        // The libyubihsm documentation makes no mention of how large this buffer should be, and
        // there don't appear to be any constants related to signature size, so this is just a
        // rough guess.
        let mut out_size: usize = 512;
        let mut out: Vec<u8> = Vec::with_capacity(out_size);

        let data_slice = data.as_ref();

        unsafe {
            let ret = ReturnCode::from(yubihsm_sys::yh_util_sign_eddsa(
                self.this.load(Ordering::Relaxed),
                key_id,
                data_slice.as_ptr(),
                data_slice.len(),
                out.as_mut_ptr(),
                &mut out_size,
            ));

            if ret != ReturnCode::Success {
                bail!("couldn't sign_eddsa: {}", ret);
            }

            out.set_len(out_size);
        }

        Ok(out)
    }

    pub fn sign_pkcs1v1_5<T: AsRef<[u8]>>(
        &self,
        key_id: u16,
        hashed: bool,
        data: T,
    ) -> Result<Vec<u8>, Error> {
        // The libyubihsm documentation makes no mention of how large this buffer should be, and
        // there don't appear to be any constants related to signature size, so this is just a
        // rough guess.
        let mut out_size: usize = 512;
        let mut out: Vec<u8> = Vec::with_capacity(out_size);

        let data_slice = data.as_ref();

        unsafe {
            let ret = ReturnCode::from(yubihsm_sys::yh_util_sign_pkcs1v1_5(
                self.this.load(Ordering::Relaxed),
                key_id,
                hashed,
                data_slice.as_ptr(),
                data_slice.len(),
                out.as_mut_ptr(),
                &mut out_size,
            ));

            if ret != ReturnCode::Success {
                bail!("couldn't sign_pkcs1v1_5: {}", ret);
            }

            out.set_len(out_size);
        }

        Ok(out)
    }

    pub fn sign_pss<T: AsRef<[u8]>>(
        &self,
        key_id: u16,
        salt_len: usize,
        mgf1_algorithm: Algorithm,
        data: T,
    ) -> Result<Vec<u8>, Error> {
        // The libyubihsm documentation makes no mention of how large this buffer should be, and
        // there don't appear to be any constants related to signature size, so this is just a
        // rough guess.
        let mut out_size: usize = 512;
        let mut out: Vec<u8> = Vec::with_capacity(out_size);

        let data_slice = data.as_ref();

        unsafe {
            let ret = ReturnCode::from(yubihsm_sys::yh_util_sign_pss(
                self.this.load(Ordering::Relaxed),
                key_id,
                data_slice.as_ptr(),
                data_slice.len(),
                out.as_mut_ptr(),
                &mut out_size,
                salt_len,
                mgf1_algorithm.into(),
            ));

            if ret != ReturnCode::Success {
                bail!("couldn't sign_pss: {}", ret);
            }

            out.set_len(out_size);
        }

        Ok(out)
    }

    generate_key!(generate_key_ec, yh_util_generate_key_ec);

    generate_key!(generate_key_ed, yh_util_generate_key_ed);

    generate_key!(generate_key_hmac, yh_util_generate_key_hmac);

    generate_key!(generate_key_rsa, yh_util_generate_key_rsa);

    pub fn generate_wrapkey(
        &self,
        key_id: u16,
        label: &str,
        domains: &[Domain],
        capabilities: &[Capability],
        delegated_capabilities: &[Capability],
        algorithm: Algorithm,
    ) -> Result<(), Error> {
        let mut key_id_ptr = key_id;
        let c_label = CString::new(label)?;
        let lib_domains = DomainParam::from(domains);
        let lib_caps = yh_capabilities::from(capabilities);
        let lib_delegated_caps = yh_capabilities::from(delegated_capabilities);

        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_generate_key_wrap(
                self.this.load(Ordering::Relaxed),
                &mut key_id_ptr,
                c_label.as_ptr(),
                lib_domains.0,
                &lib_caps,
                algorithm.into(),
                &lib_delegated_caps,
            )) {
                ReturnCode::Success => Ok(()),
                e => Err(format_err!("generate_key_wrap failed: {}", e)),
            }
        }
    }

    pub fn put_key_ec<T: AsRef<[u8]>>(
        &self,
        key_id: u16,
        label: &str,
        domains: &[Domain],
        capabilities: &[Capability],
        algorithm: Algorithm,
        s: T,
    ) -> Result<(), Error> {
        let mut key_id_ptr = key_id;
        let c_label = CString::new(label)?;
        let lib_domains = DomainParam::from(domains);
        let lib_caps = yh_capabilities::from(capabilities);

        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_import_key_ec(
                self.this.load(Ordering::Relaxed),
                &mut key_id_ptr,
                c_label.as_ptr(),
                lib_domains.0,
                &lib_caps,
                algorithm.into(),
                s.as_ref().as_ptr(),
            )) {
                ReturnCode::Success => Ok(()),
                e => bail!("couldn't import_key_rsa: {}", e),
            }
        }
    }

    pub fn put_key_ed<T: AsRef<[u8]>>(
        &self,
        key_id: u16,
        label: &str,
        domains: &[Domain],
        capabilities: &[Capability],
        algorithm: Algorithm,
        k: T,
    ) -> Result<(), Error> {
        let mut key_id_ptr = key_id;
        let c_label = CString::new(label)?;
        let lib_domains = DomainParam::from(domains);
        let lib_caps = yh_capabilities::from(capabilities);

        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_import_key_ed(
                self.this.load(Ordering::Relaxed),
                &mut key_id_ptr,
                c_label.as_ptr(),
                lib_domains.0,
                &lib_caps,
                algorithm.into(),
                k.as_ref().as_ptr(),
            )) {
                ReturnCode::Success => Ok(()),
                e => bail!("couldn't import_key_rsa: {}", e),
            }
        }
    }

    pub fn put_key_hmac<T: AsRef<[u8]>>(
        &self,
        key_id: u16,
        label: &str,
        domains: &[Domain],
        capabilities: &[Capability],
        algorithm: Algorithm,
        key: T,
    ) -> Result<(), Error> {
        let mut key_id_ptr = key_id;
        let c_label = CString::new(label)?;
        let lib_domains = DomainParam::from(domains);
        let lib_caps = yh_capabilities::from(capabilities);

        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_import_key_hmac(
                self.this.load(Ordering::Relaxed),
                &mut key_id_ptr,
                c_label.as_ptr(),
                lib_domains.0,
                &lib_caps,
                algorithm.into(),
                key.as_ref().as_ptr(),
                key.as_ref().len(),
            )) {
                ReturnCode::Success => Ok(()),
                e => bail!("couldn't import_key_rsa: {}", e),
            }
        }
    }

    // TODO(csssuf): refactor put_key design to properly solve this lint?
    #[allow(too_many_arguments)]
    pub fn put_key_rsa<T: AsRef<[u8]>>(
        &self,
        key_id: u16,
        label: &str,
        domains: &[Domain],
        capabilities: &[Capability],
        algorithm: Algorithm,
        p: T,
        q: T,
    ) -> Result<(), Error> {
        let mut key_id_ptr = key_id;
        let c_label = CString::new(label)?;
        let lib_domains = DomainParam::from(domains);
        let lib_caps = yh_capabilities::from(capabilities);

        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_import_key_rsa(
                self.this.load(Ordering::Relaxed),
                &mut key_id_ptr,
                c_label.as_ptr(),
                lib_domains.0,
                &lib_caps,
                algorithm.into(),
                p.as_ref().as_ptr(),
                q.as_ref().as_ptr(),
            )) {
                ReturnCode::Success => Ok(()),
                e => bail!("couldn't import_key_rsa: {}", e),
            }
        }
    }

    // TODO(csssuf): refactor put_key design to properly solve this lint?
    #[allow(too_many_arguments)]
    pub fn put_wrapkey<T: AsRef<[u8]>>(
        &self,
        key_id: u16,
        label: &str,
        domains: &[Domain],
        capabilities: &[Capability],
        delegated_capabilities: &[Capability],
        algorithm: Algorithm,
        key: T,
    ) -> Result<(), Error> {
        let mut key_id_ptr = key_id;
        let c_label = CString::new(label)?;
        let lib_domains = DomainParam::from(domains);
        let lib_caps = yh_capabilities::from(capabilities);
        let lib_delegated_caps = yh_capabilities::from(delegated_capabilities);

        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_import_key_wrap(
                self.this.load(Ordering::Relaxed),
                &mut key_id_ptr,
                c_label.as_ptr(),
                lib_domains.0,
                &lib_caps,
                algorithm.into(),
                &lib_delegated_caps,
                key.as_ref().as_ptr(),
                key.as_ref().len(),
            )) {
                ReturnCode::Success => Ok(()),
                e => bail!("couldn't import_key_rsa: {}", e),
            }
        }
    }

    pub fn create_authkey(
        &self,
        key_id: u16,
        label: &str,
        domains: &[Domain],
        capabilities: &[Capability],
        delegated_capabilities: &[Capability],
        password: &str,
    ) -> Result<(), Error> {
        let mut key_id_ptr = key_id;
        let c_label = CString::new(label)?;
        let c_pass = CString::new(password)?;
        let c_pass_slice = c_pass.as_bytes();
        let lib_domains = DomainParam::from(domains);
        let lib_caps = yh_capabilities::from(capabilities);
        let lib_delegated_caps = yh_capabilities::from(delegated_capabilities);

        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_import_authkey(
                self.this.load(Ordering::Relaxed),
                &mut key_id_ptr,
                c_label.as_ptr(),
                lib_domains.0,
                &lib_caps,
                &lib_delegated_caps,
                c_pass_slice.as_ptr(),
                c_pass_slice.len(),
            )) {
                ReturnCode::Success => Ok(()),
                e => Err(format_err!("util_import_authkey failed: {}", e)),
            }
        }
    }

    pub fn put_opaque_object(
        &self,
        object_id: u16,
        label: &str,
        domains: &[Domain],
        capabilities: &[Capability],
        algorithm: Algorithm,
        contents: &[u8],
    ) -> Result<(), Error> {
        let mut obj_id_ptr = object_id;
        let c_label = CString::new(label)?;
        let lib_domains = DomainParam::from(domains);
        let lib_caps = yh_capabilities::from(capabilities);

        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_import_opaque(
                self.this.load(Ordering::Relaxed),
                &mut obj_id_ptr,
                c_label.as_ptr(),
                lib_domains.0,
                &lib_caps,
                algorithm.into(),
                contents.as_ptr(),
                contents.len(),
            )) {
                ReturnCode::Success => Ok(()),
                e => Err(format_err!("util_import_opaque failed: {}", e)),
            }
        }
    }

    pub fn get_pubkey(&self, key_id: u16) -> Result<PublicKey, Error> {
        // Per the Yubico documentation, the largest type of data is a public key for a 4096-bit
        // RSA key, which is 0x400 bytes long.
        // https://developers.yubico.com/YubiHSM2/Commands/Get_Pubkey.html

        let mut data: Vec<u8> = Vec::with_capacity(0x400);
        let mut data_length = data.capacity();
        let mut algorithm = 0;

        let rc = unsafe {
            ReturnCode::from(yubihsm_sys::yh_util_get_pubkey(
                self.this.load(Ordering::Relaxed),
                key_id,
                data.as_mut_ptr(),
                &mut data_length,
                &mut algorithm,
            ))
        };

        if rc != ReturnCode::Success {
            bail!("util_get_pubkey failed: {}", rc);
        }

        unsafe { data.set_len(data_length) };
        data.shrink_to_fit();

        match Algorithm::from(algorithm) {
            Algorithm::Rsa2048 | Algorithm::Rsa3072 | Algorithm::Rsa4096 => {
                Ok(PublicKey::Rsa(data))
            }
            Algorithm::EcP224
            | Algorithm::EcP256
            | Algorithm::EcP384
            | Algorithm::EcP521
            | Algorithm::EcK256
            | Algorithm::EcBp256
            | Algorithm::EcBp384
            | Algorithm::EcBp512 => {
                // Yubico documentation claims `data` contains points X and Y here, so we'll trust
                // it and split down the middle.
                let split_point = data.len() / 2;
                let point_y = data.split_off(split_point);

                Ok(PublicKey::Ecc(data, point_y))
            }
            Algorithm::EcEd25519 => Ok(PublicKey::Edc(data)),
            a => bail!("get_pubkey: unexpected algorithm type {}", a),
        }
    }

    pub fn get_logs(&self) -> Result<Log, Error> {
        let mut entries: Vec<yubihsm_sys::yh_log_entry> =
            Vec::with_capacity(yubihsm_sys::YH_MAX_LOG_ENTRIES as usize);
        let mut n_entries = entries.capacity();
        let mut unlogged_boots = 0;
        let mut unlogged_auths = 0;

        let rc = unsafe {
            ReturnCode::from(yubihsm_sys::yh_util_get_logs(
                self.this.load(Ordering::Relaxed),
                &mut unlogged_boots,
                &mut unlogged_auths,
                entries.as_mut_ptr(),
                &mut n_entries,
            ))
        };

        if rc != ReturnCode::Success {
            bail!("util_get_logs failed: {}", rc);
        }

        unsafe { entries.set_len(n_entries) };
        entries.shrink_to_fit();

        Ok(Log {
            unlogged_boots: unlogged_boots,
            unlogged_auths: unlogged_auths,
            log_entries: entries.into_iter().map(LogEntry::from).collect::<Vec<_>>(),
        })
    }

    pub fn set_log_index(&self, log_index: u16) -> Result<(), Error> {
        unsafe {
            match ReturnCode::from(yubihsm_sys::yh_util_set_log_index(
                self.this.load(Ordering::Relaxed),
                log_index,
            )) {
                ReturnCode::Success => Ok(()),
                e => bail!("util_set_log_index failed: {}", e),
            }
        }
    }

    pub fn put_option(&self, option: DeviceOption) -> Result<(), Error> {
        let mut bytes = option.to_bytes();

        let rc = unsafe {
            ReturnCode::from(yubihsm_sys::yh_util_put_option(
                self.this.load(Ordering::Relaxed),
                From::<u8>::from(option.into()),
                bytes.len(),
                bytes.as_mut_ptr(),
            ))
        };

        if rc != ReturnCode::Success {
            bail!("util_put_option failed: {}", rc);
        }

        Ok(())
    }
}

#[derive(Clone, Debug)]
pub struct ListObjectsQuery<'a> {
    session: &'a Session,
    id: Option<u16>,
    object_type: Option<ObjectType>,
    domains: Option<&'a [Domain]>,
    capabilities: Option<&'a [Capability]>,
    algorithm: Option<Algorithm>,
    label: Option<&'a str>,
    limit: Option<usize>,
}

impl<'a> ListObjectsQuery<'a> {
    fn new(session: &'a Session) -> ListObjectsQuery {
        ListObjectsQuery {
            session,
            id: None,
            object_type: None,
            domains: None,
            capabilities: None,
            algorithm: None,
            label: None,
            limit: None,
        }
    }

    pub fn id(self, id: u16) -> ListObjectsQuery<'a> {
        ListObjectsQuery {
            id: Some(id),
            ..self
        }
    }

    pub fn object_type(self, object_type: ObjectType) -> ListObjectsQuery<'a> {
        ListObjectsQuery {
            object_type: Some(object_type),
            ..self
        }
    }

    pub fn domains(self, domains: &'a [Domain]) -> ListObjectsQuery<'a> {
        ListObjectsQuery {
            domains: Some(domains),
            ..self
        }
    }

    pub fn capabilities(self, capabilities: &'a [Capability]) -> ListObjectsQuery<'a> {
        ListObjectsQuery {
            capabilities: Some(capabilities),
            ..self
        }
    }

    pub fn algorithm(self, algorithm: Algorithm) -> ListObjectsQuery<'a> {
        ListObjectsQuery {
            algorithm: Some(algorithm),
            ..self
        }
    }

    pub fn label(self, label: &'a str) -> ListObjectsQuery<'a> {
        ListObjectsQuery {
            label: Some(label),
            ..self
        }
    }

    pub fn limit(self, limit: usize) -> ListObjectsQuery<'a> {
        ListObjectsQuery {
            limit: Some(limit),
            ..self
        }
    }

    pub fn execute(self) -> Result<Vec<ObjectInfo>, Error> {
        let id = self.id.unwrap_or(0);
        let object_type: yh_object_type = self.object_type.map(|x| x.into()).unwrap_or(0);
        let domains = self.domains
            .map(DomainParam::from)
            .unwrap_or(DomainParam(0));
        let capabilities = self.capabilities
            .map(yh_capabilities::from)
            .unwrap_or(yh_capabilities::from(&[]));
        let algorithm = self.algorithm.map(yh_algorithm::from).unwrap_or(0);
        let label = self.label
            .map(|l| CStr::from_bytes_with_nul(l.as_bytes()).map(|c| c.as_ptr()))
            .unwrap_or(Ok(ptr::null()))?;
        let limit = self.limit.unwrap_or(256);

        self.session.list_objects_query(
            id,
            object_type,
            domains,
            capabilities,
            algorithm,
            label,
            limit,
        )
    }
}