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_ANDROID_KEYMASTER_UTILS_H_
18 #define SYSTEM_KEYMASTER_ANDROID_KEYMASTER_UTILS_H_
19
20 #include <stdint.h>
21 #include <string.h>
22 #include <time.h> // for time_t.
23
24 #include <keymaster/UniquePtr.h>
25
26 #include <hardware/keymaster_defs.h>
27 #include <keymaster/serializable.h>
28
29 namespace keymaster {
30
31 /**
32 * Convert the specified time value into "Java time", which is a signed 64-bit integer representing
33 * elapsed milliseconds since Jan 1, 1970.
34 */
java_time(time_t time)35 inline int64_t java_time(time_t time) {
36 // The exact meaning of a time_t value is implementation-dependent. If this code is ported to a
37 // platform that doesn't define it as "seconds since Jan 1, 1970 UTC", this function will have
38 // to be revised.
39 return static_cast<int64_t>(time) * 1000;
40 }
41
42 /*
43 * Array Manipulation functions. This set of templated inline functions provides some nice tools
44 * for operating on c-style arrays. C-style arrays actually do have a defined size associated with
45 * them, as long as they are not allowed to decay to a pointer. These template methods exploit this
46 * to allow size-based array operations without explicitly specifying the size. If passed a pointer
47 * rather than an array, they'll fail to compile.
48 */
49
50 /**
51 * Return the size in bytes of the array \p a.
52 */
array_size(const T (& a)[N])53 template <typename T, size_t N> inline size_t array_size(const T (&a)[N]) {
54 return sizeof(a);
55 }
56
57 /**
58 * Return the number of elements in array \p a.
59 */
array_length(const T (&)[N])60 template <typename T, size_t N> inline size_t array_length(const T (&)[N]) {
61 return N;
62 }
63
64 /**
65 * Duplicate the array \p a. The memory for the new array is allocated and the caller takes
66 * responsibility.
67 */
dup_array(const T * a,size_t n)68 template <typename T> inline T* dup_array(const T* a, size_t n) {
69 T* dup = new (std::nothrow) T[n];
70 if (dup)
71 for (size_t i = 0; i < n; ++i)
72 dup[i] = a[i];
73 return dup;
74 }
75
76 /**
77 * Duplicate the array \p a. The memory for the new array is allocated and the caller takes
78 * responsibility. Note that the dup is necessarily returned as a pointer, so size is lost. Call
79 * array_length() on the original array to discover the size.
80 */
dup_array(const T (& a)[N])81 template <typename T, size_t N> inline T* dup_array(const T (&a)[N]) {
82 return dup_array(a, N);
83 }
84
85 /**
86 * Duplicate the buffer \p buf. The memory for the new buffer is allocated and the caller takes
87 * responsibility.
88 */
89 uint8_t* dup_buffer(const void* buf, size_t size);
90
91 /**
92 * Copy the contents of array \p arr to \p dest.
93 */
copy_array(const T (& arr)[N],T * dest)94 template <typename T, size_t N> inline void copy_array(const T (&arr)[N], T* dest) {
95 for (size_t i = 0; i < N; ++i)
96 dest[i] = arr[i];
97 }
98
99 /**
100 * Search array \p a for value \p val, returning true if found. Note that this function is
101 * early-exit, meaning that it should not be used in contexts where timing analysis attacks could be
102 * a concern.
103 */
array_contains(const T (& a)[N],T val)104 template <typename T, size_t N> inline bool array_contains(const T (&a)[N], T val) {
105 for (size_t i = 0; i < N; ++i) {
106 if (a[i] == val) {
107 return true;
108 }
109 }
110 return false;
111 }
112
113 /**
114 * Variant of memset() that uses GCC-specific pragmas to disable optimizations, so effect is not
115 * optimized away. This is important because we often need to wipe blocks of sensitive data from
116 * memory. As an additional convenience, this implementation avoids writing to NULL pointers.
117 */
118 #ifdef __clang__
119 #define OPTNONE __attribute__((optnone))
120 #else // not __clang__
121 #define OPTNONE __attribute__((optimize("O0")))
122 #endif // not __clang__
memset_s(void * s,int c,size_t n)123 inline OPTNONE void* memset_s(void* s, int c, size_t n) {
124 if (!s)
125 return s;
126 return memset(s, c, n);
127 }
128 #undef OPTNONE
129
130 /**
131 * Variant of memcmp that has the same runtime regardless of whether the data matches (i.e. doesn't
132 * short-circuit). Not an exact equivalent to memcmp because it doesn't return <0 if p1 < p2, just
133 * 0 for match and non-zero for non-match.
134 */
135 int memcmp_s(const void* p1, const void* p2, size_t length);
136
137 /**
138 * Eraser clears buffers. Construct it with a buffer or object and the destructor will ensure that
139 * it is zeroed.
140 */
141 class Eraser {
142 public:
143 /* Not implemented. If this gets used, we want a link error. */
144 template <typename T> explicit Eraser(T* t);
145
146 template <typename T>
Eraser(T & t)147 explicit Eraser(T& t) : buf_(reinterpret_cast<uint8_t*>(&t)), size_(sizeof(t)) {}
148
Eraser(uint8_t (& arr)[N])149 template <size_t N> explicit Eraser(uint8_t (&arr)[N]) : buf_(arr), size_(N) {}
150
Eraser(void * buf,size_t size)151 Eraser(void* buf, size_t size) : buf_(static_cast<uint8_t*>(buf)), size_(size) {}
~Eraser()152 ~Eraser() { memset_s(buf_, 0, size_); }
153
154 private:
155 Eraser(const Eraser&);
156 void operator=(const Eraser&);
157
158 uint8_t* buf_;
159 size_t size_;
160 };
161
162 /**
163 * ArrayWrapper is a trivial wrapper around a C-style array that provides begin() and end()
164 * methods. This is primarily to facilitate range-based iteration on arrays. It does not copy, nor
165 * does it take ownership; it just holds pointers.
166 */
167 template <typename T> class ArrayWrapper {
168 public:
ArrayWrapper(T * array,size_t size)169 ArrayWrapper(T* array, size_t size) : begin_(array), end_(array + size) {}
170
begin()171 T* begin() { return begin_; }
end()172 T* end() { return end_; }
173
174 private:
175 T* begin_;
176 T* end_;
177 };
178
array_range(T * begin,size_t length)179 template <typename T> ArrayWrapper<T> array_range(T* begin, size_t length) {
180 return ArrayWrapper<T>(begin, length);
181 }
182
array_range(T (& a)[n])183 template <typename T, size_t n> ArrayWrapper<T> array_range(T (&a)[n]) {
184 return ArrayWrapper<T>(a, n);
185 }
186
187 /**
188 * Convert any unsigned integer from network to host order. We implement this here rather than
189 * using the functions from arpa/inet.h because the TEE doesn't have inet.h. This isn't the most
190 * efficient implementation, but the compiler should unroll the loop and tighten it up.
191 */
ntoh(T t)192 template <typename T> T ntoh(T t) {
193 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(&t);
194 T retval = 0;
195 for (size_t i = 0; i < sizeof(t); ++i) {
196 retval <<= 8;
197 retval |= byte_ptr[i];
198 }
199 return retval;
200 }
201
202 /**
203 * Convert any unsigned integer from host to network order. We implement this here rather than
204 * using the functions from arpa/inet.h because the TEE doesn't have inet.h. This isn't the most
205 * efficient implementation, but the compiler should unroll the loop and tighten it up.
206 */
hton(T t)207 template <typename T> T hton(T t) {
208 T retval;
209 uint8_t* byte_ptr = reinterpret_cast<uint8_t*>(&retval);
210 for (size_t i = sizeof(t); i > 0; --i) {
211 byte_ptr[i - 1] = t & 0xFF;
212 t >>= 8;
213 }
214 return retval;
215 }
216
217 inline
accessBlobData(const keymaster_key_blob_t * blob)218 const uint8_t* const & accessBlobData(const keymaster_key_blob_t* blob) {
219 return blob->key_material;
220 }
221 inline
accessBlobData(keymaster_key_blob_t * blob)222 const uint8_t*& accessBlobData(keymaster_key_blob_t* blob) {
223 return blob->key_material;
224 }
225 inline
accessBlobSize(const keymaster_key_blob_t * blob)226 const size_t& accessBlobSize(const keymaster_key_blob_t* blob) {
227 return blob->key_material_size;
228 }
229 inline
accessBlobSize(keymaster_key_blob_t * blob)230 size_t& accessBlobSize(keymaster_key_blob_t* blob) {
231 return blob->key_material_size;
232 }
233
234 inline
accessBlobData(const keymaster_blob_t * blob)235 const uint8_t* const & accessBlobData(const keymaster_blob_t* blob) {
236 return blob->data;
237 }
238 inline
accessBlobData(keymaster_blob_t * blob)239 const uint8_t*& accessBlobData(keymaster_blob_t* blob) {
240 return blob->data;
241 }
242 inline
accessBlobSize(const keymaster_blob_t * blob)243 const size_t & accessBlobSize(const keymaster_blob_t* blob) {
244 return blob->data_length;
245 }
246 inline
accessBlobSize(keymaster_blob_t * blob)247 size_t& accessBlobSize(keymaster_blob_t* blob) {
248 return blob->data_length;
249 }
250
251 /**
252 * TKeymasterBlob is a very simple extension of the C structs keymaster_blob_t and
253 * keymaster_key_blob_t. It manages its own memory, which makes avoiding memory leaks
254 * much easier.
255 */
256 template <typename BlobType>
257 struct TKeymasterBlob : public BlobType {
TKeymasterBlobTKeymasterBlob258 TKeymasterBlob() {
259 accessBlobData(this) = nullptr;
260 accessBlobSize(this) = 0;
261 }
262
TKeymasterBlobTKeymasterBlob263 TKeymasterBlob(const uint8_t* data, size_t size) {
264 accessBlobSize(this) = 0;
265 accessBlobData(this) = dup_buffer(data, size);
266 if (accessBlobData(this))
267 accessBlobSize(this) = size;
268 }
269
TKeymasterBlobTKeymasterBlob270 explicit TKeymasterBlob(size_t size) {
271 accessBlobSize(this) = 0;
272 accessBlobData(this) = new (std::nothrow) uint8_t[size];
273 if (accessBlobData(this))
274 accessBlobSize(this) = size;
275 }
276
TKeymasterBlobTKeymasterBlob277 explicit TKeymasterBlob(const BlobType& blob) {
278 accessBlobSize(this) = 0;
279 accessBlobData(this) = dup_buffer(accessBlobData(&blob), accessBlobSize(&blob));
280 if (accessBlobData(this))
281 accessBlobSize(this) = accessBlobSize(&blob);
282 }
283
284 template<size_t N>
TKeymasterBlobTKeymasterBlob285 explicit TKeymasterBlob(const uint8_t (&data)[N]) {
286 accessBlobSize(this) = 0;
287 accessBlobData(this) = dup_buffer(data, N);
288 if (accessBlobData(this))
289 accessBlobSize(this) = N;
290 }
291
TKeymasterBlobTKeymasterBlob292 TKeymasterBlob(const TKeymasterBlob& blob) {
293 accessBlobSize(this) = 0;
294 accessBlobData(this) = dup_buffer(accessBlobData(&blob), accessBlobSize(&blob));
295 if (accessBlobData(this))
296 accessBlobSize(this) = accessBlobSize(&blob);
297 }
298
TKeymasterBlobTKeymasterBlob299 TKeymasterBlob(TKeymasterBlob&& rhs) {
300 accessBlobSize(this) = accessBlobSize(&rhs);
301 accessBlobData(this) = accessBlobData(&rhs);
302 accessBlobSize(&rhs) = 0;
303 accessBlobData(&rhs) = nullptr;
304 }
305
306 TKeymasterBlob& operator=(const TKeymasterBlob& blob) {
307 if (this != &blob) {
308 Clear();
309 accessBlobData(this) = dup_buffer(accessBlobData(&blob), accessBlobSize(&blob));
310 accessBlobSize(this) = accessBlobSize(&blob);
311 }
312 return *this;
313 }
314
315 TKeymasterBlob& operator=(TKeymasterBlob&& rhs) {
316 if (this != &rhs) {
317 Clear();
318 accessBlobSize(this) = accessBlobSize(&rhs);
319 accessBlobData(this) = accessBlobData(&rhs);
320 accessBlobSize(&rhs) = 0;
321 accessBlobData(&rhs) = nullptr;
322 }
323 return *this;
324 }
325
~TKeymasterBlobTKeymasterBlob326 ~TKeymasterBlob() { Clear(); }
327
beginTKeymasterBlob328 const uint8_t* begin() const { return accessBlobData(this); }
endTKeymasterBlob329 const uint8_t* end() const { return accessBlobData(this) + accessBlobSize(this); }
330
ClearTKeymasterBlob331 void Clear() {
332 memset_s(const_cast<uint8_t*>(accessBlobData(this)), 0, accessBlobSize(this));
333 delete[] accessBlobData(this);
334 accessBlobData(this) = nullptr;
335 accessBlobSize(this) = 0;
336 }
337
ResetTKeymasterBlob338 const uint8_t* Reset(size_t new_size) {
339 Clear();
340 accessBlobData(this) = new (std::nothrow) uint8_t[new_size];
341 if (accessBlobData(this))
342 accessBlobSize(this) = new_size;
343 return accessBlobData(this);
344 }
345
346 // The key_material in keymaster_key_blob_t is const, which is the right thing in most
347 // circumstances, but occasionally we do need to write into it. This method exposes a non-const
348 // version of the pointer. Use sparingly.
writable_dataTKeymasterBlob349 uint8_t* writable_data() { return const_cast<uint8_t*>(accessBlobData(this)); }
350
releaseTKeymasterBlob351 BlobType release() {
352 BlobType tmp = {accessBlobData(this), accessBlobSize(this)};
353 accessBlobData(this) = nullptr;
354 accessBlobSize(this) = 0;
355 return tmp;
356 }
357
SerializedSizeTKeymasterBlob358 size_t SerializedSize() const { return sizeof(uint32_t) + accessBlobSize(this); }
SerializeTKeymasterBlob359 uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const {
360 return append_size_and_data_to_buf(buf, end, accessBlobData(this), accessBlobSize(this));
361 }
362
DeserializeTKeymasterBlob363 bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) {
364 Clear();
365 UniquePtr<uint8_t[]> tmp;
366 if (!copy_size_and_data_from_buf(buf_ptr, end, &accessBlobSize(this), &tmp)) {
367 accessBlobData(this) = nullptr;
368 accessBlobSize(this) = 0;
369 return false;
370 }
371 accessBlobData(this) = tmp.release();
372 return true;
373 }
374 };
375
376 typedef TKeymasterBlob<keymaster_blob_t> KeymasterBlob;
377 typedef TKeymasterBlob<keymaster_key_blob_t> KeymasterKeyBlob;
378
379 struct Characteristics_Delete {
operatorCharacteristics_Delete380 void operator()(keymaster_key_characteristics_t* p) {
381 keymaster_free_characteristics(p);
382 free(p);
383 }
384 };
385
386 struct Malloc_Delete {
operatorMalloc_Delete387 void operator()(void* p) { free(p); }
388 };
389
390 struct CertificateChainDelete {
operatorCertificateChainDelete391 void operator()(keymaster_cert_chain_t* p) {
392 if (!p)
393 return;
394 for (size_t i = 0; i < p->entry_count; ++i)
395 delete[] p->entries[i].data;
396 delete[] p->entries;
397 delete p;
398 }
399 };
400
401 typedef UniquePtr<keymaster_cert_chain_t, CertificateChainDelete> CertChainPtr;
402
403 keymaster_error_t EcKeySizeToCurve(uint32_t key_size_bits, keymaster_ec_curve_t* curve);
404 keymaster_error_t EcCurveToKeySize(keymaster_ec_curve_t curve, uint32_t* key_size_bits);
405
406 template<typename T> struct remove_reference {typedef T type;};
407 template<typename T> struct remove_reference<T&> {typedef T type;};
408 template<typename T> struct remove_reference<T&&> {typedef T type;};
409 template<typename T>
410 using remove_reference_t = typename remove_reference<T>::type;
411 template<typename T>
412 remove_reference_t<T>&& move(T&& x) {
413 return static_cast<remove_reference_t<T>&&>(x);
414 }
415
416 template<typename T>
417 constexpr T&& forward(remove_reference_t<T>& x) {
418 return static_cast<T&&>(x);
419 }
420 template<typename T>
421 constexpr T&& forward(remove_reference_t<T>&& x) {
422 return static_cast<T&&>(x);
423 }
424
425 template <class F> class final_action {
426 public:
427 explicit final_action(F f) : f_(move(f)) {}
428 ~final_action() { f_(); }
429
430 private:
431 F f_;
432 };
433
434 template <class F> inline final_action<F> finally(const F& f) {
435 return final_action<F>(f);
436 }
437
438 } // namespace keymaster
439
440 #endif // SYSTEM_KEYMASTER_ANDROID_KEYMASTER_UTILS_H_
441