1 /*
2  * Copyright (C) 2016 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 ANDROID_VOLD_KEYMASTER_H
18 #define ANDROID_VOLD_KEYMASTER_H
19 
20 #include "KeyBuffer.h"
21 
22 #include <memory>
23 #include <string>
24 #include <utility>
25 
26 #include <android-base/macros.h>
27 #include <keymasterV4_1/Keymaster.h>
28 #include <keymasterV4_1/authorization_set.h>
29 
30 namespace android {
31 namespace vold {
32 
33 namespace km {
34 
35 using namespace ::android::hardware::keymaster::V4_1;
36 
37 // Surprisingly -- to me, at least -- this is totally fine.  You can re-define symbols that were
38 // brought in via a using directive (the "using namespace") above.  In general this seems like a
39 // dangerous thing to rely on, but in this case its implications are simple and straightforward:
40 // km::ErrorCode refers to the 4.0 ErrorCode, though we pull everything else from 4.1.
41 using ErrorCode = ::android::hardware::keymaster::V4_0::ErrorCode;
42 using V4_1_ErrorCode = ::android::hardware::keymaster::V4_1::ErrorCode;
43 
44 }  // namespace km
45 
46 using KmDevice = km::support::Keymaster;
47 
48 // C++ wrappers to the Keymaster hidl interface.
49 // This is tailored to the needs of KeyStorage, but could be extended to be
50 // a more general interface.
51 
52 // Wrapper for a Keymaster operation handle representing an
53 // ongoing Keymaster operation.  Aborts the operation
54 // in the destructor if it is unfinished. Methods log failures
55 // to LOG(ERROR).
56 class KeymasterOperation {
57   public:
58     ~KeymasterOperation();
59     // Is this instance valid? This is false if creation fails, and becomes
60     // false on finish or if an update fails.
61     explicit operator bool() const { return mError == km::ErrorCode::OK; }
errorCode()62     km::ErrorCode errorCode() const { return mError; }
63     // Call "update" repeatedly until all of the input is consumed, and
64     // concatenate the output. Return true on success.
65     template <class TI, class TO>
updateCompletely(TI & input,TO * output)66     bool updateCompletely(TI& input, TO* output) {
67         if (output) output->clear();
68         return updateCompletely(input.data(), input.size(), [&](const char* b, size_t n) {
69             if (output) std::copy(b, b + n, std::back_inserter(*output));
70         });
71     }
72 
73     // Finish and write the output to this string, unless pointer is null.
74     bool finish(std::string* output);
75     // Move constructor
KeymasterOperation(KeymasterOperation && rhs)76     KeymasterOperation(KeymasterOperation&& rhs) { *this = std::move(rhs); }
77     // Construct an object in an error state for error returns
KeymasterOperation()78     KeymasterOperation() : mDevice{nullptr}, mOpHandle{0}, mError{km::ErrorCode::UNKNOWN_ERROR} {}
79     // Move Assignment
80     KeymasterOperation& operator=(KeymasterOperation&& rhs) {
81         mDevice = rhs.mDevice;
82         rhs.mDevice = nullptr;
83 
84         mOpHandle = rhs.mOpHandle;
85         rhs.mOpHandle = 0;
86 
87         mError = rhs.mError;
88         rhs.mError = km::ErrorCode::UNKNOWN_ERROR;
89 
90         return *this;
91     }
92 
93   private:
KeymasterOperation(KmDevice * d,uint64_t h)94     KeymasterOperation(KmDevice* d, uint64_t h)
95         : mDevice{d}, mOpHandle{h}, mError{km::ErrorCode::OK} {}
KeymasterOperation(km::ErrorCode error)96     KeymasterOperation(km::ErrorCode error) : mDevice{nullptr}, mOpHandle{0}, mError{error} {}
97 
98     bool updateCompletely(const char* input, size_t inputLen,
99                           const std::function<void(const char*, size_t)> consumer);
100 
101     KmDevice* mDevice;
102     uint64_t mOpHandle;
103     km::ErrorCode mError;
104     DISALLOW_COPY_AND_ASSIGN(KeymasterOperation);
105     friend class Keymaster;
106 };
107 
108 // Wrapper for a Keymaster device for methods that start a KeymasterOperation or are not
109 // part of one.
110 class Keymaster {
111   public:
112     Keymaster();
113     // false if we failed to open the keymaster device.
114     explicit operator bool() { return mDevice.get() != nullptr; }
115     // Generate a key in the keymaster from the given params.
116     bool generateKey(const km::AuthorizationSet& inParams, std::string* key);
117     // Exports a keymaster key with STORAGE_KEY tag wrapped with a per-boot ephemeral key
118     bool exportKey(const KeyBuffer& kmKey, std::string* key);
119     // If the keymaster supports it, permanently delete a key.
120     bool deleteKey(const std::string& key);
121     // Replace stored key blob in response to KM_ERROR_KEY_REQUIRES_UPGRADE.
122     bool upgradeKey(const std::string& oldKey, const km::AuthorizationSet& inParams,
123                     std::string* newKey);
124     // Begin a new cryptographic operation, collecting output parameters if pointer is non-null
125     KeymasterOperation begin(km::KeyPurpose purpose, const std::string& key,
126                              const km::AuthorizationSet& inParams,
127                              const km::HardwareAuthToken& authToken,
128                              km::AuthorizationSet* outParams);
129     bool isSecure();
130 
131     // Tell all Keymaster instances that early boot has ended and early boot-only keys can no longer
132     // be created or used.
133     static void earlyBootEnded();
134 
135   private:
136     std::unique_ptr<KmDevice> mDevice;
137     DISALLOW_COPY_AND_ASSIGN(Keymaster);
138     static bool hmacKeyGenerated;
139 };
140 
141 }  // namespace vold
142 }  // namespace android
143 
144 // FIXME no longer needed now cryptfs is in C++.
145 
146 /*
147  * The following functions provide C bindings to keymaster services
148  * needed by cryptfs scrypt. The compatibility check checks whether
149  * the keymaster implementation is considered secure, i.e., TEE backed.
150  * The create_key function generates an RSA key for signing.
151  * The sign_object function signes an object with the given keymaster
152  * key.
153  */
154 
155 /* Return values for keymaster_sign_object_for_cryptfs_scrypt */
156 
157 enum class KeymasterSignResult {
158     ok = 0,
159     error = -1,
160     upgrade = -2,
161 };
162 
163 int keymaster_compatibility_cryptfs_scrypt();
164 int keymaster_create_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
165                                             uint32_t ratelimit, uint8_t* key_buffer,
166                                             uint32_t key_buffer_size, uint32_t* key_out_size);
167 
168 int keymaster_upgrade_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
169                                              uint32_t ratelimit, const uint8_t* key_blob,
170                                              size_t key_blob_size, uint8_t* key_buffer,
171                                              uint32_t key_buffer_size, uint32_t* key_out_size);
172 
173 KeymasterSignResult keymaster_sign_object_for_cryptfs_scrypt(
174     const uint8_t* key_blob, size_t key_blob_size, uint32_t ratelimit, const uint8_t* object,
175     const size_t object_size, uint8_t** signature_buffer, size_t* signature_buffer_size);
176 
177 #endif
178