kryoptic-lib 1.5.1

A PKCS #11 software token written in Rust
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
// Copyright 2023-2026 Simo Sorce
// See LICENSE.txt file for terms

use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::LazyLock;

use crate::attribute::{AttrType, Attribute};
use crate::error::{Error, Result};
use crate::mechanism::{Mechanism, Mechanisms};
use crate::misc::{sizeof, void_ptr};
use crate::pkcs11::*;

#[cfg(feature = "nssdb")]
use crate::pkcs11::vendor::nss::*;

use super::certs::{TrustObject, X509Factory};
use super::key::{
    GenericSecretKeyFactory, GenericSecretKeyMechanism, KeyFactory,
    PubKeyFactory, SecretKeyFactory,
};
use super::Object;

#[cfg(feature = "nssdb")]
use super::certs::NSSTrustObject;

use bitflags::bitflags;

/// Helper to map errors to CKR_TEMPLATE_INCOMPLETE
pub fn incomplete(e: Error) -> Error {
    if e.attr_not_found() {
        Error::ck_rv(CKR_TEMPLATE_INCOMPLETE)
    } else {
        e
    }
}

bitflags! {
    /// A bitflag set that defines attribute properties and behaviors
    #[derive(Debug, Clone, Copy)]
    pub struct OAFlags: u32 {
        /// the attribute is ignored and not copied from a template
        const Ignored              = 0x00000001;

        /// The attribute is sensitive and will not be returned by a call
        /// unless specifically authorized (like a key secret value)
        const Sensitive            = 0x00000002;

        /// The attribute has a default value that can be set when it is
        /// required on object creation but not provided by a template
        const Defval               = 0x00000004;

        /// The attribute must be provided in the template on object
        /// creation or the operation will fail
        const RequiredOnCreate     = 0x00000008;

        /// The attribute must be provided in the template on key
        /// generation or the operation will fail
        const RequiredOnGenerate   = 0x00000010;

        /// The attribute is always required or the operation will fail,
        /// however combined with Defval it means it will be generated
        /// automatically when absent from the template and will not
        /// cause the operation to fail
        const AlwaysRequired       = 0x00000020;

        /// The attribute can only be set in a template for create
        /// (import) operations, if set for any other operation (copy,
        /// generate, wrap, derive) it will cause a failure
        const SettableOnlyOnCreate = 0x00000080;

        /// This attribute can never be set in a template, if set the
        /// operation will fail (they are only ever set by internal
        /// functions)
        const NeverSettable        = 0x00000100;

        /// The attribute cannot be changed once set (enforced from
        /// changing via C_SetAttibuteValue or via C_CopyObject
        const Unchangeable         = 0x00000400;

        /// The attribute can only be changed from `True` to `False`
        const ChangeToFalse        = 0x00000C00;

        /// The attribute can only be changed from `False` to `True`
        const ChangeToTrue         = 0x00001400;

        /// The attribute can be changed only during a Copy Operation
        const ChangeOnCopy         = 0x00002400;

        /// The attribute is ephemeral and should not be stored on
        /// permanent storage
        const Ephemeral            = 0x00008000;
    }
}

/// This object is used to list the attribute that are allowed for specific
/// object types and also can define what if any their default value is and
/// what operation can be done on this object by applications.

#[derive(Debug, Clone)]
pub struct ObjectAttr {
    /// The reference attribute, may contain a default value
    pub(crate) attribute: Attribute,
    /// The flags that define the attribute properties for the object
    /// class this ObjectAttr is applied to
    flags: OAFlags,
}

impl ObjectAttr {
    /// Creates a new ObjectAttr
    pub fn new(a: Attribute, f: OAFlags) -> ObjectAttr {
        ObjectAttr {
            attribute: a,
            flags: f,
        }
    }

    /// Gets the internal attribute id (type)
    pub fn get_type(&self) -> CK_ULONG {
        self.attribute.get_type()
    }

    /// Check if a specific flag is present on the ObjectAttr
    pub fn is(&self, val: OAFlags) -> bool {
        if val.is_empty() {
            return false;
        }
        self.flags.contains(val)
    }

    /// Checks if the ObjectAttr has a default value
    pub fn has_default(&self) -> bool {
        self.flags.contains(OAFlags::Defval)
    }
}

/// Helper to quickly instantiate an ObjectAttr element
#[macro_export]
macro_rules! attr_element {
    ($id:expr; $flags:expr; $from_type:expr; val $defval:expr) => {
        $crate::object::factory::ObjectAttr::new(
            $from_type($id, $defval),
            $flags,
        )
    };
}
pub use attr_element;

/// This trait must be implemented by any mechanisms that defines an
/// object type, like key object of a specific type. The ObjectFactory
/// is responsible for defining what are the allowed attributes for the
/// specific object/key type, and any special behaviors for object
/// creation/import or other manipulation.

#[derive(Debug)]
pub struct ObjectFactoryData {
    /// Class of the object created by the factory
    class: CK_OBJECT_CLASS,
    /// List of valid attributes and their properties for this factory
    attributes: Vec<ObjectAttr>,
    /// List of attributes considered sensitive
    sensitive: Vec<CK_ATTRIBUTE_TYPE>,
    /// List of attributes that should never be saved in token storage
    ephemeral: Vec<CK_ATTRIBUTE_TYPE>,
    /// Flag that indicates this factory data has been finalized and cannot
    /// be further modified
    finalized: bool,
}

impl ObjectFactoryData {
    pub fn new(class: CK_OBJECT_CLASS) -> ObjectFactoryData {
        ObjectFactoryData {
            class: class,
            attributes: Vec::new(),
            sensitive: Vec::new(),
            ephemeral: Vec::new(),
            finalized: false,
        }
    }

    /// Return the class of the object created by the factory
    pub fn get_class(&self) -> CK_OBJECT_CLASS {
        self.class
    }

    /// Returns a reference to factory valid attributes and their properties
    pub fn get_attributes(&self) -> &Vec<ObjectAttr> {
        &self.attributes
    }

    /// Returns a mutable reference to factory valid attributes and
    /// their properties
    ///
    /// This method panics if it is called after the factory data has
    /// been finalized.
    pub fn get_attributes_mut(&mut self) -> &mut Vec<ObjectAttr> {
        if self.finalized {
            panic!("Attempted modification after finalization");
        }
        &mut self.attributes
    }

    /// Get the list of sensitive attributes
    ///
    /// Empty until the factory data is finalized
    pub fn get_sensitive(&self) -> &Vec<CK_ATTRIBUTE_TYPE> {
        &self.sensitive
    }

    /// Get the list of ephemeral attributes
    ///
    /// Empty until the factory data is finalized
    pub fn get_ephemeral(&self) -> &Vec<CK_ATTRIBUTE_TYPE> {
        &self.ephemeral
    }

    /// Finalizes the factory data and populates the sensitive
    /// and ephemeral lists
    pub fn finalize(&mut self) {
        for a in &self.attributes {
            if a.is(OAFlags::Sensitive) {
                self.sensitive.push(a.get_type());
            }
            if a.is(OAFlags::Ephemeral) {
                self.ephemeral.push(a.get_type());
            }
        }
        self.finalized = true;
    }
}

/// This is a common trait to define common methods all objects implement
/// and common attributes all objects posses
///
/// [Common attributes](https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/pkcs11-spec-v3.1-os.html#_Toc111203203)
/// and
/// [Storage Objects](https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/pkcs11-spec-v3.1-os.html#_Toc111203216)
/// (Version 3.1)

pub trait ObjectFactory: Debug + Send + Sync {
    /// Creates a new object from the template
    ///
    /// Mechanism implementations that can create objects must implement
    /// this function, the default implementation returns a general error.
    fn create(&self, _template: &[CK_ATTRIBUTE]) -> Result<Object> {
        return Err(CKR_GENERAL_ERROR)?;
    }

    /// Creates a new Built-In object from the template
    ///
    /// Implemented only by mechanism that provide built-in objects
    fn builtin_create(&self, _id: CK_ULONG) -> Result<Object> {
        return Err(CKR_GENERAL_ERROR)?;
    }

    /// Creates a copy of the object
    ///
    /// Uses the default_copy() internal method by default.
    fn copy(&self, obj: &Object, template: &[CK_ATTRIBUTE]) -> Result<Object> {
        self.default_copy(obj, template)
    }

    /// Adds the common object attributes defined in spec
    fn add_common_object_attrs(&mut self) {
        let attrs = self.get_data_mut().get_attributes_mut();
        attrs.push(attr_element!(
            CKA_CLASS; OAFlags::RequiredOnCreate;
            Attribute::from_ulong; val 0));
        attrs.push(attr_element!(
            CKA_UNIQUE_ID; OAFlags::NeverSettable | OAFlags::Unchangeable;
            Attribute::from_string; val String::new()));
    }

    /// Adds the storage object attributes defined in the spec
    fn add_common_storage_attrs(&mut self, private: bool) {
        self.add_common_object_attrs();
        let attrs = self.get_data_mut().get_attributes_mut();
        attrs.push(attr_element!(
            CKA_TOKEN; OAFlags::Defval | OAFlags::ChangeOnCopy;
            Attribute::from_bool; val false));
        attrs.push(attr_element!(
            CKA_PRIVATE; OAFlags::Defval | OAFlags::ChangeOnCopy;
            Attribute::from_bool; val private));
        attrs.push(attr_element!(
            CKA_MODIFIABLE; OAFlags::Defval | OAFlags::ChangeOnCopy;
            Attribute::from_bool; val true));
        attrs.push(attr_element!(
            CKA_LABEL; OAFlags::empty(); Attribute::from_string;
            val String::new()));
        attrs.push(attr_element!(
            CKA_COPYABLE; OAFlags::Defval | OAFlags::ChangeToFalse;
            Attribute::from_bool; val true));
        attrs.push(attr_element!(
            CKA_DESTROYABLE; OAFlags::Defval; Attribute::from_bool;
            val true));
    }

    /// This function implements the creation/import/derivation of any object
    /// type and encodes common rules to interpret the list of ObjectAttr for
    /// the object.
    ///
    /// The unacceptable_flags argument defines what attributes can't be
    /// manipulated by the calling function when their flag matches one of
    /// the flags specified in this argument.
    ///
    /// The required_flags argument defines what attributes must be provided
    /// in the template by the calling function when their flag matches one of
    /// the flags specified in this argument.
    ///
    /// This function should not be overridden by specialized factories.

    fn internal_object_create(
        &self,
        template: &[CK_ATTRIBUTE],
        unacceptable_flags: OAFlags,
        required_flags: OAFlags,
    ) -> Result<Object> {
        let data = self.get_data();
        let mut obj = Object::new(data.get_class());

        let attributes = data.get_attributes();
        for ck_attr in template {
            match attributes.iter().find(|a| a.get_type() == ck_attr.type_) {
                Some(attr) => {
                    if attr.is(unacceptable_flags) {
                        return Err(CKR_ATTRIBUTE_TYPE_INVALID)?;
                    }
                    /* duplicate? */
                    match obj.get_attr(ck_attr.type_) {
                        Some(oa) => {
                            if oa.get_type() != CKA_CLASS
                                || (oa.get_type() == CKA_CLASS
                                    && ck_attr.to_ulong()? != oa.to_ulong()?)
                            {
                                return Err(CKR_TEMPLATE_INCONSISTENT)?;
                            }
                        }
                        None => (),
                    }
                    if !attr.is(OAFlags::Ignored) {
                        obj.attributes.push(Attribute::from_ck_attr(ck_attr)?);
                    }
                }
                None => {
                    return Err(CKR_ATTRIBUTE_VALUE_INVALID)?;
                }
            }
        }
        for attr in attributes {
            match obj.get_attr(attr.get_type()) {
                Some(_) => (),
                None => {
                    if attr.has_default() {
                        obj.attributes.push(attr.attribute.clone());
                    } else if attr.is(required_flags)
                        || attr.is(OAFlags::AlwaysRequired)
                    {
                        return Err(CKR_TEMPLATE_INCOMPLETE)?;
                    }
                }
            }
        }
        Ok(obj)
    }

    fn default_object_create(
        &self,
        template: &[CK_ATTRIBUTE],
    ) -> Result<Object> {
        let mut obj = self.internal_object_create(
            template,
            OAFlags::NeverSettable,
            OAFlags::RequiredOnCreate,
        )?;
        obj.generate_unique();
        Ok(obj)
    }

    /// Adds an attribute to an object using the default value defined
    /// for the attribute type in the factory
    #[allow(dead_code)]
    fn set_attribute_default(
        &self,
        attr: CK_ATTRIBUTE_TYPE,
        obj: &mut Object,
    ) -> Result<()> {
        let attributes = self.get_data().get_attributes();
        match attributes.iter().find(|a| a.get_type() == attr) {
            Some(defattr) => {
                if defattr.has_default() {
                    obj.set_attr(defattr.attribute.clone())?;
                }
            }
            None => (),
        }
        Ok(())
    }

    /// Helper to copy objects that respects the semantics and restrictions
    /// defined in the PKCS#11 specification.
    fn default_copy(
        &self,
        origin: &Object,
        template: &[CK_ATTRIBUTE],
    ) -> Result<Object> {
        let attributes = self.get_data().get_attributes();
        for ck_attr in template {
            match attributes.iter().find(|a| a.get_type() == ck_attr.type_) {
                Some(attr) => {
                    if attr.is(OAFlags::Unchangeable) {
                        if attr
                            .is(OAFlags::ChangeToFalse | OAFlags::ChangeToTrue)
                        {
                            let val =
                                match origin.get_attr_as_bool(ck_attr.type_) {
                                    Ok(a) => a,
                                    Err(_) => false,
                                };
                            if val && !attr.is(OAFlags::ChangeToFalse) {
                                return Err(CKR_ATTRIBUTE_READ_ONLY)?;
                            }
                            if !val && !attr.is(OAFlags::ChangeToTrue) {
                                return Err(CKR_ATTRIBUTE_READ_ONLY)?;
                            }
                        }
                        if !attr.is(OAFlags::ChangeOnCopy) {
                            return Err(CKR_ATTRIBUTE_READ_ONLY)?;
                        }
                    }
                }
                None => return Err(CKR_TEMPLATE_INCONSISTENT)?,
            }
        }

        let mut obj = origin.blind_copy()?;
        for ck_attr in template {
            let _ = obj.set_attr(Attribute::from_ck_attr(ck_attr)?)?;
        }

        /* special attrs handling */
        match obj.get_attr_as_bool(CKA_EXTRACTABLE) {
            Ok(e) => {
                let mut val = !e;
                match obj.get_attr_as_bool(CKA_NEVER_EXTRACTABLE) {
                    Ok(ne) => val &= ne,
                    Err(_) => match origin.get_attr_as_bool(CKA_EXTRACTABLE) {
                        Ok(oe) => val &= !oe,
                        Err(_) => val = false,
                    },
                }
                let _ = obj.set_attr(Attribute::from_bool(
                    CKA_NEVER_EXTRACTABLE,
                    val,
                ))?;
            }
            Err(_) => (),
        }
        match obj.get_attr_as_bool(CKA_SENSITIVE) {
            Ok(b) => {
                let mut val = b;
                match origin.get_attr_as_bool(CKA_ALWAYS_SENSITIVE) {
                    Ok(ob) => val &= ob,
                    Err(_) => match origin.get_attr_as_bool(CKA_SENSITIVE) {
                        Ok(os) => val &= os,
                        Err(_) => val = false,
                    },
                }
                let _ = obj.set_attr(Attribute::from_bool(
                    CKA_ALWAYS_SENSITIVE,
                    val,
                ))?;
            }
            Err(_) => (),
        }

        Ok(obj)
    }

    /// Helper function to check if the attributes specified in the template
    /// can be modified according to the PKCS#11 rules for the specific object.
    /// If an attribute provided in the template cannot be changed an
    /// appropriate error is returned.
    fn check_set_attributes(&self, template: &[CK_ATTRIBUTE]) -> Result<()> {
        let attrs = self.get_data().get_attributes();
        for ck_attr in template {
            match attrs.iter().find(|a| a.get_type() == ck_attr.type_) {
                None => return Err(CKR_ATTRIBUTE_TYPE_INVALID)?,
                Some(attr) => {
                    if attr.is(OAFlags::NeverSettable) {
                        return Err(CKR_ACTION_PROHIBITED)?;
                    }
                    if attr.is(OAFlags::Unchangeable) {
                        if attr.attribute.get_attrtype() == AttrType::BoolType {
                            let val = ck_attr.to_bool()?;
                            if val {
                                if !attr.is(OAFlags::ChangeToTrue) {
                                    return Err(CKR_ATTRIBUTE_READ_ONLY)?;
                                }
                            } else {
                                if !attr.is(OAFlags::ChangeToFalse) {
                                    return Err(CKR_ATTRIBUTE_READ_ONLY)?;
                                }
                            }
                        } else {
                            return Err(CKR_ATTRIBUTE_READ_ONLY)?;
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Helper function to change the attributes of an existing object.
    /// This helpers performs the necessary checks required to permit
    /// object modification in accordance to the PKCS#11 specification
    /// and returns an error if any check fails before any attribute is
    /// modified.
    fn set_object_attributes(
        &self,
        obj: &mut Object,
        template: &[CK_ATTRIBUTE],
    ) -> Result<()> {
        if !obj.is_modifiable() {
            return Err(CKR_ACTION_PROHIBITED)?;
        }

        /* first check that all attributes can be changed */
        self.check_set_attributes(template)?;

        /* if checks clear out, apply changes */
        for ck_attr in template {
            obj.set_attr(Attribute::from_ck_attr(ck_attr)?)?;
        }

        Ok(())
    }

    /// Helper method to get a reference to the ObjectFactoryData
    fn get_data(&self) -> &ObjectFactoryData;

    /// Helper method to get a mutable reference to the ObjectFactoryData
    fn get_data_mut(&mut self) -> &mut ObjectFactoryData;

    /// Helper to access traits that are only available for objects of
    /// type Key, other types of objects should not implement this method.
    fn as_key_factory(&self) -> Result<&dyn KeyFactory> {
        Err(CKR_GENERAL_ERROR)?
    }

    /// Helper to access traits that are only available for objects of
    /// class CKO_PUPBLIC_KEY. Other key type factories should not

    /// implement this method.
    fn as_public_key_factory(&self) -> Result<&dyn PubKeyFactory> {
        Err(CKR_GENERAL_ERROR)?
    }

    /// Helper to access traits that are only available for objects of
    /// class CKO_SECRET_KEY. Other key type factories should not
    /// implement this method.
    fn as_secret_key_factory(&self) -> Result<&dyn SecretKeyFactory> {
        Err(CKR_GENERAL_ERROR)?
    }
}

/// This is a specialized factory for objects of class CKO_DATA
///
/// [Data Objects](https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/pkcs11-spec-v3.1-os.html#_Toc111203218)
/// (Version 3.1)

#[derive(Debug)]
struct DataFactory {
    data: ObjectFactoryData,
}

impl DataFactory {
    /// Initializes a new DataFactory object
    fn new() -> DataFactory {
        let mut factory: DataFactory = DataFactory {
            data: ObjectFactoryData::new(CKO_DATA),
        };

        factory.add_common_storage_attrs(false);

        let attributes = factory.data.get_attributes_mut();

        attributes.push(attr_element!(
            CKA_APPLICATION; OAFlags::Defval; Attribute::from_string;
            val String::new()));
        attributes.push(attr_element!(
            CKA_OBJECT_ID; OAFlags::empty(); Attribute::from_bytes;
            val Vec::new()));
        attributes.push(attr_element!(
            CKA_VALUE; OAFlags::Defval; Attribute::from_bytes;
            val Vec::new()));

        factory.data.finalize();

        factory
    }
}

impl ObjectFactory for DataFactory {
    /// Creates a new Data Object from the template
    ///
    /// Uses `key_create()`
    fn create(&self, template: &[CK_ATTRIBUTE]) -> Result<Object> {
        self.default_object_create(template)
    }

    fn copy(
        &self,
        origin: &Object,
        template: &[CK_ATTRIBUTE],
    ) -> Result<Object> {
        self.default_copy(origin, template)
    }

    fn get_data(&self) -> &ObjectFactoryData {
        &self.data
    }

    fn get_data_mut(&mut self) -> &mut ObjectFactoryData {
        &mut self.data
    }
}

/// This is a specialized factory for objects of class CKO_PROFILE

#[cfg(feature = "profiles")]
#[derive(Debug)]
pub struct ProfileFactory {
    data: ObjectFactoryData,
}

#[cfg(feature = "profiles")]
impl ProfileFactory {
    /// Initializes a new ProfileFactory object
    fn new() -> ProfileFactory {
        let mut factory: ProfileFactory = ProfileFactory {
            data: ObjectFactoryData::new(CKO_PROFILE),
        };

        factory.add_common_object_attrs();

        let attributes = factory.data.get_attributes_mut();

        attributes.push(attr_element!(
            CKA_PROFILE_ID; OAFlags::RequiredOnCreate; Attribute::from_ulong;
            val CK_UNAVAILABLE_INFORMATION));

        factory.data.finalize();

        factory
    }
}

#[cfg(feature = "profiles")]
impl ObjectFactory for ProfileFactory {
    fn create(&self, _template: &[CK_ATTRIBUTE]) -> Result<Object> {
        Err(CKR_TEMPLATE_INCOMPLETE)?
    }

    fn builtin_create(&self, profile_id: CK_PROFILE_ID) -> Result<Object> {
        let mut pid = profile_id;
        let attr = CK_ATTRIBUTE {
            type_: CKA_PROFILE_ID,
            pValue: void_ptr!(&mut pid),
            ulValueLen: sizeof!(CK_PROFILE_ID),
        };
        let mut obj = self.internal_object_create(
            &[attr],
            OAFlags::empty(),
            OAFlags::RequiredOnCreate,
        )?;
        obj.generate_stable_unique(profile_id);
        Ok(obj)
    }

    fn copy(
        &self,
        _origin: &Object,
        _template: &[CK_ATTRIBUTE],
    ) -> Result<Object> {
        Err(CKR_ACTION_PROHIBITED)?
    }

    fn get_data(&self) -> &ObjectFactoryData {
        &self.data
    }

    fn get_data_mut(&mut self) -> &mut ObjectFactoryData {
        &mut self.data
    }
}

/// This is a specialized factory for objects of class CKO_MECHANISM

#[derive(Debug)]
pub struct MechanismFactory {
    data: ObjectFactoryData,
}

impl MechanismFactory {
    /// Initializes a new MechanismFactory object
    fn new() -> MechanismFactory {
        let mut factory: MechanismFactory = MechanismFactory {
            data: ObjectFactoryData::new(CKO_MECHANISM),
        };

        factory.add_common_object_attrs();

        let attributes = factory.data.get_attributes_mut();

        attributes.push(attr_element!(
            CKA_MECHANISM_TYPE; OAFlags::RequiredOnCreate; Attribute::from_ulong;
            val CK_UNAVAILABLE_INFORMATION));

        factory.data.finalize();

        factory
    }
}

impl ObjectFactory for MechanismFactory {
    fn create(&self, _template: &[CK_ATTRIBUTE]) -> Result<Object> {
        Err(CKR_TEMPLATE_INCOMPLETE)?
    }

    fn builtin_create(
        &self,
        mechanism_type: CK_MECHANISM_TYPE,
    ) -> Result<Object> {
        let mut mt = mechanism_type;
        let attr = CK_ATTRIBUTE {
            type_: CKA_MECHANISM_TYPE,
            pValue: void_ptr!(&mut mt),
            ulValueLen: sizeof!(CK_MECHANISM_TYPE),
        };
        let mut obj = self.internal_object_create(
            &[attr],
            OAFlags::empty(),
            OAFlags::RequiredOnCreate,
        )?;
        obj.generate_stable_unique(mechanism_type);
        Ok(obj)
    }

    fn copy(
        &self,
        _origin: &Object,
        _template: &[CK_ATTRIBUTE],
    ) -> Result<Object> {
        Err(CKR_ACTION_PROHIBITED)?
    }

    fn get_data(&self) -> &ObjectFactoryData {
        &self.data
    }

    fn get_data_mut(&mut self) -> &mut ObjectFactoryData {
        &mut self.data
    }
}

/// Structure that defines an Object Type
///
/// Holds a Class type and the underlying type.
///
/// For object classes that have no underlying type `type_` is set to 0.
#[derive(Debug, Eq, Hash, PartialEq)]
pub struct ObjectType {
    class: CK_ULONG,
    type_: CK_ULONG,
}

impl ObjectType {
    /// Initializes and returns a new ObjectType
    pub fn new(class: CK_ULONG, type_: CK_ULONG) -> ObjectType {
        ObjectType {
            class: class,
            type_: type_,
        }
    }
}

/// This structure holds all of the registered object factories for
/// the implemented object types.
///
/// It provides accessors to find and retrieve object factories, and
/// to add object factories at token initialization.

#[derive(Debug)]
pub struct ObjectFactories {
    factories: HashMap<ObjectType, &'static Box<dyn ObjectFactory>>,
}

impl ObjectFactories {
    /// Crates a new Object Factory registry
    pub fn new() -> ObjectFactories {
        ObjectFactories {
            factories: HashMap::new(),
        }
    }

    /// Adds a factory to the registry
    pub fn add_factory(
        &mut self,
        otype: ObjectType,
        templ: &'static Box<dyn ObjectFactory>,
    ) {
        self.factories.insert(otype, templ);
    }

    /// Retrieves a factory for the specified object type from the registry
    pub fn get_factory(
        &self,
        otype: ObjectType,
    ) -> Result<&Box<dyn ObjectFactory>> {
        match self.factories.get(&otype) {
            Some(b) => Ok(b),
            None => Err(CKR_ATTRIBUTE_VALUE_INVALID)?,
        }
    }

    /// Crates a new object using the appropriate factory based on the
    /// data in the template.
    pub fn create(&self, template: &[CK_ATTRIBUTE]) -> Result<Object> {
        let class = match template.iter().find(|a| a.type_ == CKA_CLASS) {
            Some(c) => c.to_ulong()?,
            None => return Err(CKR_TEMPLATE_INCOMPLETE)?,
        };
        let type_ = match class {
            CKO_DATA | CKO_TRUST | CKO_PROFILE | CKO_MECHANISM => 0,
            #[cfg(feature = "nssdb")]
            CKO_NSS_TRUST => 0,
            CKO_CERTIFICATE => {
                match template.iter().find(|a| a.type_ == CKA_CERTIFICATE_TYPE)
                {
                    Some(c) => c.to_ulong()?,
                    None => return Err(CKR_TEMPLATE_INCOMPLETE)?,
                }
            }
            CKO_PUBLIC_KEY => {
                match template.iter().find(|a| a.type_ == CKA_KEY_TYPE) {
                    Some(k) => k.to_ulong()?,
                    None => return Err(CKR_TEMPLATE_INCOMPLETE)?,
                }
            }
            CKO_PRIVATE_KEY => {
                match template.iter().find(|a| a.type_ == CKA_KEY_TYPE) {
                    Some(k) => k.to_ulong()?,
                    None => return Err(CKR_TEMPLATE_INCOMPLETE)?,
                }
            }
            CKO_SECRET_KEY => {
                match template.iter().find(|a| a.type_ == CKA_KEY_TYPE) {
                    Some(k) => k.to_ulong()?,
                    None => return Err(CKR_TEMPLATE_INCOMPLETE)?,
                }
            }
            /* TODO:
             * CKO_HW_FEATURE, CKO_DOMAIN_PARAMETERS, CKO_OTP_KEY,
             * CKO_VENDOR_DEFINED.
             * Builtin objects cannot be created so they always return
             * this error. Unsupported objects alaso return the same.
             */
            _ => return Err(CKR_TEMPLATE_INCONSISTENT)?,
        };
        self.get_factory(ObjectType::new(class, type_))?
            .create(template)
    }

    /// Returns the object factory associated to the specified object
    pub fn get_object_factory(
        &self,
        obj: &Object,
    ) -> Result<&Box<dyn ObjectFactory>> {
        let class = obj.get_attr_as_ulong(CKA_CLASS)?;
        let type_ = match class {
            CKO_CERTIFICATE => obj.get_attr_as_ulong(CKA_CERTIFICATE_TYPE)?,
            CKO_PUBLIC_KEY | CKO_PRIVATE_KEY | CKO_SECRET_KEY => {
                obj.get_attr_as_ulong(CKA_KEY_TYPE)?
            }
            _ => 0,
        };
        self.get_factory(ObjectType::new(class, type_))
    }

    /// Helper to check if the template includes invalid or sensitive
    /// attributes related to the specified object. This is done by
    /// sourcing the object factory related to the provide object and
    /// then using object type specific attribute lists.
    pub fn check_sensitive(
        &self,
        obj: &Object,
        template: &[CK_ATTRIBUTE],
    ) -> Result<()> {
        let objtype_attrs =
            self.get_object_factory(obj)?.get_data().get_attributes();
        for ck_attr in template {
            match objtype_attrs.iter().find(|a| a.get_type() == ck_attr.type_) {
                None => return Err(CKR_ATTRIBUTE_TYPE_INVALID)?,
                Some(attr) => {
                    if attr.is(OAFlags::Sensitive) {
                        return Err(CKR_ATTRIBUTE_SENSITIVE)?;
                    }
                }
            }
        }
        Ok(())
    }

    /// Fills the template with the specified attributes from the provided
    /// object. Ensures the attribute are valid and can be returned. If the
    /// object is not extractable and a sensitive attribute is requested an
    /// appropriate error is returned and the template is not filled, except
    /// for setting the ulValueLen of the forbidden attributes appropriately
    /// as required by the PKCS#11 specification.
    pub fn get_object_attributes(
        &self,
        obj: &Object,
        template: &mut [CK_ATTRIBUTE],
    ) -> Result<()> {
        let sensitive = obj.is_sensitive() || !obj.is_extractable();
        let mut result = CKR_OK;

        let factory_attrs =
            self.get_object_factory(obj)?.get_data().get_attributes();
        let obj_attrs = obj.get_attributes();

        for ck_attr in template.iter_mut() {
            let valid: bool;

            /* check if this attribute is valid/allowed */
            match factory_attrs.iter().find(|a| a.get_type() == ck_attr.type_) {
                Some(fa) => {
                    if sensitive && fa.is(OAFlags::Sensitive) {
                        ck_attr.ulValueLen = CK_UNAVAILABLE_INFORMATION;
                        if result == CKR_OK {
                            result = CKR_ATTRIBUTE_SENSITIVE;
                        }
                        valid = false;
                    } else {
                        valid = true;
                    }
                }
                None => {
                    /* This attribute is not valid for given object type */
                    ck_attr.ulValueLen = CK_UNAVAILABLE_INFORMATION;
                    if result == CKR_OK {
                        result = CKR_ATTRIBUTE_TYPE_INVALID;
                    }
                    valid = false;
                }
            }

            if !valid {
                /* The attribute value can't be returned, it is either sesntive
                 * or the attribute type is invalid for this object class.
                 * Continue to the next one skipping the code that copies the
                 * values in the template */
                continue;
            }

            match obj_attrs.iter().find(|a| a.get_type() == ck_attr.type_) {
                Some(oa) => {
                    let attr_val = oa.get_value();
                    let attr_len = CK_ULONG::try_from(attr_val.len())?;
                    if ck_attr.pValue.is_null() {
                        ck_attr.ulValueLen = attr_len;
                    } else if ck_attr.ulValueLen == CK_UNAVAILABLE_INFORMATION {
                        if result == CKR_OK {
                            result = CKR_TEMPLATE_INCONSISTENT;
                        }
                    } else {
                        if ck_attr.ulValueLen < attr_len {
                            ck_attr.ulValueLen = CK_UNAVAILABLE_INFORMATION;
                            if result == CKR_OK {
                                result = CKR_BUFFER_TOO_SMALL;
                            }
                        } else {
                            ck_attr.ulValueLen = attr_len;
                            unsafe {
                                std::ptr::copy_nonoverlapping(
                                    attr_val.as_ptr(),
                                    ck_attr.pValue as *mut _,
                                    attr_val.len(),
                                );
                            }
                        }
                    }
                }
                None => {
                    /* This attribute is not available on given object */
                    ck_attr.ulValueLen = CK_UNAVAILABLE_INFORMATION;
                    if result == CKR_OK {
                        result = CKR_ATTRIBUTE_TYPE_INVALID;
                    }
                }
            }
        }
        if result == CKR_OK {
            Ok(())
        } else {
            Err(result)?
        }
    }

    /// Uses an object type specific copy operation to return a copy
    /// of the provided object
    pub fn copy(
        &self,
        obj: &Object,
        template: &[CK_ATTRIBUTE],
    ) -> Result<Object> {
        if !obj.is_copyable() {
            return Err(CKR_ACTION_PROHIBITED)?;
        }
        self.get_object_factory(obj)?.copy(obj, template)
    }

    /// Finds the appropriate object factory to operate on the object
    /// defined by the template
    pub fn get_obj_factory_from_key_template(
        &self,
        template: &[CK_ATTRIBUTE],
    ) -> Result<&Box<dyn ObjectFactory>> {
        let class = match template.iter().position(|x| x.type_ == CKA_CLASS) {
            Some(idx) => template[idx].to_ulong()?,
            None => return Err(CKR_TEMPLATE_INCONSISTENT)?,
        };
        let key_type =
            match template.iter().position(|x| x.type_ == CKA_KEY_TYPE) {
                Some(idx) => template[idx].to_ulong()?,
                None => return Err(CKR_TEMPLATE_INCONSISTENT)?,
            };
        self.get_factory(ObjectType::new(class, key_type))
    }

    /// Finds the appropriate object factory for the derivation template
    /// provided and attempts a key derivation operation.
    pub fn derive_key_from_template(
        &self,
        key: &Object,
        template: &[CK_ATTRIBUTE],
    ) -> Result<Object> {
        let factory = self.get_obj_factory_from_key_template(template)?;
        factory.as_key_factory()?.key_derive(template, key)
    }
}

/// The static Data Object factory
static DATA_OBJECT_FACTORY: LazyLock<Box<dyn ObjectFactory>> =
    LazyLock::new(|| Box::new(DataFactory::new()));

/// The static X509 Certificate factory
static X509_CERT_FACTORY: LazyLock<Box<dyn ObjectFactory>> =
    LazyLock::new(|| Box::new(X509Factory::new()));

/// The static Trust Object factory
static TRUST_OBJECT_FACTORY: LazyLock<Box<dyn ObjectFactory>> =
    LazyLock::new(|| Box::new(TrustObject::new()));

/// The static NSS Trust Object factory
#[cfg(feature = "nssdb")]
static NSS_TRUST_OBJECT_FACTORY: LazyLock<Box<dyn ObjectFactory>> =
    LazyLock::new(|| Box::new(NSSTrustObject::new()));

/// The static Profile Object factory
#[cfg(feature = "profiles")]
static PROFILE_FACTORY: LazyLock<Box<dyn ObjectFactory>> =
    LazyLock::new(|| Box::new(ProfileFactory::new()));

/// The static Mechanism Object factory
static MECHANISM_FACTORY: LazyLock<Box<dyn ObjectFactory>> =
    LazyLock::new(|| Box::new(MechanismFactory::new()));

/// Object that holds Mechanisms for Generic Secrets
static GENERIC_SECRET: LazyLock<Box<dyn Mechanism>> = LazyLock::new(|| {
    Box::new(GenericSecretKeyMechanism::new(CKK_GENERIC_SECRET))
});

/// The static Generic Secret factory
pub(crate) static GENERIC_SECRET_FACTORY: LazyLock<Box<dyn ObjectFactory>> =
    LazyLock::new(|| Box::new(GenericSecretKeyFactory::new()));

/// Registers mechanisms and key factories for Data Objects, X509
/// Certificates and Generic Secret Keys
pub fn register(mechs: &mut Mechanisms, ot: &mut ObjectFactories) {
    mechs.add_mechanism(CKM_GENERIC_SECRET_KEY_GEN, &(*GENERIC_SECRET));

    ot.add_factory(ObjectType::new(CKO_DATA, 0), &(*DATA_OBJECT_FACTORY));
    ot.add_factory(
        ObjectType::new(CKO_CERTIFICATE, CKC_X_509),
        &(*X509_CERT_FACTORY),
    );
    ot.add_factory(
        ObjectType::new(CKO_SECRET_KEY, CKK_GENERIC_SECRET),
        &(*GENERIC_SECRET_FACTORY),
    );
    ot.add_factory(ObjectType::new(CKO_TRUST, 0), &(*TRUST_OBJECT_FACTORY));
    #[cfg(feature = "nssdb")]
    ot.add_factory(
        ObjectType::new(CKO_NSS_TRUST, 0),
        &(*NSS_TRUST_OBJECT_FACTORY),
    );
    #[cfg(feature = "profiles")]
    ot.add_factory(ObjectType::new(CKO_PROFILE, 0), &(*PROFILE_FACTORY));
    ot.add_factory(ObjectType::new(CKO_MECHANISM, 0), &(*MECHANISM_FACTORY));
}