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 /**
20 * This header contains various definitions that make working with keymaster tags safer and easier.
21 *
22 * It makes use of a fair amount of template metaprogramming. The metaprogramming serves the purpose
23 * of making it impossible to make certain classes of mistakes when operating on keymaster
24 * authorizations. For example, it's an error to create a KeyParameter with tag == Tag::PURPOSE
25 * and then to assign Algorithm::RSA to algorithm element of its union. But because the user
26 * must choose the union field, there could be a mismatch which the compiler has now way to
27 * diagnose.
28 *
29 * The machinery in this header solves these problems by describing which union field corresponds
30 * to which Tag. Central to this mechanism is the template TypedTag. It has zero size and binds a
31 * numeric Tag to a type that the compiler understands. By means of the macro DECLARE_TYPED_TAG,
32 * we declare types for each of the tags defined in hardware/interfaces/keymaster/2.0/types.hal.
33 *
34 * The macro DECLARE_TYPED_TAG(name) generates a typename TAG_name_t and a zero sized instance
35 * TAG_name. Once these typed tags have been declared we define metafunctions mapping the each tag
36 * to its value c++ type and the correct union element of KeyParameter. This is done by means of
37 * the macros MAKE_TAG_*VALUE_ACCESSOR, which generates TypedTag2ValueType, a metafunction mapping
38 * a typed tag to the corresponding c++ type, and access function, accessTagValue returning a
39 * reference to the correct element of KeyParameter.
40 * E.g.:
41 * given "KeyParameter param;" then "accessTagValue(TAG_PURPOSE, param)"
42 * yields a reference to param.f.purpose
43 * If used in an assignment the compiler can now check the compatibility of the assigned value.
44 *
45 * For convenience we also provide the constructor like function Authorization().
46 * Authorization takes a typed tag and a value and checks at compile time whether the value given
47 * is suitable for the given tag. At runtime it creates a new KeyParameter initialized with the
48 * given tag and value and returns it by value.
49 *
50 * The second convenience function, authorizationValue, allows access to the KeyParameter value in
51 * a safe way. It takes a typed tag and a KeyParameter and returns a reference to the value wrapped
52 * by NullOr. NullOr has out-of-band information about whether it is save to access the wrapped
53 * reference.
54 * E.g.:
55 * auto param = Authorization(TAG_ALGORITM, Algorithm::RSA);
56 * auto value1 = authorizationValue(TAG_PURPOSE, param);
57 * auto value2 = authorizationValue(TAG_ALGORITM, param);
58 * value1.isOk() yields false, but value2.isOk() yields true, thus value2.value() is save to access.
59 */
60
61 #include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
62 #include <hardware/hw_auth_token.h>
63 #include <type_traits>
64
65 namespace keymaster::ng {
66
67 using ::android::hardware::keymaster::V3_0::Algorithm;
68 using ::android::hardware::keymaster::V3_0::BlockMode;
69 using ::android::hardware::keymaster::V3_0::Digest;
70 using ::android::hardware::keymaster::V3_0::EcCurve;
71 using ::android::hardware::keymaster::V3_0::ErrorCode;
72 using ::android::hardware::keymaster::V3_0::HardwareAuthenticatorType;
73 using ::android::hardware::keymaster::V3_0::HardwareAuthToken;
74 using ::android::hardware::keymaster::V3_0::IKeymasterDevice;
75 using ::android::hardware::keymaster::V3_0::KeyBlobUsageRequirements;
76 using ::android::hardware::keymaster::V3_0::KeyCharacteristics;
77 using ::android::hardware::keymaster::V3_0::KeyDerivationFunction;
78 using ::android::hardware::keymaster::V3_0::KeyFormat;
79 using ::android::hardware::keymaster::V3_0::KeyOrigin;
80 using ::android::hardware::keymaster::V3_0::KeyParameter;
81 using ::android::hardware::keymaster::V3_0::KeyPurpose;
82 using ::android::hardware::keymaster::V3_0::PaddingMode;
83 using ::android::hardware::keymaster::V3_0::Tag;
84 using ::android::hardware::keymaster::V3_0::TagType;
85
86 using ::android::hardware::hidl_vec;
87 using ::android::hardware::Return;
88 using ::android::hardware::Status;
89
90 // The following create the numeric values that KM_TAG_PADDING and KM_TAG_DIGEST used to have. We
91 // need these old values to be able to support old keys that use them.
92 static const int32_t KM_TAG_DIGEST_OLD = static_cast<int32_t>(TagType::ENUM) | 5;
93 static const int32_t KM_TAG_PADDING_OLD = static_cast<int32_t>(TagType::ENUM) | 7;
94
typeFromTag(Tag tag)95 constexpr TagType typeFromTag(Tag tag) {
96 return static_cast<TagType>(static_cast<uint32_t>(tag) & static_cast<uint32_t>(0xf0000000));
97 }
98
99 /**
100 * TypedTag is a templatized version of Tag, which provides compile-time checking of
101 * keymaster tag types. Instances are convertible to Tag, so they can be used wherever
102 * Tag is expected, and because they encode the tag type it's possible to create
103 * function overloads that only operate on tags with a particular type.
104 */
105 template <TagType tag_type, Tag tag> struct TypedTag {
TypedTagTypedTag106 inline TypedTag() {
107 // Ensure that it's impossible to create a TypedTag instance whose 'tag' doesn't have type
108 // 'tag_type'. Attempting to instantiate a tag with the wrong type will result in a compile
109 // error (no match for template specialization StaticAssert<false>), with no run-time cost.
110 static_assert(typeFromTag(tag) == tag_type, "mismatch between tag and tag_type");
111 }
112 // NOLINTNEXTLINE(google-explicit-constructor)
TagTypedTag113 operator Tag() const { return tag; }
114 };
115
116 template <Tag tag> struct Tag2TypedTag { typedef TypedTag<typeFromTag(tag), tag> type; };
117
118 template <Tag tag> struct Tag2String;
119
120 #define _TAGS_STRINGIFY(x) #x
121 #define TAGS_STRINGIFY(x) _TAGS_STRINGIFY(x)
122
123 #define DECLARE_TYPED_TAG(name) \
124 typedef typename Tag2TypedTag<Tag::name>::type TAG_##name##_t; \
125 extern TAG_##name##_t TAG_##name; \
126 template <> struct Tag2String<Tag::name> { \
127 static const char* value() { return "Tag::" TAGS_STRINGIFY(name); } \
128 }
129
130 DECLARE_TYPED_TAG(INVALID);
131 DECLARE_TYPED_TAG(KEY_SIZE);
132 DECLARE_TYPED_TAG(MAC_LENGTH);
133 DECLARE_TYPED_TAG(CALLER_NONCE);
134 DECLARE_TYPED_TAG(MIN_MAC_LENGTH);
135 DECLARE_TYPED_TAG(RSA_PUBLIC_EXPONENT);
136 DECLARE_TYPED_TAG(ECIES_SINGLE_HASH_MODE);
137 DECLARE_TYPED_TAG(INCLUDE_UNIQUE_ID);
138 DECLARE_TYPED_TAG(ACTIVE_DATETIME);
139 DECLARE_TYPED_TAG(ORIGINATION_EXPIRE_DATETIME);
140 DECLARE_TYPED_TAG(USAGE_EXPIRE_DATETIME);
141 DECLARE_TYPED_TAG(MIN_SECONDS_BETWEEN_OPS);
142 DECLARE_TYPED_TAG(MAX_USES_PER_BOOT);
143 DECLARE_TYPED_TAG(ALL_USERS);
144 DECLARE_TYPED_TAG(USER_ID);
145 DECLARE_TYPED_TAG(USER_SECURE_ID);
146 DECLARE_TYPED_TAG(NO_AUTH_REQUIRED);
147 DECLARE_TYPED_TAG(AUTH_TIMEOUT);
148 DECLARE_TYPED_TAG(ALLOW_WHILE_ON_BODY);
149 DECLARE_TYPED_TAG(ALL_APPLICATIONS);
150 DECLARE_TYPED_TAG(APPLICATION_ID);
151 DECLARE_TYPED_TAG(APPLICATION_DATA);
152 DECLARE_TYPED_TAG(CREATION_DATETIME);
153 DECLARE_TYPED_TAG(ROLLBACK_RESISTANT);
154 DECLARE_TYPED_TAG(ROOT_OF_TRUST);
155 DECLARE_TYPED_TAG(ASSOCIATED_DATA);
156 DECLARE_TYPED_TAG(NONCE);
157 DECLARE_TYPED_TAG(AUTH_TOKEN);
158 DECLARE_TYPED_TAG(BOOTLOADER_ONLY);
159 DECLARE_TYPED_TAG(OS_VERSION);
160 DECLARE_TYPED_TAG(OS_PATCHLEVEL);
161 DECLARE_TYPED_TAG(UNIQUE_ID);
162 DECLARE_TYPED_TAG(ATTESTATION_CHALLENGE);
163 DECLARE_TYPED_TAG(ATTESTATION_APPLICATION_ID);
164 DECLARE_TYPED_TAG(RESET_SINCE_ID_ROTATION);
165
166 DECLARE_TYPED_TAG(PURPOSE);
167 DECLARE_TYPED_TAG(ALGORITHM);
168 DECLARE_TYPED_TAG(BLOCK_MODE);
169 DECLARE_TYPED_TAG(DIGEST);
170 DECLARE_TYPED_TAG(PADDING);
171 DECLARE_TYPED_TAG(BLOB_USAGE_REQUIREMENTS);
172 DECLARE_TYPED_TAG(ORIGIN);
173 DECLARE_TYPED_TAG(USER_AUTH_TYPE);
174 DECLARE_TYPED_TAG(KDF);
175 DECLARE_TYPED_TAG(EC_CURVE);
176
177 template <typename... Elems> struct MetaList {};
178
179 using all_tags_t = MetaList<
180 TAG_INVALID_t, TAG_KEY_SIZE_t, TAG_MAC_LENGTH_t, TAG_CALLER_NONCE_t, TAG_MIN_MAC_LENGTH_t,
181 TAG_RSA_PUBLIC_EXPONENT_t, TAG_ECIES_SINGLE_HASH_MODE_t, TAG_INCLUDE_UNIQUE_ID_t,
182 TAG_ACTIVE_DATETIME_t, TAG_ORIGINATION_EXPIRE_DATETIME_t, TAG_USAGE_EXPIRE_DATETIME_t,
183 TAG_MIN_SECONDS_BETWEEN_OPS_t, TAG_MAX_USES_PER_BOOT_t, TAG_ALL_USERS_t, TAG_USER_ID_t,
184 TAG_USER_SECURE_ID_t, TAG_NO_AUTH_REQUIRED_t, TAG_AUTH_TIMEOUT_t, TAG_ALLOW_WHILE_ON_BODY_t,
185 TAG_ALL_APPLICATIONS_t, TAG_APPLICATION_ID_t, TAG_APPLICATION_DATA_t, TAG_CREATION_DATETIME_t,
186 TAG_ROLLBACK_RESISTANT_t, TAG_ROOT_OF_TRUST_t, TAG_ASSOCIATED_DATA_t, TAG_NONCE_t,
187 TAG_AUTH_TOKEN_t, TAG_BOOTLOADER_ONLY_t, TAG_OS_VERSION_t, TAG_OS_PATCHLEVEL_t, TAG_UNIQUE_ID_t,
188 TAG_ATTESTATION_CHALLENGE_t, TAG_ATTESTATION_APPLICATION_ID_t, TAG_RESET_SINCE_ID_ROTATION_t,
189 TAG_PURPOSE_t, TAG_ALGORITHM_t, TAG_BLOCK_MODE_t, TAG_DIGEST_t, TAG_PADDING_t,
190 TAG_BLOB_USAGE_REQUIREMENTS_t, TAG_ORIGIN_t, TAG_USER_AUTH_TYPE_t, TAG_KDF_t, TAG_EC_CURVE_t>;
191
192 /* implementation in keystore_utils.cpp */
193 extern const char* stringifyTag(Tag tag);
194
195 template <typename TypedTagType> struct TypedTag2ValueType;
196
197 #define MAKE_TAG_VALUE_ACCESSOR(tag_type, field_name) \
198 template <Tag tag> struct TypedTag2ValueType<TypedTag<tag_type, tag>> { \
199 typedef decltype(static_cast<KeyParameter*>(nullptr)->field_name) type; \
200 }; \
201 template <Tag tag> \
202 inline auto accessTagValue(TypedTag<tag_type, tag>, const KeyParameter& param) \
203 ->const decltype(param.field_name)& { \
204 return param.field_name; \
205 } \
206 template <Tag tag> \
207 inline auto accessTagValue(TypedTag<tag_type, tag>, KeyParameter& param) \
208 ->decltype(param.field_name)& { \
209 return param.field_name; \
210 }
211
212 MAKE_TAG_VALUE_ACCESSOR(TagType::ULONG, f.longInteger)
213 MAKE_TAG_VALUE_ACCESSOR(TagType::ULONG_REP, f.longInteger)
214 MAKE_TAG_VALUE_ACCESSOR(TagType::DATE, f.dateTime)
215 MAKE_TAG_VALUE_ACCESSOR(TagType::UINT, f.integer)
216 MAKE_TAG_VALUE_ACCESSOR(TagType::UINT_REP, f.integer)
217 MAKE_TAG_VALUE_ACCESSOR(TagType::BOOL, f.boolValue)
MAKE_TAG_VALUE_ACCESSOR(TagType::BYTES,blob)218 MAKE_TAG_VALUE_ACCESSOR(TagType::BYTES, blob)
219 MAKE_TAG_VALUE_ACCESSOR(TagType::BIGNUM, blob)
220
221 #define MAKE_TAG_ENUM_VALUE_ACCESSOR(typed_tag, field_name) \
222 template <> struct TypedTag2ValueType<decltype(typed_tag)> { \
223 typedef decltype(static_cast<KeyParameter*>(nullptr)->field_name) type; \
224 }; \
225 inline auto accessTagValue(decltype(typed_tag), const KeyParameter& param) \
226 ->const decltype(param.field_name)& { \
227 return param.field_name; \
228 } \
229 inline auto accessTagValue(decltype(typed_tag), KeyParameter& param) \
230 ->decltype(param.field_name)& { \
231 return param.field_name; \
232 }
233
234 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_ALGORITHM, f.algorithm)
235 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_BLOB_USAGE_REQUIREMENTS, f.keyBlobUsageRequirements)
236 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_BLOCK_MODE, f.blockMode)
237 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_DIGEST, f.digest)
238 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_EC_CURVE, f.ecCurve)
239 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_KDF, f.keyDerivationFunction)
240 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_ORIGIN, f.origin)
241 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_PADDING, f.paddingMode)
242 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_PURPOSE, f.purpose)
243 MAKE_TAG_ENUM_VALUE_ACCESSOR(TAG_USER_AUTH_TYPE, f.hardwareAuthenticatorType)
244
245 template <TagType tag_type, Tag tag, typename ValueT>
246 inline KeyParameter makeKeyParameter(TypedTag<tag_type, tag> ttag, ValueT&& value) {
247 KeyParameter param;
248 param.tag = tag;
249 param.f.longInteger = 0;
250 accessTagValue(ttag, param) = std::forward<ValueT>(value);
251 return param;
252 }
253
254 // the boolean case
makeKeyParameter(TypedTag<TagType::BOOL,tag>)255 template <Tag tag> inline KeyParameter makeKeyParameter(TypedTag<TagType::BOOL, tag>) {
256 KeyParameter param;
257 param.tag = tag;
258 param.f.boolValue = true;
259 return param;
260 }
261
262 template <typename... Pack> struct FirstOrNoneHelper;
263 template <typename First> struct FirstOrNoneHelper<First> { typedef First type; };
264 template <> struct FirstOrNoneHelper<> {
265 struct type {};
266 };
267
268 template <typename... Pack> using FirstOrNone = typename FirstOrNoneHelper<Pack...>::type;
269
270 template <TagType tag_type, Tag tag, typename... Args>
271 inline KeyParameter Authorization(TypedTag<tag_type, tag> ttag, Args&&... args) {
272 static_assert(tag_type != TagType::BOOL || (sizeof...(args) == 0),
273 "TagType::BOOL Authorizations do not take parameters. Presence is truth.");
274 static_assert(tag_type == TagType::BOOL || (sizeof...(args) == 1),
275 "Authorization other then TagType::BOOL take exactly one parameter.");
276 static_assert(
277 tag_type == TagType::BOOL ||
278 std::is_convertible<std::remove_cv_t<std::remove_reference_t<FirstOrNone<Args...>>>,
279 typename TypedTag2ValueType<TypedTag<tag_type, tag>>::type>::value,
280 "Invalid argument type for given tag.");
281
282 return makeKeyParameter(ttag, std::forward<Args>(args)...);
283 }
284
285 /**
286 * This class wraps a (mostly return) value and stores whether or not the wrapped value is valid out
287 * of band. Note that if the wrapped value is a reference it is unsafe to access the value if
288 * !isOk(). If the wrapped type is a pointer or value and !isOk(), it is still safe to access the
289 * wrapped value. In this case the pointer will be NULL though, and the value will be default
290 * constructed.
291 */
292 template <typename ValueT> class NullOr {
293 template <typename T> struct reference_initializer {
294 static T&& init() { return *static_cast<std::remove_reference_t<T>*>(nullptr); }
295 };
296 template <typename T> struct pointer_initializer {
297 static T init() { return nullptr; }
298 };
299 template <typename T> struct value_initializer {
300 static T init() { return T(); }
301 };
302 template <typename T>
303 using initializer_t =
304 std::conditional_t<std::is_lvalue_reference<T>::value, reference_initializer<T>,
305 std::conditional_t<std::is_pointer<T>::value, pointer_initializer<T>,
306 value_initializer<T>>>;
307
308 public:
309 NullOr() : value_(initializer_t<ValueT>::init()), null_(true) {}
310 // NOLINTNEXTLINE(google-explicit-constructor)
311 NullOr(ValueT&& value) : value_(std::forward<ValueT>(value)), null_(false) {}
312
313 bool isOk() const { return !null_; }
314
315 const ValueT& value() const& { return value_; }
316 ValueT& value() & { return value_; }
317 ValueT&& value() && { return std::move(value_); }
318
319 private:
320 ValueT value_;
321 bool null_;
322 };
323
324 template <typename T> std::remove_reference_t<T> NullOrOr(T&& v) {
325 if (v.isOk()) return v;
326 return {};
327 }
328
329 template <typename Head, typename... Tail>
330 std::remove_reference_t<Head> NullOrOr(Head&& head, Tail&&... tail) {
331 if (head.isOk()) return head;
332 return NullOrOr(std::forward<Tail>(tail)...);
333 }
334
335 template <typename Default, typename Wrapped>
336 std::remove_reference_t<Wrapped> defaultOr(NullOr<Wrapped>&& optional, Default&& def) {
337 static_assert(std::is_convertible<std::remove_reference_t<Default>,
338 std::remove_reference_t<Wrapped>>::value,
339 "Type of default value must match the type wrapped by NullOr");
340 if (optional.isOk()) return optional.value();
341 return def;
342 }
343
344 template <TagType tag_type, Tag tag>
345 inline NullOr<const typename TypedTag2ValueType<TypedTag<tag_type, tag>>::type&>
346 authorizationValue(TypedTag<tag_type, tag> ttag, const KeyParameter& param) {
347 if (tag != param.tag) return {};
348 return accessTagValue(ttag, param);
349 }
350
351 } // namespace keymaster::ng
352