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