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