1 /*
2 * Copyright 2014 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
17 #pragma once
18
19 #include <stddef.h>
20 #include <stdint.h>
21 #include <stdlib.h>
22 #include <string.h>
23
24 #include <keymaster/UniquePtr.h>
25 #include <keymaster/mem.h>
26
27 namespace keymaster {
28
29 class Serializable {
30 public:
Serializable()31 Serializable() {}
~Serializable()32 virtual ~Serializable() {}
33
34 /**
35 * Return the size of the serialized representation of this object.
36 */
37 virtual size_t SerializedSize() const = 0;
38
39 /**
40 * Serialize this object into the provided buffer. Returns a pointer to the byte after the last
41 * written. Will not write past \p end, which should point to \p buf + size of the buffer
42 * (i.e. one past the end of the buffer).
43 */
44 virtual uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const = 0;
45
46 /**
47 * Deserialize from the provided buffer, copying the data into newly-allocated storage. Returns
48 * true if successful, and advances *buf past the bytes read.
49 */
50 virtual bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) = 0;
51
52 // Disallow copying and assignment.
53 Serializable(const Serializable&) = delete;
54 Serializable& operator=(const Serializable&) = delete;
55
56 // Move only.
57 Serializable(Serializable&&) = default;
58 Serializable& operator=(Serializable&&) = default;
59 };
60
61 /*
62 * Utility functions for writing Serialize() methods
63 */
64
65 /**
66 * Convert a pointer into a value. This is used to make sure compiler won't optimize away pointer
67 * overflow checks. (See http://www.kb.cert.org/vuls/id/162289)
68 */
__pval(const T * p)69 template <typename T> inline uintptr_t __pval(const T* p) {
70 return reinterpret_cast<uintptr_t>(p);
71 }
72
73 /**
74 * Append a byte array to a buffer. Note that by itself this function isn't very useful, because it
75 * provides no indication in the serialized buffer of what the array size is. For writing arrays,
76 * see \p append_size_and_data_to_buf().
77 *
78 * Returns a pointer to the first byte after the data written.
79 */
80 uint8_t* append_to_buf(uint8_t* buf, const uint8_t* end, const void* data, size_t data_len);
81
82 /**
83 * Append some type of value convertible to a uint32_t to a buffer. This is primarily used for
84 * writing enumerated values, and uint32_ts.
85 *
86 * Returns a pointer to the first byte after the data written.
87 */
88 template <typename T>
append_uint32_to_buf(uint8_t * buf,const uint8_t * end,T value)89 inline uint8_t* append_uint32_to_buf(uint8_t* buf, const uint8_t* end, T value) {
90 uint32_t val = static_cast<uint32_t>(value);
91 return append_to_buf(buf, end, &val, sizeof(val));
92 }
93
94 /**
95 * Append a uint64_t to a buffer. Returns a pointer to the first byte after the data written.
96 */
append_uint64_to_buf(uint8_t * buf,const uint8_t * end,uint64_t value)97 inline uint8_t* append_uint64_to_buf(uint8_t* buf, const uint8_t* end, uint64_t value) {
98 return append_to_buf(buf, end, &value, sizeof(value));
99 }
100
101 /**
102 * Appends a byte array to a buffer, prefixing it with a 32-bit size field. Returns a pointer to
103 * the first byte after the data written.
104 *
105 * See copy_size_and_data_from_buf().
106 */
append_size_and_data_to_buf(uint8_t * buf,const uint8_t * end,const void * data,size_t data_len)107 inline uint8_t* append_size_and_data_to_buf(uint8_t* buf, const uint8_t* end, const void* data,
108 size_t data_len) {
109 buf = append_uint32_to_buf(buf, end, data_len);
110 return append_to_buf(buf, end, data, data_len);
111 }
112
113 /**
114 * Appends an array of values that are convertible to uint32_t as uint32ts to a buffer, prefixing a
115 * count so deserialization knows how many values to read.
116 *
117 * See copy_uint32_array_from_buf().
118 */
119 template <typename T>
append_uint32_array_to_buf(uint8_t * buf,const uint8_t * end,const T * data,size_t count)120 inline uint8_t* append_uint32_array_to_buf(uint8_t* buf, const uint8_t* end, const T* data,
121 size_t count) {
122 // Check for overflow
123 if (count >= (UINT32_MAX / sizeof(uint32_t)) ||
124 __pval(buf) + count * sizeof(uint32_t) < __pval(buf))
125 return buf;
126 buf = append_uint32_to_buf(buf, end, count);
127 for (size_t i = 0; i < count; ++i)
128 buf = append_uint32_to_buf(buf, end, static_cast<uint32_t>(data[i]));
129 return buf;
130 }
131
132 /*
133 * Utility functions for writing Deserialize() methods.
134 */
135
136 /**
137 * Copy \p size bytes from \p *buf_ptr into \p dest. If there are fewer than \p size bytes to read,
138 * returns false. Advances *buf_ptr to the next byte to be read.
139 */
140 bool copy_from_buf(const uint8_t** buf_ptr, const uint8_t* end, void* dest, size_t size);
141
142 /**
143 * Extracts a uint32_t size from *buf_ptr, placing it in \p *size, and then reads *size bytes from
144 * *buf_ptr, placing them in newly-allocated storage in *dest. If there aren't enough bytes in
145 * *buf_ptr, returns false. Advances \p *buf_ptr to the next byte to be read.
146 *
147 * See \p append_size_and_data_to_buf().
148 */
149 bool copy_size_and_data_from_buf(const uint8_t** buf_ptr, const uint8_t* end, size_t* size,
150 UniquePtr<uint8_t[]>* dest);
151
152 /**
153 * Copies a value convertible from uint32_t from \p *buf_ptr. Returns false if there are less than
154 * four bytes remaining in \p *buf_ptr. Advances \p *buf_ptr to the next byte to be read.
155 */
156 template <typename T>
copy_uint32_from_buf(const uint8_t ** buf_ptr,const uint8_t * end,T * value)157 inline bool copy_uint32_from_buf(const uint8_t** buf_ptr, const uint8_t* end, T* value) {
158 uint32_t val;
159 if (!copy_from_buf(buf_ptr, end, &val, sizeof(val))) return false;
160 *value = static_cast<T>(val);
161 return true;
162 }
163
164 /**
165 * Copies a uint64_t from \p *buf_ptr. Returns false if there are less than eight bytes remaining
166 * in \p *buf_ptr. Advances \p *buf_ptr to the next byte to be read.
167 */
copy_uint64_from_buf(const uint8_t ** buf_ptr,const uint8_t * end,uint64_t * value)168 inline bool copy_uint64_from_buf(const uint8_t** buf_ptr, const uint8_t* end, uint64_t* value) {
169 return copy_from_buf(buf_ptr, end, value, sizeof(*value));
170 }
171
172 /**
173 * Copies an array of values convertible to uint32_t from \p *buf_ptr, first reading a count of
174 * values to read. The count is returned in \p *count and the values returned in newly-allocated
175 * storage at *data. Returns false if there are insufficient bytes at \p *buf_ptr. Advances \p
176 * *buf_ptr to the next byte to be read.
177 */
178 template <typename T>
copy_uint32_array_from_buf(const uint8_t ** buf_ptr,const uint8_t * end,UniquePtr<T[]> * data,size_t * count)179 inline bool copy_uint32_array_from_buf(const uint8_t** buf_ptr, const uint8_t* end,
180 UniquePtr<T[]>* data, size_t* count) {
181 if (!copy_uint32_from_buf(buf_ptr, end, count)) return false;
182
183 uintptr_t array_end = __pval(*buf_ptr) + *count * sizeof(uint32_t);
184 if (*count >= UINT32_MAX / sizeof(uint32_t) || array_end < __pval(*buf_ptr) ||
185 array_end > __pval(end))
186 return false;
187
188 data->reset(new (std::nothrow) T[*count]);
189 if (!data->get()) return false;
190 for (size_t i = 0; i < *count; ++i)
191 if (!copy_uint32_from_buf(buf_ptr, end, &(*data)[i])) return false;
192 return true;
193 }
194
195 /**
196 * A simple buffer that supports reading and writing. Manages its own memory.
197 */
198 class Buffer : public Serializable {
199 public:
Buffer()200 Buffer() : buffer_(nullptr), buffer_size_(0), read_position_(0), write_position_(0) {}
Buffer(size_t size)201 explicit Buffer(size_t size) : buffer_(nullptr) { Reinitialize(size); }
Buffer(const void * buf,size_t size)202 Buffer(const void* buf, size_t size) : buffer_(nullptr) { Reinitialize(buf, size); }
Buffer(Buffer && b)203 Buffer(Buffer&& b) { *this = move(b); }
204 Buffer(const Buffer&) = delete;
205
~Buffer()206 ~Buffer() { Clear(); }
207
208 Buffer& operator=(Buffer&& other) {
209 if (this == &other) return *this;
210 buffer_ = move(other.buffer_);
211 buffer_size_ = other.buffer_size_;
212 other.buffer_size_ = 0;
213 read_position_ = other.read_position_;
214 other.read_position_ = 0;
215 write_position_ = other.write_position_;
216 other.write_position_ = 0;
217 return *this;
218 }
219
220 void operator=(const Buffer& other) = delete;
221
222 // Grow the buffer so that at least \p size bytes can be written.
223 bool reserve(size_t size);
224
225 bool Reinitialize(size_t size);
226 bool Reinitialize(const void* buf, size_t size);
227
228 // Reinitialize with a copy of the provided buffer's readable data.
Reinitialize(const Buffer & buffer)229 bool Reinitialize(const Buffer& buffer) {
230 return Reinitialize(buffer.peek_read(), buffer.available_read());
231 }
232
begin()233 const uint8_t* begin() const { return peek_read(); }
end()234 const uint8_t* end() const { return peek_read() + available_read(); }
235
236 void Clear();
237
238 size_t available_write() const;
239 size_t available_read() const;
buffer_size()240 size_t buffer_size() const { return buffer_size_; }
241
242 bool write(const uint8_t* src, size_t write_length);
243 bool read(uint8_t* dest, size_t read_length);
peek_read()244 const uint8_t* peek_read() const { return buffer_.get() + read_position_; }
advance_read(int distance)245 bool advance_read(int distance) {
246 if (static_cast<size_t>(read_position_ + distance) <= write_position_) {
247 read_position_ += distance;
248 return true;
249 }
250 return false;
251 }
peek_write()252 uint8_t* peek_write() { return buffer_.get() + write_position_; }
advance_write(int distance)253 bool advance_write(int distance) {
254 if (static_cast<size_t>(write_position_ + distance) <= buffer_size_) {
255 write_position_ += distance;
256 return true;
257 }
258 return false;
259 }
260
261 size_t SerializedSize() const;
262 uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const;
263 bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end);
264
265 private:
266 UniquePtr<uint8_t[]> buffer_;
267 size_t buffer_size_;
268 size_t read_position_;
269 size_t write_position_;
270 };
271
272 } // namespace keymaster
273