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 <assert.h>
21
22#include <openssl/evp.h>
23
24#include <hardware/keymaster_defs.h>
25#include <keymaster/keymaster_enforcement.h>
26
27namespace keymaster {
28
29class AuthorizationSet;
30class KeyFactory;
31class OperationFactory;
32struct KeymasterKeyBlob;
33
34/**
35 * KeymasterContext provides a singleton abstract interface that encapsulates various
36 * environment-dependent elements of AndroidKeymaster.
37 *
38 * AndroidKeymaster runs in multiple contexts.  Primarily:
39 *
40 * - In a trusted execution environment (TEE) as a "secure hardware" implementation.  In this
41 *   context keys are wrapped with an master key that never leaves the TEE, TEE-specific routines
42 *   are used for random number generation, all AndroidKeymaster-enforced authorizations are
43 *   considered hardware-enforced, and there's a bootloader-provided root of trust.
44 *
45 * - In the non-secure world as a software-only implementation.  In this context keys are not
46 *   encrypted (though they are integrity-checked) because there is no place to securely store a
47 *   key, OpenSSL is used for random number generation, no AndroidKeymaster-enforced authorizations
48 *   are considered hardware enforced and the root of trust is a static string.
49 *
50 * - In the non-secure world as a hybrid implementation fronting a less-capable hardware
51 *   implementation.  For example, a keymaster0 hardware implementation.  In this context keys are
52 *   not encrypted by AndroidKeymaster, but some may be opaque blobs provided by the backing
53 *   hardware, but blobs that lack the extended authorization lists of keymaster1.  In addition,
54 *   keymaster0 lacks many features of keymaster1, including modes of operation related to the
55 *   backing keymaster0 keys.  AndroidKeymaster must extend the blobs to add authorization lists,
56 *   and must provide the missing operation mode implementations in software, which means that
57 *   authorization lists are partially hardware-enforced (the bits that are enforced by the
58 *   underlying keymaster0) and partially software-enforced (the rest). OpenSSL is used for number
59 *   generation and the root of trust is a static string.
60 *
61 * More contexts are possible.
62 */
63class KeymasterContext {
64  public:
65    KeymasterContext() {}
66    virtual ~KeymasterContext(){};
67
68    /**
69     * Returns the security level (SW or TEE) of this keymaster implementation.
70     */
71    virtual keymaster_security_level_t GetSecurityLevel() const = 0;
72
73    /**
74     * Sets the system version as reported by the system *itself*.  This is used to verify that the
75     * system believes itself to be running the same version that is reported by the bootloader, in
76     * hardware implementations.  For SoftKeymasterDevice, this sets the version information used.
77     *
78     * If the specified values don't match the bootloader-provided values, this method must return
79     * KM_ERROR_INVALID_ARGUMENT;
80     */
81    virtual keymaster_error_t SetSystemVersion(uint32_t os_version, uint32_t os_patchlevel) = 0;
82
83    /**
84     * Returns the system version.  For hardware-based implementations this will be the value
85     * reported by the bootloader.  For SoftKeymasterDevice it will be the verion information set by
86     * SetSystemVersion above.
87     */
88    virtual void GetSystemVersion(uint32_t* os_version, uint32_t* os_patchlevel) const = 0;
89
90    virtual KeyFactory* GetKeyFactory(keymaster_algorithm_t algorithm) const = 0;
91    virtual OperationFactory* GetOperationFactory(keymaster_algorithm_t algorithm,
92                                                  keymaster_purpose_t purpose) const = 0;
93    virtual keymaster_algorithm_t* GetSupportedAlgorithms(size_t* algorithms_count) const = 0;
94
95    /**
96     * CreateKeyBlob takes authorization sets and key material and produces a key blob and hardware
97     * and software authorization lists ready to be returned to the AndroidKeymaster client
98     * (Keystore, generally).  The blob is integrity-checked and may be encrypted, depending on the
99     * needs of the context.
100    *
101     * This method is generally called only by KeyFactory subclassses.
102     */
103    virtual keymaster_error_t CreateKeyBlob(const AuthorizationSet& key_description,
104                                            keymaster_key_origin_t origin,
105                                            const KeymasterKeyBlob& key_material,
106                                            KeymasterKeyBlob* blob, AuthorizationSet* hw_enforced,
107                                            AuthorizationSet* sw_enforced) const = 0;
108
109    /**
110     * UpgradeKeyBlob takes an existing blob, parses out key material and constructs a new blob with
111     * the current format and OS version info.
112     */
113    virtual keymaster_error_t UpgradeKeyBlob(const KeymasterKeyBlob& key_to_upgrade,
114                                             const AuthorizationSet& upgrade_params,
115                                             KeymasterKeyBlob* upgraded_key) const = 0;
116
117    /**
118     * ParseKeyBlob takes a blob and extracts authorization sets and key material, returning an
119     * error if the blob fails integrity checking or decryption.  Note that the returned key
120     * material may itself be an opaque blob usable only by secure hardware (in the hybrid case).
121     *
122     * This method is called by AndroidKeymaster.
123     */
124    virtual keymaster_error_t ParseKeyBlob(const KeymasterKeyBlob& blob,
125                                           const AuthorizationSet& additional_params,
126                                           KeymasterKeyBlob* key_material,
127                                           AuthorizationSet* hw_enforced,
128                                           AuthorizationSet* sw_enforced) const = 0;
129
130    /**
131     * Take whatever environment-specific action is appropriate (if any) to delete the specified
132     * key.
133     */
134    virtual keymaster_error_t DeleteKey(const KeymasterKeyBlob& /* blob */) const {
135        return KM_ERROR_OK;
136    }
137
138    /**
139     * Take whatever environment-specific action is appropriate to delete all keys.
140     */
141    virtual keymaster_error_t DeleteAllKeys() const { return KM_ERROR_OK; }
142
143    /**
144     * Adds entropy to the Cryptographic Pseudo Random Number Generator used to generate key
145     * material, and other cryptographic protocol elements.  Note that if the underlying CPRNG
146     * tracks the size of its entropy pool, it should not assume that the provided data contributes
147     * any entropy, and it should also ensure that data provided through this interface cannot
148     * "poison" the CPRNG outputs, making them predictable.
149     */
150    virtual keymaster_error_t AddRngEntropy(const uint8_t* buf, size_t length) const = 0;
151
152    /**
153     * Generates \p length random bytes, placing them in \p buf.
154     */
155    virtual keymaster_error_t GenerateRandom(uint8_t* buf, size_t length) const = 0;
156
157    /**
158     * Return the enforcement policy for this context, or null if no enforcement should be done.
159     */
160    virtual KeymasterEnforcement* enforcement_policy() = 0;
161
162    /**
163     * Return the attestation signing key of the specified algorithm (KM_ALGORITHM_RSA or
164     * KM_ALGORITHM_EC).  Caller acquires ownership and should free using EVP_PKEY_free.
165     */
166    virtual EVP_PKEY* AttestationKey(keymaster_algorithm_t algorithm,
167                                     keymaster_error_t* error) const = 0;
168
169    /**
170     * Return the certificate chain of the attestation signing key of the specified algorithm
171     * (KM_ALGORITHM_RSA or KM_ALGORITHM_EC).  Caller acquires ownership and should free.
172     */
173    virtual keymaster_cert_chain_t* AttestationChain(keymaster_algorithm_t algorithm,
174                                                     keymaster_error_t* error) const = 0;
175
176    /**
177     * Generate the current unique ID.
178     */
179    virtual keymaster_error_t GenerateUniqueId(uint64_t creation_date_time,
180                                               const keymaster_blob_t& application_id,
181                                               bool reset_since_rotation,
182                                               Buffer* unique_id) const = 0;
183
184    /**
185     * Verify that the device IDs provided in the attestation_params match the device's actual IDs
186     * and copy them to attestation. If *any* of the IDs do not match or verification is not
187     * possible, return KM_ERROR_CANNOT_ATTEST_IDS. If *all* IDs provided are successfully verified
188     * or no IDs were provided, return KM_ERROR_OK.
189     *
190     * If you do not support device ID attestation, ignore all arguments and return
191     * KM_ERROR_UNIMPLEMENTED.
192     */
193    virtual keymaster_error_t VerifyAndCopyDeviceIds(
194        const AuthorizationSet& /* attestation_params */,
195        AuthorizationSet* /* attestation */) const {
196        return KM_ERROR_UNIMPLEMENTED;
197    }
198
199    /**
200     * Returns verified boot parameters for the Attestation Extension.  For hardware-based
201     * implementations, these will be the values reported by the bootloader. By default,  verified
202     * boot state is unknown, and KM_ERROR_UNIMPLEMENTED is returned.
203     */
204    virtual keymaster_error_t
205    GetVerifiedBootParams(keymaster_blob_t* /* verified_boot_key */,
206                          keymaster_verified_boot_t* /* verified_boot_state */,
207                          bool* /* device_locked */) const {
208        return KM_ERROR_UNIMPLEMENTED;
209    }
210
211  private:
212    // Uncopyable.
213    KeymasterContext(const KeymasterContext&);
214    void operator=(const KeymasterContext&);
215};
216
217}  // namespace keymaster
218
219#endif  // SYSTEM_KEYMASTER_KEYMASTER_CONTEXT_H_
220