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