1 //
2 // Copyright (C) 2020 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 #include "tpm_serialize.h"
17
18 #include <cstring>
19
20 #include <android-base/logging.h>
21 #include "tss2/tss2_mu.h"
22 #include "tss2/tss2_rc.h"
23
24 template<typename T>
25 int MarshalFn = 0; // Break code without an explicit specialization.
26
27 template<typename T>
28 int UnmarshalFn = 0; // Break code without an explicit specialization.
29
30 template<>
31 auto MarshalFn<TPM2B_PRIVATE> = Tss2_MU_TPM2B_PRIVATE_Marshal;
32
33 template<>
34 auto UnmarshalFn<TPM2B_PRIVATE> = Tss2_MU_TPM2B_PRIVATE_Unmarshal;
35
36 template<>
37 auto MarshalFn<TPM2B_PUBLIC> = Tss2_MU_TPM2B_PUBLIC_Marshal;
38
39 template<>
40 auto UnmarshalFn<TPM2B_PUBLIC> = Tss2_MU_TPM2B_PUBLIC_Unmarshal;
41
42 template<typename T>
TpmSerializable(T * instance)43 TpmSerializable<T>::TpmSerializable(T* instance) : instance_(instance) {}
44
45 template<typename T>
SerializedSize() const46 size_t TpmSerializable<T>::SerializedSize() const {
47 std::size_t size = 0;
48 auto rc = MarshalFn<T>(instance_, nullptr, sizeof(T), &size);
49 if (rc != TPM2_RC_SUCCESS) {
50 LOG(ERROR) << "tss2 marshalling failed: " << Tss2_RC_Decode(rc)
51 << "(" << rc << ")";
52 return -1;
53 }
54 return size;
55 }
56
57 template<typename T>
Serialize(uint8_t * buf,const uint8_t * end) const58 uint8_t* TpmSerializable<T>::Serialize(uint8_t* buf, const uint8_t* end) const {
59 std::size_t offset = 0;
60 auto rc = MarshalFn<T>(instance_, buf, end - buf, &offset);
61 if (rc != TPM2_RC_SUCCESS) {
62 LOG(ERROR) << "tss2 marshalling failed: " << Tss2_RC_Decode(rc)
63 << "(" << rc << ")";
64 return buf;
65 }
66 return buf + offset;
67 }
68
69 template<typename T>
Deserialize(const uint8_t ** buf_ptr,const uint8_t * end)70 bool TpmSerializable<T>::Deserialize(
71 const uint8_t** buf_ptr, const uint8_t* end) {
72 std::size_t offset = 0;
73 auto rc = UnmarshalFn<T>(*buf_ptr, end - *buf_ptr, &offset, instance_);
74 if (rc != TPM2_RC_SUCCESS) {
75 LOG(ERROR) << "tss2 unmarshalling failed: " << Tss2_RC_Decode(rc)
76 << "(" << rc << ")";
77 return false;
78 }
79 *buf_ptr += offset;
80 return true;
81 }
82
83 template class TpmSerializable<TPM2B_PRIVATE>;
84 template class TpmSerializable<TPM2B_PUBLIC>;
85