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
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use anyhow::Result;
use cryptoki::session::Session;

use crate::util::attribute::{AttrData, AttributeError, AttributeMap, AttributeType, ObjectClass};
use crate::util::helper;

#[derive(Clone, Debug, Default)]
pub struct ElementaryFile {
    pub name: String,
    pub application: Option<String>,
    pub private: bool,
}

impl ElementaryFile {
    pub fn new(name: String) -> Self {
        Self {
            name,
            ..Default::default()
        }
    }

    pub fn application(mut self, app: String) -> Self {
        self.application = Some(app);
        self
    }

    pub fn private(mut self, private: bool) -> Self {
        self.private = private;
        self
    }

    pub fn find(session: &Session, search: AttributeMap) -> Result<Vec<Self>> {
        let mut search = search;
        search.insert(
            AttributeType::Class,
            AttrData::ObjectClass(ObjectClass::Data),
        );
        let search = search.to_vec()?;
        let attr = [
            AttributeType::Label,
            AttributeType::Application,
            AttributeType::Private,
        ];
        let attr = attr
            .iter()
            .map(|&a| Ok(a.try_into()?))
            .collect::<Result<Vec<cryptoki::object::AttributeType>>>()?;

        let mut result = Vec::new();
        for object in session.find_objects(&search)? {
            let data = session.get_attributes(object, &attr)?;
            let data = AttributeMap::from(data.as_slice());
            result.push(Self {
                name: data
                    .get(&AttributeType::Label)
                    .map(|x| x.try_string())
                    .transpose()?
                    .unwrap_or_else(|| String::from("<unnamed>")),
                application: data
                    .get(&AttributeType::Application)
                    .map(|x| x.try_string())
                    .transpose()?,
                private: data
                    .get(&AttributeType::Private)
                    .map(|x| x.try_into())
                    .transpose()?
                    .unwrap_or(false),
            });
        }
        Ok(result)
    }

    pub fn list(session: &Session) -> Result<Vec<Self>> {
        Self::find(session, AttributeMap::default())
    }

    pub fn exists(self, session: &Session) -> Result<bool> {
        let mut attr = AttributeMap::default();
        attr.insert(
            AttributeType::Class,
            AttrData::ObjectClass(ObjectClass::Data),
        );
        attr.insert(AttributeType::Label, AttrData::Str(self.name.clone()));
        if let Some(app) = &self.application {
            attr.insert(AttributeType::Application, AttrData::Str(app.clone()));
        }
        let attr = attr.to_vec()?;
        let objects = session.find_objects(&attr)?;
        Ok(!objects.is_empty())
    }

    pub fn read(self, session: &Session) -> Result<Vec<u8>> {
        let mut attr = AttributeMap::default();
        attr.insert(
            AttributeType::Class,
            AttrData::ObjectClass(ObjectClass::Data),
        );
        attr.insert(AttributeType::Label, AttrData::Str(self.name.clone()));
        if let Some(app) = &self.application {
            attr.insert(AttributeType::Application, AttrData::Str(app.clone()));
        }
        let attr = attr.to_vec()?;

        let object = helper::find_one_object(session, &attr)?;
        let data = AttributeMap::from_object(session, object)?;
        let value = data
            .get(&AttributeType::Value)
            .ok_or(AttributeError::AttributeNotFound(AttributeType::Value))?;
        let value = Vec::<u8>::try_from(value)?;
        Ok(value)
    }

    pub fn write(self, session: &Session, data: &[u8]) -> Result<()> {
        let mut attr = AttributeMap::default();
        attr.insert(
            AttributeType::Class,
            AttrData::ObjectClass(ObjectClass::Data),
        );
        attr.insert(AttributeType::Label, AttrData::Str(self.name.clone()));
        if let Some(application) = &self.application {
            // Is this a bug in opensc-pkcs11 or in the Nitrokey?
            // It seems the application string needs a nul terminator.
            let mut val = application.clone();
            val.push(0 as char);
            attr.insert(AttributeType::Application, AttrData::Str(val));
        }
        attr.insert(AttributeType::Token, AttrData::from(true));
        attr.insert(AttributeType::Private, AttrData::from(self.private));
        attr.insert(AttributeType::Value, AttrData::from(data));
        let attr = attr.to_vec()?;
        session.create_object(&attr)?;
        Ok(())
    }
}