xref: /aosp_15_r20/system/security/keystore2/src/km_compat/km_compat.h (revision e1997b9af69e3155ead6e072d106a0077849ffba)
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     ScopedAStatus
151     setAdditionalAttestationInfo(const std::vector<KeyParameter>& additionalAttestationInfo);
152 
153     // These are public to allow testing code to use them directly.
154     // This class should not be used publicly anyway.
155     std::variant<std::vector<Certificate>, KMV1_ErrorCode>
156     getCertificate(const std::vector<KeyParameter>& keyParams, const std::vector<uint8_t>& keyBlob,
157                    bool isWrappedKey = false);
158 
159     void setNumFreeSlots(uint8_t numFreeSlots);
160 
161   private:
162     std::optional<KMV1_ErrorCode> signCertificate(const std::vector<KeyParameter>& keyParams,
163                                                   const std::vector<uint8_t>& keyBlob, X509* cert);
164     KeyMintSecurityLevel securityLevel_;
165 
166     // Software-based KeyMint device used to implement ECDH.
167     std::shared_ptr<IKeyMintDevice> softKeyMintDevice_;
168 };
169 
170 class KeyMintOperation : public aidl::android::hardware::security::keymint::BnKeyMintOperation {
171   public:
KeyMintOperation(::android::sp<Keymaster> device,uint64_t operationHandle,OperationSlot slot)172     KeyMintOperation(::android::sp<Keymaster> device, uint64_t operationHandle, OperationSlot slot)
173         : mDevice(device), mOperationHandle(operationHandle), mOperationSlot(std::move(slot)) {}
174     ~KeyMintOperation();
175 
176     ScopedAStatus updateAad(const std::vector<uint8_t>& input,
177                             const std::optional<HardwareAuthToken>& authToken,
178                             const std::optional<TimeStampToken>& timestampToken) override;
179 
180     ScopedAStatus update(const std::vector<uint8_t>& input,
181                          const std::optional<HardwareAuthToken>& authToken,
182                          const std::optional<TimeStampToken>& timestampToken,
183                          std::vector<uint8_t>* output) override;
184 
185     ScopedAStatus finish(const std::optional<std::vector<uint8_t>>& input,
186                          const std::optional<std::vector<uint8_t>>& signature,
187                          const std::optional<HardwareAuthToken>& authToken,
188                          const std::optional<TimeStampToken>& timeStampToken,
189                          const std::optional<std::vector<uint8_t>>& confirmationToken,
190                          std::vector<uint8_t>* output) override;
191 
192     ScopedAStatus abort();
193 
194   private:
195     /**
196      * Sets mUpdateBuffer to the given value.
197      * @param data
198      */
199     void setUpdateBuffer(std::vector<uint8_t> data);
200     /**
201      * If mUpdateBuffer is not empty, suffix is appended to mUpdateBuffer, and a reference to
202      * mUpdateBuffer is returned. Otherwise a reference to suffix is returned.
203      * @param suffix
204      * @return
205      */
206     const std::vector<uint8_t>& getExtendedUpdateBuffer(const std::vector<uint8_t>& suffix);
207 
208     std::vector<uint8_t> mUpdateBuffer;
209     ::android::sp<Keymaster> mDevice;
210     uint64_t mOperationHandle;
211     std::optional<OperationSlot> mOperationSlot;
212 };
213 
214 class SharedSecret : public aidl::android::hardware::security::sharedsecret::BnSharedSecret {
215   private:
216     ::android::sp<Keymaster> mDevice;
217 
218   public:
SharedSecret(::android::sp<Keymaster> device)219     SharedSecret(::android::sp<Keymaster> device) : mDevice(device) {}
220     static std::shared_ptr<SharedSecret> createSharedSecret(KeyMintSecurityLevel securityLevel);
221 
222     virtual ScopedAStatus getSharedSecretParameters(SharedSecretParameters* _aidl_return) override;
223     virtual ScopedAStatus computeSharedSecret(const std::vector<SharedSecretParameters>& in_params,
224                                               std::vector<uint8_t>* _aidl_return) override;
225 };
226 
227 class SecureClock : public aidl::android::hardware::security::secureclock::BnSecureClock {
228   private:
229     ::android::sp<Keymaster> mDevice;
230 
231   public:
SecureClock(::android::sp<Keymaster> device)232     SecureClock(::android::sp<Keymaster> device) : mDevice(device) {}
233     static std::shared_ptr<SecureClock> createSecureClock(KeyMintSecurityLevel securityLevel);
234 
235     ScopedAStatus generateTimeStamp(int64_t in_challenge, TimeStampToken* _aidl_return) override;
236 };
237 
238 class KeystoreCompatService : public BnKeystoreCompatService {
239   private:
240     std::unordered_map<KeyMintSecurityLevel, std::shared_ptr<IKeyMintDevice>> mDeviceCache;
241     std::unordered_map<KeyMintSecurityLevel, std::shared_ptr<ISharedSecret>> mSharedSecretCache;
242     std::shared_ptr<ISecureClock> mSecureClock;
243 
244   public:
KeystoreCompatService()245     KeystoreCompatService() {}
246     ScopedAStatus getKeyMintDevice(KeyMintSecurityLevel in_securityLevel,
247                                    std::shared_ptr<IKeyMintDevice>* _aidl_return) override;
248     ScopedAStatus getSharedSecret(KeyMintSecurityLevel in_securityLevel,
249                                   std::shared_ptr<ISharedSecret>* _aidl_return) override;
250     ScopedAStatus getSecureClock(std::shared_ptr<ISecureClock>* _aidl_return) override;
251 };
252