1 /*
2  * Copyright 2015 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_KEYMASTER_KEYMASTER_CONTEXT_H_
18 #define SYSTEM_KEYMASTER_KEYMASTER_CONTEXT_H_
19 
20 #include <optional>
21 #include <string_view>
22 
23 #include <assert.h>
24 
25 #include <hardware/keymaster_defs.h>
26 
27 #include <keymaster/android_keymaster_messages.h>
28 #include <keymaster/android_keymaster_utils.h>
29 #include <keymaster/keymaster_enforcement.h>
30 #include <keymaster/km_version.h>
31 #include <keymaster/remote_provisioning_context.h>
32 #include <keymaster/secure_key_storage.h>
33 
34 namespace keymaster {
35 
36 class AuthorizationSet;
37 class AttestationContext;
38 class KeyFactory;
39 class OperationFactory;
40 class SecureDeletionSecretStorage;
41 template <typename BlobType> struct TKeymasterBlob;
42 typedef TKeymasterBlob<keymaster_key_blob_t> KeymasterKeyBlob;
43 class Key;
44 
45 /**
46  * KeymasterContext provides a singleton abstract interface that encapsulates various
47  * environment-dependent elements of AndroidKeymaster.
48  *
49  * AndroidKeymaster runs in multiple contexts.  Primarily:
50  *
51  * - In a trusted execution environment (TEE) as a "secure hardware" implementation.  In this
52  *   context keys are wrapped with an master key that never leaves the TEE, TEE-specific routines
53  *   are used for random number generation, all AndroidKeymaster-enforced authorizations are
54  *   considered hardware-enforced, and there's a bootloader-provided root of trust.
55  *
56  * - In the non-secure world as a software-only implementation.  In this context keys are not
57  *   encrypted (though they are integrity-checked) because there is no place to securely store a
58  *   key, OpenSSL is used for random number generation, no AndroidKeymaster-enforced authorizations
59  *   are considered hardware enforced and the root of trust is a static string.
60  *
61  * - In the non-secure world as a hybrid implementation fronting a less-capable hardware
62  *   implementation.  For example, a keymaster0 hardware implementation.  In this context keys are
63  *   not encrypted by AndroidKeymaster, but some may be opaque blobs provided by the backing
64  *   hardware, but blobs that lack the extended authorization lists of keymaster1.  In addition,
65  *   keymaster0 lacks many features of keymaster1, including modes of operation related to the
66  *   backing keymaster0 keys.  AndroidKeymaster must extend the blobs to add authorization lists,
67  *   and must provide the missing operation mode implementations in software, which means that
68  *   authorization lists are partially hardware-enforced (the bits that are enforced by the
69  *   underlying keymaster0) and partially software-enforced (the rest). OpenSSL is used for number
70  *   generation and the root of trust is a static string.
71  *
72  * More contexts are possible.
73  */
74 class KeymasterContext {
75   public:
KeymasterContext()76     KeymasterContext() {}
~KeymasterContext()77     virtual ~KeymasterContext(){};
78 
79     /**
80      * Returns the Keymaster/KeyMint version we're currently implementing.
81      *
82      * Because AndroidKeymaster supports multiple versions of Keymaster/KeyMint, with slightly
83      * different behavior, we sometimes need to branch based on the version currently being
84      * implemented.  This method provides the currently-implemented version.
85      */
86     virtual KmVersion GetKmVersion() const = 0;
87 
88     /**
89      * Sets the system version as reported by the system *itself*.  This is used to verify that the
90      * system believes itself to be running the same version that is reported by the bootloader, in
91      * hardware implementations.  For SoftKeymasterDevice, this sets the version information used.
92      *
93      * If the specified values don't match the bootloader-provided values, this method must return
94      * KM_ERROR_INVALID_ARGUMENT;
95      */
96     virtual keymaster_error_t SetSystemVersion(uint32_t os_version, uint32_t os_patchlevel) = 0;
97 
98     /**
99      * Returns the system version.  For hardware-based implementations this will be the value
100      * reported by the bootloader.  For SoftKeymasterDevice it will be the verion information set by
101      * SetSystemVersion above.
102      */
103     virtual void GetSystemVersion(uint32_t* os_version, uint32_t* os_patchlevel) const = 0;
104 
105     virtual const KeyFactory* GetKeyFactory(keymaster_algorithm_t algorithm) const = 0;
106     virtual const OperationFactory* GetOperationFactory(keymaster_algorithm_t algorithm,
107                                                         keymaster_purpose_t purpose) const = 0;
108     virtual const keymaster_algorithm_t* GetSupportedAlgorithms(size_t* algorithms_count) const = 0;
109 
110     /**
111      * UpgradeKeyBlob takes an existing blob, parses out key material and constructs a new blob with
112      * the current format and OS version info.
113      */
114     virtual keymaster_error_t UpgradeKeyBlob(const KeymasterKeyBlob& key_to_upgrade,
115                                              const AuthorizationSet& upgrade_params,
116                                              KeymasterKeyBlob* upgraded_key) const = 0;
117 
118     /**
119      * ParseKeyBlob takes a blob and extracts authorization sets and key material, returning an
120      * error if the blob fails integrity checking or decryption.  Note that the returned key
121      * material may itself be an opaque blob usable only by secure hardware (in the hybrid case).
122      *
123      * This method is called by AndroidKeymaster.
124      */
125     virtual keymaster_error_t ParseKeyBlob(const KeymasterKeyBlob& blob,
126                                            const AuthorizationSet& additional_params,
127                                            UniquePtr<Key>* key) const = 0;
128 
129     /**
130      * Take whatever environment-specific action is appropriate (if any) to delete the specified
131      * key.
132      */
DeleteKey(const KeymasterKeyBlob &)133     virtual keymaster_error_t DeleteKey(const KeymasterKeyBlob& /* blob */) const {
134         return KM_ERROR_OK;
135     }
136 
137     /**
138      * Take whatever environment-specific action is appropriate to delete all keys.
139      */
DeleteAllKeys()140     virtual keymaster_error_t DeleteAllKeys() const { return KM_ERROR_OK; }
141 
142     /**
143      * Adds entropy to the Cryptographic Pseudo Random Number Generator used to generate key
144      * material, and other cryptographic protocol elements.  Note that if the underlying CPRNG
145      * tracks the size of its entropy pool, it should not assume that the provided data contributes
146      * any entropy, and it should also ensure that data provided through this interface cannot
147      * "poison" the CPRNG outputs, making them predictable.
148      */
149     virtual keymaster_error_t AddRngEntropy(const uint8_t* buf, size_t length) const = 0;
150 
151     /**
152      * Return the enforcement policy for this context, or null if no enforcement should be done.
153      */
154     virtual KeymasterEnforcement* enforcement_policy() = 0;
155 
156     /**
157      * Return the attestation context for this context.
158      */
attestation_context()159     virtual AttestationContext* attestation_context() { return nullptr; }
160 
161     /**
162      * Generate an attestation certificate, with chain.
163      *
164      * If attest_key is null, the certificate will be signed with the factory attestation key (from
165      * AttestationContext) and have the issuer subject set to the subject name from the signing key
166      * certificate.  If attest_key is non-null, it will be used to sign the certificate and the
167      * provided issuer subject will be used (must contain a DER-encoded X.509 NAME).
168      */
169     virtual CertificateChain GenerateAttestation(const Key& key,
170                                                  const AuthorizationSet& attest_params,
171                                                  UniquePtr<Key> attest_key,
172                                                  const KeymasterBlob& issuer_subject,
173                                                  keymaster_error_t* error) const = 0;
174 
175     /**
176      * Generate a self-signed certificate.  If fake_signature is true, a fake signature is installed
177      * in the certificate, rather than an actual self-signature.  The fake signature will not
178      * verify, of course.  In this case the certificate is primarily a way to convey the public key.
179      *
180      * Note that although the return type is CertificateChain, this is for convenience and
181      * consistency with GenerateAttestation, the chain never contains more than a single
182      * certificate.
183      */
184     virtual CertificateChain GenerateSelfSignedCertificate(const Key& key,
185                                                            const AuthorizationSet& cert_params,
186                                                            bool fake_signature,
187                                                            keymaster_error_t* error) const = 0;
188 
189     virtual keymaster_error_t
190     UnwrapKey(const KeymasterKeyBlob& wrapped_key_blob, const KeymasterKeyBlob& wrapping_key_blob,
191               const AuthorizationSet& wrapping_key_params, const KeymasterKeyBlob& masking_key,
192               AuthorizationSet* wrapped_key_params, keymaster_key_format_t* wrapped_key_format,
193               KeymasterKeyBlob* wrapped_key_material) const = 0;
194 
195     /**
196      * Return the secure key storage for this context, or null if there is no available secure key
197      * storage.
198      */
secure_key_storage()199     virtual SecureKeyStorage* secure_key_storage() { return nullptr; }
200 
201     /**
202      * Return the secure deletion secret storage for this context, or null if none is available.
203      *
204      * Note that SecureDeletionSecretStorage obsoletes SecureKeyStorage (see method above).  The
205      * latter will be removed in the future.
206      */
secure_deletion_secret_storage()207     virtual SecureDeletionSecretStorage* secure_deletion_secret_storage() { return nullptr; }
208 
209     /**
210      * Checks that the data in |input_data| of size |input_data_size| matches the
211      * confirmation token given by |confirmation_token|.
212      *
213      * Note that |input_data| will already contain the prefixed message tag
214      * "confirmation token" (not including NUL byte) so all the implementation
215      * of this method needs to do is to calculate HMAC-SHA256 over |input_data|
216      * and compare it with |confirmation_token|. To do this the implementation
217      * needs access to the secret key shared with the ConfirmationUI TA.
218      *
219      * Returns KM_ERROR_OK if |input_data| matches |confirmation_token|,
220      * KM_ERROR_NO_USER_CONFIRMATION if it doesn't, and if memory allocation
221      * fails KM_ERROR_MEMORY_ALLOCATION_FAILED. If not implemented then
222      * KM_ERROR_UNIMPLEMENTED is returned.
223      */
224     virtual keymaster_error_t
CheckConfirmationToken(const uint8_t *,size_t,const uint8_t[kConfirmationTokenSize])225     CheckConfirmationToken(const uint8_t* /*input_data*/, size_t /*input_data_size*/,
226                            const uint8_t /*confirmation_token*/[kConfirmationTokenSize]) const {
227         return KM_ERROR_UNIMPLEMENTED;
228     }
229 
230     /**
231      * Return the remote provisioning context object, or null if remote provisioning is not
232      * supported.
233      */
GetRemoteProvisioningContext()234     virtual RemoteProvisioningContext* GetRemoteProvisioningContext() const { return nullptr; }
235 
236     /**
237      * Sets the verified boot metadata. This value should be set by the bootloader.
238      * A subsequent to set a different value will return KM_ERROR_INVALID_ARGUMENT.
239      */
SetVerifiedBootInfo(std::string_view,std::string_view,const std::vector<uint8_t> &)240     virtual keymaster_error_t SetVerifiedBootInfo(std::string_view /*verified_boot_state*/,
241                                                   std::string_view /*bootloader_state*/,
242                                                   const std::vector<uint8_t>& /*vbmeta_digest*/) {
243         return KM_ERROR_UNIMPLEMENTED;
244     }
245 
246     /**
247      * Sets the vendor patchlevel (format YYYYMMDD) for the implementation. This value should
248      * be set by the HAL service at start of day.  A subsequent attempt to set a different
249      * value will return KM_ERROR_INVALID_ARGUMENT.
250      */
SetVendorPatchlevel(uint32_t)251     virtual keymaster_error_t SetVendorPatchlevel(uint32_t /* vendor_patchlevel */) {
252         return KM_ERROR_UNIMPLEMENTED;
253     }
254 
255     /**
256      * Sets the boot patchlevel (format YYYYMMDD) for the implementation. This value should be set
257      * by the bootloader.  A subsequent to set a different value will return
258      * KM_ERROR_INVALID_ARGUMENT.
259      */
SetBootPatchlevel(uint32_t)260     virtual keymaster_error_t SetBootPatchlevel(uint32_t /* boot_patchlevel */) {
261         return KM_ERROR_UNIMPLEMENTED;
262     }
263 
264     /**
265      * Returns the vendor patchlevel, as set by the HAL service using SetVendorPatchlevel.
266      */
GetVendorPatchlevel()267     virtual std::optional<uint32_t> GetVendorPatchlevel() const { return std::nullopt; }
268 
269     /**
270      * Returns the boot patchlevel. For hardware-based implementations this will be the value set by
271      * the bootloader. For software implementations this will be the information set by
272      * SetBootPatchLevel.
273      */
GetBootPatchlevel()274     virtual std::optional<uint32_t> GetBootPatchlevel() const { return std::nullopt; }
275 
276     /**
277      * Sets attestation IDs for the implementation. On physical devices (as opposed to emulators)
278      * attestation IDs should only be set during provisioning process.
279      */
SetAttestationIds(const SetAttestationIdsRequest &)280     virtual keymaster_error_t SetAttestationIds(const SetAttestationIdsRequest& /* request */) {
281         return KM_ERROR_UNIMPLEMENTED;
282     }
283 
284     /**
285      * Sets KM3 attestation IDs for the implementation. On physical
286      * devices (as opposed to emulators) attestation ID should only be set
287      * during provisioning process.
288      */
289     virtual keymaster_error_t
SetAttestationIdsKM3(const SetAttestationIdsKM3Request &)290     SetAttestationIdsKM3(const SetAttestationIdsKM3Request& /* request */) {
291         return KM_ERROR_UNIMPLEMENTED;
292     }
293 
294   private:
295     // Uncopyable.
296     KeymasterContext(const KeymasterContext&);
297     void operator=(const KeymasterContext&);
298 };
299 
300 }  // namespace keymaster
301 
302 #endif  // SYSTEM_KEYMASTER_KEYMASTER_CONTEXT_H_
303