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