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
// Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0

use crate::{
    attributes::NvIndexAttributes,
    handles::NvIndexTpmHandle,
    interface_types::algorithm::HashingAlgorithm,
    structures::Digest,
    tss2_esys::{TPM2B_NV_PUBLIC, TPMS_NV_PUBLIC},
    Error, Result, WrapperErrorKind,
};
use log::error;
use std::convert::{TryFrom, TryInto};

/// Representation of the public parameters of a non-volatile
/// space allocation.
///
/// # Details
/// Corresponds to `TPMS_NV_PUBLIC`
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct NvPublic {
    nv_index: NvIndexTpmHandle,
    name_algorithm: HashingAlgorithm,
    attributes: NvIndexAttributes,
    authorization_policy: Digest,
    data_size: usize,
}

impl NvPublic {
    const MAX_SIZE: usize = std::mem::size_of::<TPMS_NV_PUBLIC>();

    pub fn nv_index(&self) -> NvIndexTpmHandle {
        self.nv_index
    }

    pub fn name_algorithm(&self) -> HashingAlgorithm {
        self.name_algorithm
    }

    pub fn attributes(&self) -> NvIndexAttributes {
        self.attributes
    }

    pub fn authorization_policy(&self) -> &Digest {
        &self.authorization_policy
    }

    pub fn data_size(&self) -> usize {
        self.data_size
    }

    /// Get a builder for the structure
    pub const fn builder() -> NvPublicBuilder {
        NvPublicBuilder::new()
    }
}

impl TryFrom<TPM2B_NV_PUBLIC> for NvPublic {
    type Error = Error;
    fn try_from(tss_nv_public: TPM2B_NV_PUBLIC) -> Result<NvPublic> {
        if tss_nv_public.size as usize > NvPublic::MAX_SIZE {
            error!("Encountered an invalid size of the TPMS_NV_PUBLIC");
            return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
        }
        // Parse actual data
        Ok(NvPublic {
            nv_index: tss_nv_public.nvPublic.nvIndex.try_into()?,
            name_algorithm: tss_nv_public.nvPublic.nameAlg.try_into()?,
            attributes: tss_nv_public.nvPublic.attributes.try_into()?,
            authorization_policy: tss_nv_public.nvPublic.authPolicy.try_into()?,
            data_size: tss_nv_public.nvPublic.dataSize as usize,
        })
    }
}

impl TryFrom<NvPublic> for TPM2B_NV_PUBLIC {
    type Error = Error;
    fn try_from(nv_public: NvPublic) -> Result<TPM2B_NV_PUBLIC> {
        Ok(TPM2B_NV_PUBLIC {
            // Will be ignored due to being a complex TPM2B type
            // The marshalling functionality in TSS will calculate
            // the correct value.
            size: 0,
            nvPublic: TPMS_NV_PUBLIC {
                nvIndex: nv_public.nv_index.into(),
                nameAlg: nv_public.name_algorithm.into(),
                attributes: nv_public.attributes.try_into()?,
                authPolicy: nv_public.authorization_policy.into(),
                dataSize: nv_public.data_size as u16,
            },
        })
    }
}

/// Builder for NvPublic.
///
///
#[derive(Debug, Default)]
pub struct NvPublicBuilder {
    nv_index: Option<NvIndexTpmHandle>,
    name_algorithm: Option<HashingAlgorithm>,
    attributes: Option<NvIndexAttributes>,
    authorization_policy: Option<Digest>,
    data_size: Option<usize>,
}

impl NvPublicBuilder {
    pub const fn new() -> Self {
        NvPublicBuilder {
            nv_index: None,
            name_algorithm: None,
            attributes: None,
            authorization_policy: None,
            data_size: None,
        }
    }

    pub fn with_nv_index(mut self, nv_index: NvIndexTpmHandle) -> Self {
        self.nv_index = Some(nv_index);
        self
    }

    pub fn with_index_name_algorithm(mut self, nv_index_name_algorithm: HashingAlgorithm) -> Self {
        self.name_algorithm = Some(nv_index_name_algorithm);
        self
    }

    pub fn with_index_attributes(mut self, nv_index_attributes: NvIndexAttributes) -> Self {
        self.attributes = Some(nv_index_attributes);
        self
    }

    pub fn with_index_auth_policy(mut self, nv_index_auth_policy: Digest) -> Self {
        self.authorization_policy = Some(nv_index_auth_policy);
        self
    }

    pub fn with_data_area_size(mut self, nv_index_data_area_size: usize) -> Self {
        self.data_size = Some(nv_index_data_area_size);
        self
    }

    pub fn build(self) -> Result<NvPublic> {
        // TODO: Do some clever checking of the values in
        // order to determine some defaults values when
        // some params have not been specified.
        //

        Ok(NvPublic {
            // Nv Index
            nv_index: self.nv_index.ok_or_else(|| {
                error!("No NV index was specified");
                Error::local_error(WrapperErrorKind::ParamsMissing)
            })?,
            // Hashing algorithm for the name of index
            name_algorithm: self.name_algorithm.ok_or_else(|| {
                error!("No name algorithm was specified");
                Error::local_error(WrapperErrorKind::ParamsMissing)
            })?,
            // Index attributes
            attributes: self.attributes.ok_or_else(|| {
                error!("No attributes were specified");
                Error::local_error(WrapperErrorKind::ParamsMissing)
            })?,
            // Index Auth policy
            authorization_policy: self.authorization_policy.unwrap_or_default(),
            // Size of the data area of the index
            data_size: self
                .data_size
                .ok_or_else(|| {
                    error!("No data size specified");
                    Error::local_error(WrapperErrorKind::ParamsMissing)
                })
                .and_then(|v| {
                    if v > std::u16::MAX.into() {
                        error!("data area size is too large (>{})", std::u16::MAX);
                        return Err(Error::local_error(WrapperErrorKind::InvalidParam));
                    }
                    Ok(v)
                })?,
        })
    }
}