blob: 09e98b134e51043be56e24d059ee78f8f2b9d0fa [file] [log] [blame]
Shawn Willden5ada7b62014-07-29 09:44:17 -06001/*
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
Shawn Willden32873522020-12-14 22:29:46 -070017#pragma once
Shawn Willden5ada7b62014-07-29 09:44:17 -060018
Shawn Willden2cb22a42021-02-19 07:50:33 -070019#include <stddef.h>
Shawn Willden5ada7b62014-07-29 09:44:17 -060020#include <stdint.h>
21#include <stdlib.h>
22#include <string.h>
23
Seth Moore27accf52022-02-14 10:30:04 -080024#include <iterator>
T.J. Mercieraed61b12022-07-26 23:20:07 +000025#include <utility>
Seth Moore27accf52022-02-14 10:30:04 -080026
Janis Danisevskisf38a0022017-04-26 14:44:46 -070027#include <keymaster/UniquePtr.h>
Seth Moore27accf52022-02-14 10:30:04 -080028#include <keymaster/logger.h>
Shawn Willden2cb22a42021-02-19 07:50:33 -070029#include <keymaster/mem.h>
Shawn Willdenf2282b32014-08-25 06:49:54 -060030
Shawn Willden5ada7b62014-07-29 09:44:17 -060031namespace keymaster {
32
33class Serializable {
34 public:
Shawn Willden172f8c92014-08-17 07:50:34 -060035 Serializable() {}
36 virtual ~Serializable() {}
37
38 /**
39 * Return the size of the serialized representation of this object.
40 */
Shawn Willden5ada7b62014-07-29 09:44:17 -060041 virtual size_t SerializedSize() const = 0;
Shawn Willden172f8c92014-08-17 07:50:34 -060042
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 */
Shawn Willden58e1a542014-08-08 21:58:29 -060048 virtual uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const = 0;
Shawn Willden5ada7b62014-07-29 09:44:17 -060049
Shawn Willden172f8c92014-08-17 07:50:34 -060050 /**
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
Shawn Willden172f8c92014-08-17 07:50:34 -060056 // Disallow copying and assignment.
Nick Bray3b12e5e2019-01-18 14:44:19 -080057 Serializable(const Serializable&) = delete;
58 Serializable& operator=(const Serializable&) = delete;
59
60 // Move only.
61 Serializable(Serializable&&) = default;
62 Serializable& operator=(Serializable&&) = default;
Shawn Willden5ada7b62014-07-29 09:44:17 -060063};
64
Shawn Willden172f8c92014-08-17 07:50:34 -060065/*
66 * Utility functions for writing Serialize() methods
67 */
68
69/**
Sami Tolvanen637dd842016-03-31 10:37:49 -070070 * 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 */
Shawn Willden32873522020-12-14 22:29:46 -070073template <typename T> inline uintptr_t __pval(const T* p) {
Sami Tolvanen637dd842016-03-31 10:37:49 -070074 return reinterpret_cast<uintptr_t>(p);
75}
76
77/**
Seth Moore27accf52022-02-14 10:30:04 -080078 * Performs an overflow-checked bounds check. Returns true iff \p buf + \p len is less than
79 * \p end.
80 */
81bool __buffer_bound_check(const uint8_t* buf, const uint8_t* end, size_t len);
82
83/**
Shawn Willden172f8c92014-08-17 07:50:34 -060084 * 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 */
Shawn Willden8d336ae2014-08-09 15:47:05 -060090uint8_t* append_to_buf(uint8_t* buf, const uint8_t* end, const void* data, size_t data_len);
91
Shawn Willden172f8c92014-08-17 07:50:34 -060092/**
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 */
98template <typename T>
99inline 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}
Shawn Willden58e1a542014-08-08 21:58:29 -0600103
Shawn Willden172f8c92014-08-17 07:50:34 -0600104/**
105 * Append a uint64_t to a buffer. Returns a pointer to the first byte after the data written.
106 */
107inline uint8_t* append_uint64_to_buf(uint8_t* buf, const uint8_t* end, uint64_t value) {
Shawn Willden8d336ae2014-08-09 15:47:05 -0600108 return append_to_buf(buf, end, &value, sizeof(value));
Shawn Willden5ada7b62014-07-29 09:44:17 -0600109}
110
Shawn Willden172f8c92014-08-17 07:50:34 -0600111/**
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 */
Shawn Willden58e1a542014-08-08 21:58:29 -0600117inline uint8_t* append_size_and_data_to_buf(uint8_t* buf, const uint8_t* end, const void* data,
118 size_t data_len) {
Shawn Willden172f8c92014-08-17 07:50:34 -0600119 buf = append_uint32_to_buf(buf, end, data_len);
Shawn Willden58e1a542014-08-08 21:58:29 -0600120 return append_to_buf(buf, end, data, data_len);
Shawn Willden5ada7b62014-07-29 09:44:17 -0600121}
122
Shawn Willden172f8c92014-08-17 07:50:34 -0600123/**
Seth Moore27accf52022-02-14 10:30:04 -0800124 * 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 */
128template <typename T>
129uint8_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/**
Shawn Willden172f8c92014-08-17 07:50:34 -0600138 * 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 */
143template <typename T>
144inline uint8_t* append_uint32_array_to_buf(uint8_t* buf, const uint8_t* end, const T* data,
145 size_t count) {
Shawn Willden0f906ec2015-06-20 09:16:30 -0600146 // Check for overflow
Sami Tolvanen637dd842016-03-31 10:37:49 -0700147 if (count >= (UINT32_MAX / sizeof(uint32_t)) ||
148 __pval(buf) + count * sizeof(uint32_t) < __pval(buf))
Shawn Willden0f906ec2015-06-20 09:16:30 -0600149 return buf;
Shawn Willden172f8c92014-08-17 07:50:34 -0600150 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;
Shawn Willden5ada7b62014-07-29 09:44:17 -0600154}
155
Shawn Willden172f8c92014-08-17 07:50:34 -0600156/*
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 */
164bool 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 */
173bool copy_size_and_data_from_buf(const uint8_t** buf_ptr, const uint8_t* end, size_t* size,
Shawn Willdenf2282b32014-08-25 06:49:54 -0600174 UniquePtr<uint8_t[]>* dest);
Shawn Willden172f8c92014-08-17 07:50:34 -0600175
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 */
180template <typename T>
181inline bool copy_uint32_from_buf(const uint8_t** buf_ptr, const uint8_t* end, T* value) {
182 uint32_t val;
Shawn Willden32873522020-12-14 22:29:46 -0700183 if (!copy_from_buf(buf_ptr, end, &val, sizeof(val))) return false;
Shawn Willden172f8c92014-08-17 07:50:34 -0600184 *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 */
192inline 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 */
202template <typename T>
Shawn Willdenf2282b32014-08-25 06:49:54 -0600203inline bool copy_uint32_array_from_buf(const uint8_t** buf_ptr, const uint8_t* end,
204 UniquePtr<T[]>* data, size_t* count) {
Shawn Willden32873522020-12-14 22:29:46 -0700205 if (!copy_uint32_from_buf(buf_ptr, end, count)) return false;
Shawn Willden0f906ec2015-06-20 09:16:30 -0600206
Sami Tolvanen637dd842016-03-31 10:37:49 -0700207 uintptr_t array_end = __pval(*buf_ptr) + *count * sizeof(uint32_t);
Shawn Willden32873522020-12-14 22:29:46 -0700208 if (*count >= UINT32_MAX / sizeof(uint32_t) || array_end < __pval(*buf_ptr) ||
209 array_end > __pval(end))
Shawn Willden0f906ec2015-06-20 09:16:30 -0600210 return false;
211
212 data->reset(new (std::nothrow) T[*count]);
Shawn Willden32873522020-12-14 22:29:46 -0700213 if (!data->get()) return false;
Shawn Willden172f8c92014-08-17 07:50:34 -0600214 for (size_t i = 0; i < *count; ++i)
Shawn Willden32873522020-12-14 22:29:46 -0700215 if (!copy_uint32_from_buf(buf_ptr, end, &(*data)[i])) return false;
Shawn Willden172f8c92014-08-17 07:50:34 -0600216 return true;
Shawn Willden5ada7b62014-07-29 09:44:17 -0600217}
218
Shawn Willden98d9b922014-08-26 08:14:10 -0600219/**
Seth Moore27accf52022-02-14 10:30:04 -0800220 * 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 */
224template <typename T>
225bool 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/**
Shawn Willden98d9b922014-08-26 08:14:10 -0600248 * A simple buffer that supports reading and writing. Manages its own memory.
249 */
250class Buffer : public Serializable {
251 public:
Janis Danisevskisd8091852017-05-10 18:56:35 -0700252 Buffer() : buffer_(nullptr), buffer_size_(0), read_position_(0), write_position_(0) {}
253 explicit Buffer(size_t size) : buffer_(nullptr) { Reinitialize(size); }
254 Buffer(const void* buf, size_t size) : buffer_(nullptr) { Reinitialize(buf, size); }
T.J. Mercieraed61b12022-07-26 23:20:07 +0000255 Buffer(Buffer&& b) { *this = std::move(b); }
Shawn Willden2cb22a42021-02-19 07:50:33 -0700256 Buffer(const Buffer&) = delete;
257
Shawn Willden11b57602021-04-08 15:21:32 -0600258 ~Buffer() { Clear(); }
259
Shawn Willden9a3792e2021-04-08 09:38:14 -0600260 Buffer& operator=(Buffer&& other) {
261 if (this == &other) return *this;
T.J. Mercieraed61b12022-07-26 23:20:07 +0000262 buffer_ = std::move(other.buffer_);
Shawn Willden2cb22a42021-02-19 07:50:33 -0700263 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;
Shawn Willden9a3792e2021-04-08 09:38:14 -0600269 return *this;
Shawn Willden2cb22a42021-02-19 07:50:33 -0700270 }
271
272 void operator=(const Buffer& other) = delete;
Shawn Willden98d9b922014-08-26 08:14:10 -0600273
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.
281 bool Reinitialize(const Buffer& buffer) {
282 return Reinitialize(buffer.peek_read(), buffer.available_read());
283 }
284
Shawn Willden0cb69422015-05-26 08:31:37 -0600285 const uint8_t* begin() const { return peek_read(); }
286 const uint8_t* end() const { return peek_read() + available_read(); }
287
Shawn Willden98d9b922014-08-26 08:14:10 -0600288 void Clear();
289
290 size_t available_write() const;
291 size_t available_read() const;
292 size_t buffer_size() const { return buffer_size_; }
Eran Messeri7f7caba2021-07-19 17:46:11 +0100293 bool valid_buffer_state() const;
Shawn Willden98d9b922014-08-26 08:14:10 -0600294
295 bool write(const uint8_t* src, size_t write_length);
Shawn Willden2865c252021-07-31 15:34:12 -0600296 template <size_t N> bool write(const uint8_t (&src)[N]) { return write(src, N); }
Shawn Willden98d9b922014-08-26 08:14:10 -0600297 bool read(uint8_t* dest, size_t read_length);
298 const uint8_t* peek_read() const { return buffer_.get() + read_position_; }
Shawn Willden98d9b922014-08-26 08:14:10 -0600299 uint8_t* peek_write() { return buffer_.get() + write_position_; }
Eran Messeri7f7caba2021-07-19 17:46:11 +0100300 bool advance_write(int distance);
Shawn Willden98d9b922014-08-26 08:14:10 -0600301 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:
Shawn Willden98d9b922014-08-26 08:14:10 -0600306 UniquePtr<uint8_t[]> buffer_;
307 size_t buffer_size_;
Shawn Willden0f906ec2015-06-20 09:16:30 -0600308 size_t read_position_;
309 size_t write_position_;
Shawn Willden98d9b922014-08-26 08:14:10 -0600310};
311
Shawn Willden5ada7b62014-07-29 09:44:17 -0600312} // namespace keymaster