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

use crate::{
    structures::Public,
    traits::{Marshall, UnMarshall},
    tss2_esys::{TPM2B_PUBLIC, TPMT_PUBLIC},
    Error, Result, WrapperErrorKind,
};
use log::error;
use std::{
    convert::{TryFrom, TryInto},
    ops::Deref,
};
use zeroize::Zeroize;

/// Public data buffer.
///
/// # Details
/// Corresponds to `TPM2B_PUBLIC`. The contents of
/// the buffer can be unmarshalled into a [Public]
/// structure.
#[derive(Debug, Clone, PartialEq, Eq, Zeroize)]
#[zeroize(drop)]
pub struct PublicBuffer(Vec<u8>);

impl PublicBuffer {
    pub const MAX_SIZE: usize = std::mem::size_of::<TPMT_PUBLIC>();

    pub fn value(&self) -> &[u8] {
        &self.0
    }
}

impl Deref for PublicBuffer {
    type Target = Vec<u8>;

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

impl TryFrom<Vec<u8>> for PublicBuffer {
    type Error = Error;

    fn try_from(bytes: Vec<u8>) -> Result<Self> {
        if bytes.len() > Self::MAX_SIZE {
            error!(
                "Error: Invalid Vec<u8> size ({} > {})",
                bytes.len(),
                Self::MAX_SIZE
            );
            return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
        }
        Ok(PublicBuffer(bytes))
    }
}

impl TryFrom<&[u8]> for PublicBuffer {
    type Error = Error;

    fn try_from(bytes: &[u8]) -> Result<Self> {
        if bytes.len() > Self::MAX_SIZE {
            error!(
                "Error: Invalid &[u8] size ({} > {})",
                bytes.len(),
                Self::MAX_SIZE
            );
            return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
        }
        Ok(PublicBuffer(bytes.to_vec()))
    }
}

impl TryFrom<TPM2B_PUBLIC> for PublicBuffer {
    type Error = Error;

    fn try_from(tss: TPM2B_PUBLIC) -> Result<Self> {
        let size = tss.size as usize;
        if size > Self::MAX_SIZE {
            error!("Error: Invalid buffer size ({} > {})", size, Self::MAX_SIZE);
            return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
        }
        let public = Public::try_from(tss.publicArea)?;
        Ok(PublicBuffer(public.marshall()?))
    }
}

impl TryFrom<PublicBuffer> for TPM2B_PUBLIC {
    type Error = Error;

    fn try_from(native: PublicBuffer) -> Result<Self> {
        let mut buffer = TPM2B_PUBLIC {
            size: native.0.len() as u16,
            ..Default::default()
        };
        let public = Public::unmarshall(&native.0)?;
        buffer.publicArea = public.into();
        Ok(buffer)
    }
}

impl TryFrom<PublicBuffer> for Public {
    type Error = Error;

    fn try_from(buf: PublicBuffer) -> Result<Self> {
        Public::unmarshall(&buf.0)
    }
}

impl TryFrom<Public> for PublicBuffer {
    type Error = Error;

    fn try_from(public: Public) -> Result<PublicBuffer> {
        Ok(PublicBuffer(public.marshall()?))
    }
}

impl Marshall for PublicBuffer {
    const BUFFER_SIZE: usize = std::mem::size_of::<TPM2B_PUBLIC>();

    /// Produce a marshalled [`TPM2B_PUBLIC`]
    fn marshall(&self) -> Result<Vec<u8>> {
        let mut buffer = vec![0; Self::BUFFER_SIZE];
        let mut offset = 0;

        let ret = Error::from_tss_rc(unsafe {
            crate::tss2_esys::Tss2_MU_TPM2B_PUBLIC_Marshal(
                &self.clone().try_into()?,
                buffer.as_mut_ptr(),
                Self::BUFFER_SIZE.try_into().map_err(|e| {
                    error!("Failed to convert size of buffer to TSS size_t type: {}", e);
                    Error::local_error(WrapperErrorKind::InvalidParam)
                })?,
                &mut offset,
            )
        });

        if !ret.is_success() {
            return Err(ret);
        }

        let checked_offset = usize::try_from(offset).map_err(|e| {
            error!("Failed to parse offset as usize: {}", e);
            Error::local_error(WrapperErrorKind::InvalidParam)
        })?;

        buffer.truncate(checked_offset);

        Ok(buffer)
    }
}

impl UnMarshall for PublicBuffer {
    /// Unmarshall the structure from [`TPM2B_PUBLIC`]
    fn unmarshall(marshalled_data: &[u8]) -> Result<Self> {
        let mut dest = TPM2B_PUBLIC::default();
        let mut offset = 0;

        let ret = Error::from_tss_rc(unsafe {
            crate::tss2_esys::Tss2_MU_TPM2B_PUBLIC_Unmarshal(
                marshalled_data.as_ptr(),
                marshalled_data.len().try_into().map_err(|e| {
                    error!("Failed to convert length of marshalled data: {}", e);
                    Error::local_error(WrapperErrorKind::InvalidParam)
                })?,
                &mut offset,
                &mut dest,
            )
        });

        if !ret.is_success() {
            return Err(ret);
        }

        PublicBuffer::try_from(dest)
    }
}