1 /*
2  * Copyright (C) 2020 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 #include <aidl/android/hardware/security/keymint/BnKeyMintDevice.h>
20 #include <aidl/android/hardware/security/keymint/BnKeyMintOperation.h>
21 #include <aidl/android/hardware/security/keymint/ErrorCode.h>
22 #include <aidl/android/hardware/security/secureclock/BnSecureClock.h>
23 #include <aidl/android/hardware/security/sharedsecret/BnSharedSecret.h>
24 #include <aidl/android/security/compat/BnKeystoreCompatService.h>
25 #include <keymasterV4_1/Keymaster4.h>
26 #include <unordered_map>
27 #include <variant>
28 
29 #include "certificate_utils.h"
30 
31 using ::aidl::android::hardware::security::keymint::AttestationKey;
32 using ::aidl::android::hardware::security::keymint::BeginResult;
33 using ::aidl::android::hardware::security::keymint::Certificate;
34 using ::aidl::android::hardware::security::keymint::HardwareAuthToken;
35 using ::aidl::android::hardware::security::keymint::KeyCharacteristics;
36 using ::aidl::android::hardware::security::keymint::KeyCreationResult;
37 using ::aidl::android::hardware::security::keymint::KeyFormat;
38 using ::aidl::android::hardware::security::keymint::KeyMintHardwareInfo;
39 using ::aidl::android::hardware::security::keymint::KeyParameter;
40 using ::aidl::android::hardware::security::keymint::KeyPurpose;
41 using KeyMintSecurityLevel = ::aidl::android::hardware::security::keymint::SecurityLevel;
42 using V4_0_ErrorCode = ::android::hardware::keymaster::V4_0::ErrorCode;
43 using ::aidl::android::hardware::security::keymint::IKeyMintDevice;
44 using KMV1_ErrorCode = ::aidl::android::hardware::security::keymint::ErrorCode;
45 using ::aidl::android::hardware::security::secureclock::ISecureClock;
46 using ::aidl::android::hardware::security::secureclock::TimeStampToken;
47 using ::aidl::android::hardware::security::sharedsecret::ISharedSecret;
48 using ::aidl::android::hardware::security::sharedsecret::SharedSecretParameters;
49 using ::aidl::android::security::compat::BnKeystoreCompatService;
50 using ::android::hardware::keymaster::V4_1::support::Keymaster;
51 using ::ndk::ScopedAStatus;
52 
53 class OperationSlot;
54 class OperationSlotManager;
55 // An abstraction for a single operation slot.
56 // This contains logic to ensure that we do not free the slot multiple times,
57 // e.g., if we call abort twice on the same operation.
58 class OperationSlot {
59     friend OperationSlotManager;
60 
61   private:
62     std::shared_ptr<OperationSlotManager> mOperationSlots;
63     std::optional<std::unique_lock<std::mutex>> mReservedGuard;
64 
65   protected:
66     OperationSlot(std::shared_ptr<OperationSlotManager>,
67                   std::optional<std::unique_lock<std::mutex>> reservedGuard);
68     OperationSlot(const OperationSlot&) = delete;
69     OperationSlot& operator=(const OperationSlot&) = delete;
70 
71   public:
OperationSlot()72     OperationSlot() : mOperationSlots(nullptr), mReservedGuard(std::nullopt) {}
73     OperationSlot(OperationSlot&&) = default;
74     OperationSlot& operator=(OperationSlot&&) = default;
75     ~OperationSlot();
76 };
77 
78 class OperationSlotManager {
79   private:
80     uint8_t mNumFreeSlots;
81     std::mutex mNumFreeSlotsMutex;
82     std::mutex mReservedSlotMutex;
83 
84   public:
85     void setNumFreeSlots(uint8_t numFreeSlots);
86     static std::optional<OperationSlot>
87     claimSlot(std::shared_ptr<OperationSlotManager> operationSlots);
88     static OperationSlot claimReservedSlot(std::shared_ptr<OperationSlotManager> operationSlots);
89     void freeSlot();
90 };
91 
92 class KeyMintDevice : public aidl::android::hardware::security::keymint::BnKeyMintDevice {
93   private:
94     ::android::sp<Keymaster> mDevice;
95     std::shared_ptr<OperationSlotManager> mOperationSlots;
96 
97   public:
98     explicit KeyMintDevice(::android::sp<Keymaster>, KeyMintSecurityLevel);
99     static std::shared_ptr<IKeyMintDevice> createKeyMintDevice(KeyMintSecurityLevel securityLevel);
100     static std::shared_ptr<KeyMintDevice>
101     getWrappedKeymasterDevice(KeyMintSecurityLevel securityLevel);
102 
103     ScopedAStatus getHardwareInfo(KeyMintHardwareInfo* _aidl_return) override;
104     ScopedAStatus addRngEntropy(const std::vector<uint8_t>& in_data) override;
105     ScopedAStatus generateKey(const std::vector<KeyParameter>& in_keyParams,
106                               const std::optional<AttestationKey>& in_attestationKey,
107                               KeyCreationResult* out_creationResult) override;
108     ScopedAStatus importKey(const std::vector<KeyParameter>& in_inKeyParams,
109                             KeyFormat in_inKeyFormat, const std::vector<uint8_t>& in_inKeyData,
110                             const std::optional<AttestationKey>& in_attestationKey,
111                             KeyCreationResult* out_creationResult) override;
112     ScopedAStatus importWrappedKey(const std::vector<uint8_t>& in_inWrappedKeyData,
113                                    const std::vector<uint8_t>& in_inWrappingKeyBlob,
114                                    const std::vector<uint8_t>& in_inMaskingKey,
115                                    const std::vector<KeyParameter>& in_inUnwrappingParams,
116                                    int64_t in_inPasswordSid, int64_t in_inBiometricSid,
117                                    KeyCreationResult* out_creationResult) override;
118     ScopedAStatus upgradeKey(const std::vector<uint8_t>& in_inKeyBlobToUpgrade,
119                              const std::vector<KeyParameter>& in_inUpgradeParams,
120                              std::vector<uint8_t>* _aidl_return) override;
121     ScopedAStatus deleteKey(const std::vector<uint8_t>& in_inKeyBlob) override;
122     ScopedAStatus deleteAllKeys() override;
123     ScopedAStatus destroyAttestationIds() override;
124 
125     ScopedAStatus begin(KeyPurpose in_inPurpose, const std::vector<uint8_t>& in_inKeyBlob,
126                         const std::vector<KeyParameter>& in_inParams,
127                         const std::optional<HardwareAuthToken>& in_inAuthToken,
128                         BeginResult* _aidl_return) override;
129     ScopedAStatus beginInternal(KeyPurpose in_inPurpose, const std::vector<uint8_t>& in_inKeyBlob,
130                                 const std::vector<KeyParameter>& in_inParams,
131                                 const std::optional<HardwareAuthToken>& in_inAuthToken,
132                                 bool useReservedSlot, BeginResult* _aidl_return);
133     ScopedAStatus deviceLocked(bool passwordOnly,
134                                const std::optional<TimeStampToken>& timestampToken) override;
135     ScopedAStatus earlyBootEnded() override;
136 
137     ScopedAStatus convertStorageKeyToEphemeral(const std::vector<uint8_t>& storageKeyBlob,
138                                                std::vector<uint8_t>* ephemeralKeyBlob) override;
139 
140     ScopedAStatus
141     getKeyCharacteristics(const std::vector<uint8_t>& storageKeyBlob,
142                           const std::vector<uint8_t>& appId, const std::vector<uint8_t>& appData,
143                           std::vector<KeyCharacteristics>* keyCharacteristics) override;
144 
145     ScopedAStatus getRootOfTrustChallenge(std::array<uint8_t, 16>* challenge);
146     ScopedAStatus getRootOfTrust(const std::array<uint8_t, 16>& challenge,
147                                  std::vector<uint8_t>* rootOfTrust);
148     ScopedAStatus sendRootOfTrust(const std::vector<uint8_t>& rootOfTrust);
149 
150     // These are public to allow testing code to use them directly.
151     // This class should not be used publicly anyway.
152     std::variant<std::vector<Certificate>, KMV1_ErrorCode>
153     getCertificate(const std::vector<KeyParameter>& keyParams, const std::vector<uint8_t>& keyBlob,
154                    bool isWrappedKey = false);
155 
156     void setNumFreeSlots(uint8_t numFreeSlots);
157 
158   private:
159     std::optional<KMV1_ErrorCode> signCertificate(const std::vector<KeyParameter>& keyParams,
160                                                   const std::vector<uint8_t>& keyBlob, X509* cert);
161     KeyMintSecurityLevel securityLevel_;
162 
163     // Software-based KeyMint device used to implement ECDH.
164     std::shared_ptr<IKeyMintDevice> softKeyMintDevice_;
165 };
166 
167 class KeyMintOperation : public aidl::android::hardware::security::keymint::BnKeyMintOperation {
168   public:
KeyMintOperation(::android::sp<Keymaster> device,uint64_t operationHandle,OperationSlot slot)169     KeyMintOperation(::android::sp<Keymaster> device, uint64_t operationHandle, OperationSlot slot)
170         : mDevice(device), mOperationHandle(operationHandle), mOperationSlot(std::move(slot)) {}
171     ~KeyMintOperation();
172 
173     ScopedAStatus updateAad(const std::vector<uint8_t>& input,
174                             const std::optional<HardwareAuthToken>& authToken,
175                             const std::optional<TimeStampToken>& timestampToken) override;
176 
177     ScopedAStatus update(const std::vector<uint8_t>& input,
178                          const std::optional<HardwareAuthToken>& authToken,
179                          const std::optional<TimeStampToken>& timestampToken,
180                          std::vector<uint8_t>* output) override;
181 
182     ScopedAStatus finish(const std::optional<std::vector<uint8_t>>& input,
183                          const std::optional<std::vector<uint8_t>>& signature,
184                          const std::optional<HardwareAuthToken>& authToken,
185                          const std::optional<TimeStampToken>& timeStampToken,
186                          const std::optional<std::vector<uint8_t>>& confirmationToken,
187                          std::vector<uint8_t>* output) override;
188 
189     ScopedAStatus abort();
190 
191   private:
192     /**
193      * Sets mUpdateBuffer to the given value.
194      * @param data
195      */
196     void setUpdateBuffer(std::vector<uint8_t> data);
197     /**
198      * If mUpdateBuffer is not empty, suffix is appended to mUpdateBuffer, and a reference to
199      * mUpdateBuffer is returned. Otherwise a reference to suffix is returned.
200      * @param suffix
201      * @return
202      */
203     const std::vector<uint8_t>& getExtendedUpdateBuffer(const std::vector<uint8_t>& suffix);
204 
205     std::vector<uint8_t> mUpdateBuffer;
206     ::android::sp<Keymaster> mDevice;
207     uint64_t mOperationHandle;
208     std::optional<OperationSlot> mOperationSlot;
209 };
210 
211 class SharedSecret : public aidl::android::hardware::security::sharedsecret::BnSharedSecret {
212   private:
213     ::android::sp<Keymaster> mDevice;
214 
215   public:
SharedSecret(::android::sp<Keymaster> device)216     SharedSecret(::android::sp<Keymaster> device) : mDevice(device) {}
217     static std::shared_ptr<SharedSecret> createSharedSecret(KeyMintSecurityLevel securityLevel);
218 
219     virtual ScopedAStatus getSharedSecretParameters(SharedSecretParameters* _aidl_return) override;
220     virtual ScopedAStatus computeSharedSecret(const std::vector<SharedSecretParameters>& in_params,
221                                               std::vector<uint8_t>* _aidl_return) override;
222 };
223 
224 class SecureClock : public aidl::android::hardware::security::secureclock::BnSecureClock {
225   private:
226     ::android::sp<Keymaster> mDevice;
227 
228   public:
SecureClock(::android::sp<Keymaster> device)229     SecureClock(::android::sp<Keymaster> device) : mDevice(device) {}
230     static std::shared_ptr<SecureClock> createSecureClock(KeyMintSecurityLevel securityLevel);
231 
232     ScopedAStatus generateTimeStamp(int64_t in_challenge, TimeStampToken* _aidl_return) override;
233 };
234 
235 class KeystoreCompatService : public BnKeystoreCompatService {
236   private:
237     std::unordered_map<KeyMintSecurityLevel, std::shared_ptr<IKeyMintDevice>> mDeviceCache;
238     std::unordered_map<KeyMintSecurityLevel, std::shared_ptr<ISharedSecret>> mSharedSecretCache;
239     std::shared_ptr<ISecureClock> mSecureClock;
240 
241   public:
KeystoreCompatService()242     KeystoreCompatService() {}
243     ScopedAStatus getKeyMintDevice(KeyMintSecurityLevel in_securityLevel,
244                                    std::shared_ptr<IKeyMintDevice>* _aidl_return) override;
245     ScopedAStatus getSharedSecret(KeyMintSecurityLevel in_securityLevel,
246                                   std::shared_ptr<ISharedSecret>* _aidl_return) override;
247     ScopedAStatus getSecureClock(std::shared_ptr<ISecureClock>* _aidl_return) override;
248 };
249