/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.hardware.keymaster@4.0; import android.hardware.keymaster@3.0::ErrorCode; import android.hardware.keymaster@3.0::KeyFormat; /** * Keymaster device definition. For thorough documentation see the implementer's reference, at * https://source.android.com/security/keystore/implementer-ref.html */ interface IKeymasterDevice { /** * Returns information about the underlying Keymaster hardware. * * @return security level of the Keymaster implementation accessed through this HAL. * * @return keymasterName is the name of the Keymaster implementation. * * @return keymasterAuthorName is the name of the author of the Keymaster implementation * (organization name, not individual). */ getHardwareInfo() generates (SecurityLevel securityLevel, string keymasterName, string keymasterAuthorName); /** * Start the creation of an HMAC key, shared with another Keymaster implementation. Any device * with a StrongBox Keymaster has two Keymaster instances, because there must be a TEE Keymaster * as well. The HMAC key used to MAC and verify authentication tokens must be shared between * TEE and StrongBox so they can each validate tokens produced by the other. This method is the * first step in the process for for agreeing on a shared key. It is called by Keystore during * startup if and only if Keystore loads multiple Keymaster HALs. Keystore calls it on each of * the HAL instances and collects the results in preparation for the second step. */ getHmacSharingParameters() generates (ErrorCode error, HmacSharingParameters params); /** * Complete the creation of an HMAC key, shared with another Keymaster implementation. Any * device with a StrongBox Keymaster has two Keymasters instances, because there must be a TEE * Keymaster as well. The HMAC key used to MAC and verify authentication tokens must be shared * between TEE and StrongBox so they can each validate tokens produced by the other. This * method is the second and final step in the process for agreeing on a shared key. It is * called by Keystore during startup if and only if Keystore loads multiple Keymaster HALs. * Keystore calls it on each of the HAL instances, and sends to it all of the * HmacSharingParameters returned by all HALs. * * This method computes the shared 32-byte HMAC ``H'' as follows (all Keymaster instances * perform the same computation to arrive at the same result): * * H = CKDF(key = K, * context = P1 || P2 || ... || Pn, * label = "KeymasterSharedMac") * * where: * * ``CKDF'' is the standard AES-CMAC KDF from NIST SP 800-108 in counter mode (see Section * 5.1 of the referenced publication). ``key'', ``context'', and ``label'' are * defined in the standard. The counter is prefixed, as shown in the construction on * page 12 of the standard. The label string is UTF-8 encoded. * * ``K'' is a pre-established shared secret, set up during factory reset. The mechanism for * establishing this shared secret is implementation-defined, but see below for a * recommended approach, which assumes that the TEE Keymaster does not have storage * available to it, but the StrongBox Keymaster does. * * CRITICAL SECURITY REQUIREMENT: All keys created by a Keymaster instance must * be cryptographically bound to the value of K, such that establishing a new K * permanently destroys them. * * ``||'' represents concatenation. * * ``Pi'' is the i'th HmacSharingParameters value in the params vector. Note that at * present only two Keymaster implementations are supported, but this mechanism * extends without modification to any number of implementations. Encoding of an * HmacSharingParameters is the concatenation of its two fields, i.e. seed || nonce. * * Process for establishing K: * * Any method of securely establishing K that ensures that an attacker cannot obtain or * derive its value is acceptable. What follows is a recommended approach, to be executed * during each factory reset. It relies on use of the factory-installed attestation keys to * mitigate man-in-the-middle attacks. This protocol requires that one of the instances * have secure persistent storage. This model was chosen because StrongBox has secure * persistent storage (by definition), but the TEE may not. The instance without storage is * assumed to be able to derive a unique hardware-bound key (HBK) which is used only for * this purpose, and is not derivable outside of the secure environment.. * * In what follows, T is the Keymaster instance without storage, S is the Keymaster instance * with storage: * * 1. T generates an ephemeral EC P-256 key pair K1 * 2. T sends K1_pub to S, signed with T's attestation key. * 3. S validates the signature on K1_pub. * 4. S generates an ephemeral EC P-256 key pair K2. * 5. S sends {K1_pub, K2_pub}, to T, signed with S's attestation key. * 6. T validates the signature on {K1_pub, K2_pub} * 7. T uses {K1_priv, K2_pub} with ECDH to compute session secret Q. * 8. T generates a random seed S * 9. T computes K = KDF(HBK, S), where KDF is some secure key derivation function. * 10. T sends M = AES-GCM-ENCRYPT(Q, {S || K}) to S. * 10. S uses {K2_priv, K1_pub} with ECDH to compute session secret Q. * 11. S computes S || K = AES-GCM-DECRYPT(Q, M) and stores S and K. * * When S receives the getHmacSharingParameters call, it returns the stored S as the seed * and a nonce. When T receives the same call, it returns an empty seed and a nonce. When * T receives the computeSharedHmac call, it uses the seed provided by S to compute K. S, * of course, has K stored. * * @param params The HmacSharingParameters data returned by all Keymaster instances when * getHmacSharingParameters was called. * * @return sharingCheck A 32-byte value used to verify that all Keymaster instances have * computed the same shared HMAC key. The sharingCheck value is computed as follows: * * sharingCheck = HMAC(H, "Keymaster HMAC Verification") * * The string is UTF-8 encoded. If the returned values of all Keymaster instances don't * match, Keystore will assume that HMAC agreement failed. */ computeSharedHmac(vec params) generates (ErrorCode error, vec sharingCheck); /** * Verify authorizations for another Keymaster instance. * * On systems with both a StrongBox and a TEE Keymaster instance it is sometimes useful to ask * the TEE Keymaster to verify authorizations for a key hosted in StrongBox. * * For every StrongBox operation, Keystore is required to call this method on the TEE Keymaster, * passing in the StrongBox key's hardwareEnforced authorization list and the operation handle * returned by StrongBox begin(). The TEE Keymaster must validate all of the authorizations it * can and return those it validated in the VerificationToken. If it cannot verify any, the * parametersVerified field of the VerificationToken must be empty. Keystore must then pass the * VerificationToken to the subsequent invocations of StrongBox update() and finish(). * * StrongBox implementations must return ErrorCode::UNIMPLEMENTED. * * @param operationHandle the operation handle returned by StrongBox Keymaster's begin(). * * @param parametersToVerify Set of authorizations to verify. * * @param authToken A HardwareAuthToken if needed to authorize key usage. */ verifyAuthorization(uint64_t operationHandle, vec parametersToVerify, HardwareAuthToken authToken) generates (ErrorCode error, VerificationToken token); /** * Adds entropy to the RNG used by Keymaster. Entropy added through this method is guaranteed * not to be the only source of entropy used, and the mixing function is required to be secure, * in the sense that if the RNG is seeded (from any source) with any data the attacker cannot * predict (or control), then the RNG output is indistinguishable from random. Thus, if the * entropy from any source is good, the output must be good. * * @param data Bytes to be mixed into the RNG. * * @return error See the ErrorCode enum in types.hal. */ addRngEntropy(vec data) generates (ErrorCode error); /** * Generates a key, or key pair, returning a key blob and a description of the key. * * @param keyParams Key generation parameters are defined as Keymaster tag/value pairs, provided * in params. See Tag in types.hal for the full list. * * @return error See the ErrorCode enum in types.hal. * * @return keyBlob Opaque, encrypted descriptor of the generated key. A recommended * implementation strategy is to include an encrypted copy of the key material, wrapped * in a key unavailable outside secure hardware. * * @return keyCharacteristics Description of the generated key. See KeyCharacteristis in * types.hal. */ generateKey(vec keyParams) generates (ErrorCode error, vec keyBlob, KeyCharacteristics keyCharacteristics); /** * Imports a key, or key pair, returning a key blob and/or a description of the key. * * @param keyParams Key generation parameters are defined as Keymaster tag/value pairs, provided * in params. See Tag for the full list. * * @param keyFormat The format of the key material to import. * * @pram keyData The key material to import, in the format specifed in keyFormat. * * @return error See the ErrorCode enum. * * @return keyBlob Opaque, encrypted descriptor of the generated key, which will generally * contain a copy of the key material, wrapped in a key unavailable outside secure * hardware. * * @return keyCharacteristics Decription of the generated key. */ importKey(vec keyParams, KeyFormat keyFormat, vec keyData) generates (ErrorCode error, vec keyBlob, KeyCharacteristics keyCharacteristics); /** * Securely imports a key, or key pair, returning a key blob and a description of the imported * key. * * @param wrappedKeyData The wrapped key material to import. The wrapped key is in DER-encoded * ASN.1 format, specified by the following schema: * * KeyDescription ::= SEQUENCE( * keyFormat INTEGER, # Values from KeyFormat enum. * keyParams AuthorizationList, * ) * * SecureKeyWrapper ::= SEQUENCE( * version INTEGER, # Contains value 0 * encryptedTransportKey OCTET_STRING, * initializationVector OCTET_STRING, * keyDescription KeyDescription, * encryptedKey OCTET_STRING, * tag OCTET_STRING * ) * * Where: * * o keyFormat is an integer from the KeyFormat enum, defining the format of the plaintext * key material. * o keyParams is the characteristics of the key to be imported (as with generateKey or * importKey). If the secure import is successful, these characteristics must be * associated with the key exactly as if the key material had been insecurely imported * with the @3.0::IKeymasterDevice::importKey. * o encryptedTransportKey is a 256-bit AES key, XORed with a masking key and then encrypted * in RSA-OAEP mode (SHA-256 digest, SHA-1 MGF1 digest) with the wrapping key specified by * wrappingKeyBlob. * o keyDescription is a KeyDescription, above. * o encryptedKey is the key material of the key to be imported, in format keyFormat, and * encrypted with encryptedEphemeralKey in AES-GCM mode, with the DER-encoded * representation of keyDescription provided as additional authenticated data. * o tag is the tag produced by the AES-GCM encryption of encryptedKey. * * So, importWrappedKey does the following: * * 1. Get the private key material for wrappingKeyBlob, verifying that the wrapping key has * purpose KEY_WRAP, padding mode RSA_OAEP, and digest SHA_2_256, returning the * appropriate error if any of those requirements fail. * 2. Extract the encryptedTransportKey field from the SecureKeyWrapper, and decrypt * it with the wrapping key. * 3. XOR the result of step 2 with maskingKey. * 4. Use the result of step 3 as an AES-GCM key to decrypt encryptedKey, using the encoded * value of keyDescription as the additional authenticated data. Call the result * "keyData" for the next step. * 5. Perform the equivalent of calling importKey(keyParams, keyFormat, keyData), except * that the origin tag should be set to SECURELY_IMPORTED. * * @param wrappingKeyBlob The opaque key descriptor returned by generateKey() or importKey(). * This key must have been created with Purpose::WRAP_KEY, and must be a key algorithm * that supports encryption and must be at least as strong (in key size) as the key to be * imported (per NIST key length recommendations: 112 bits symmetric is equivalent to * 2048-bit RSA or 224-bit EC, 128 bits symmetric ~ 3072-bit RSA or 256-bit EC, etc.). * * @param maskingKey The 32-byte value XOR'd with the transport key in the SecureWrappedKey * structure. * * @param unwrappingParams must contain any parameters needed to perform the unwrapping * operation. For example, if the wrapping key is an AES key the block and padding modes * must be specified in this argument. * * @param passwordSid specifies the password secure ID (SID) of the user that owns the key being * installed. If the authorization list in wrappedKeyData contains a Tag::USER_SECURE_ID * with a value that has the HardwareAuthenticatorType::PASSWORD bit set, the constructed * key must be bound to the SID value provided by this argument. If the wrappedKeyData * does not contain such a tag and value, this argument must be ignored. * * @param biometricSid specifies the biometric secure ID (SID) of the user that owns the key * being installed. If the authorization list in wrappedKeyData contains a * Tag::USER_SECURE_ID with a value that has the HardwareAuthenticatorType::FINGERPRINT * bit set, the constructed key must be bound to the SID value provided by this argument. * If the wrappedKeyData does not contain such a tag and value, this argument must be * ignored. * * @return error See the ErrorCode enum. * * @return keyBlob Opaque descriptor of the imported key. It is recommended that the keyBlob * contain a copy of the key material, wrapped in a key unavailable outside secure * hardware. */ importWrappedKey(vec wrappedKeyData, vec wrappingKeyBlob, vec maskingKey, vec unwrappingParams, uint64_t passwordSid, uint64_t biometricSid) generates(ErrorCode error, vec keyBlob, KeyCharacteristics keyCharacteristics); /** * Returns the characteristics of the specified key, if the keyBlob is valid (implementations * must fully validate the integrity of the key). * * @param keyBlob The opaque descriptor returned by generateKey() or importKey(); * * @param clientId An opaque byte string identifying the client. This value must match the * Tag::APPLICATION_ID data provided during key generation/import. Without the correct * value, it must be computationally infeasible for the secure hardware to obtain the key * material. * * @param appData An opaque byte string provided by the application. This value must match the * Tag::APPLICATION_DATA data provided during key generation/import. Without the correct * value, it must be computationally infeasible for the secure hardware to obtain the key * material. * * @return error See the ErrorCode enum in types.hal. * * @return keyCharacteristics Decription of the generated key. See KeyCharacteristis in * types.hal. */ getKeyCharacteristics(vec keyBlob, vec clientId, vec appData) generates (ErrorCode error, KeyCharacteristics keyCharacteristics); /** * Exports a public key, returning the key in the specified format. * * @parm keyFormat The format used for export. See KeyFormat in types.hal. * * @param keyBlob The opaque descriptor returned by generateKey() or importKey(). The * referenced key must be asymmetric. * * @param clientId An opaque byte string identifying the client. This value must match the * Tag::APPLICATION_ID data provided during key generation/import. Without the correct * value, it must be computationally infeasible for the secure hardware to obtain the key * material. * * @param appData An opaque byte string provided by the application. This value must match the * Tag::APPLICATION_DATA data provided during key generation/import. Without the correct * value, it must be computationally infeasible for the secure hardware to obtain the key * material. * * @return error See the ErrorCode enum in types.hal. * * @return keyMaterial The public key material in PKCS#8 format. */ exportKey(KeyFormat keyFormat, vec keyBlob, vec clientId, vec appData) generates (ErrorCode error, vec keyMaterial); /** * Generates a signed X.509 certificate chain attesting to the presence of keyToAttest in * Keymaster. The certificate must contain an extension with OID 1.3.6.1.4.1.11129.2.1.17 and * value defined in: * * https://developer.android.com/training/articles/security-key-attestation.html. * * @param keyToAttest The opaque descriptor returned by generateKey() or importKey(). The * referenced key must be asymmetric. * * @param attestParams Parameters for the attestation, notably Tag::ATTESTATION_CHALLENGE. * * @return error See the ErrorCode enum in types.hal. * * @return certChain The attestation certificate, and additional certificates back to the root * attestation certificate, which clients will need to check against a known-good value. */ attestKey(vec keyToAttest, vec attestParams) generates (ErrorCode error, vec> certChain); /** * Upgrades an old key blob. Keys can become "old" in two ways: Keymaster can be upgraded to a * new version with an incompatible key blob format, or the system can be updated to invalidate * the OS version (OS_VERSION tag), system patch level (OS_PATCHLEVEL tag), vendor patch level * (VENDOR_PATCH_LEVEL tag), boot patch level (BOOT_PATCH_LEVEL tag) or other, * implementation-defined patch level (keymaster implementers are encouraged to extend this HAL * with a minor version extension to define validatable patch levels for other images; tags * must be defined in the implemeter's namespace, starting at 10000). In either case, * attempts to use an old key blob with getKeyCharacteristics(), exportKey(), attestKey() or * begin() must result in Keymaster returning ErrorCode::KEY_REQUIRES_UPGRADE. The caller must * use this method to upgrade the key blob. * * If upgradeKey is asked to update a key with any version or patch level that is higher than * the current system version or patch level, it must return ErrorCode::INVALID_ARGUMENT. There * is one exception: it is always permissible to "upgrade" from any OS_VERSION number to * OS_VERSION 0. For example, if the key has OS_VERSION 080001, it is permisible to upgrade the * key if the current system version is 080100, because the new version is larger, or if the * current system version is 0, because upgrades to 0 are always allowed. If the system version * were 080000, however, keymaster must return ErrorCode::INVALID_ARGUMENT because that value is * smaller than 080001. * * Note that Keymaster versions 2 and 3 required that the system and boot images have the same * patch level and OS version. This requirement is relaxed for Keymaster 4, and the OS version * in the boot image footer is no longer used. * * @param keyBlobToUpgrade The opaque descriptor returned by generateKey() or importKey(); * * @param upgradeParams A parameter list containing any parameters needed to complete the * upgrade, including Tag::APPLICATION_ID and Tag::APPLICATION_DATA. * * @return error See the ErrorCode enum. * * @return upgradedKeyBlob A new key blob that references the same key as keyBlobToUpgrade, but * is in the new format, or has the new version data. */ upgradeKey(vec keyBlobToUpgrade, vec upgradeParams) generates (ErrorCode error, vec upgradedKeyBlob); /** * Deletes the key, or key pair, associated with the key blob. Calling this function on a key * with Tag::ROLLBACK_RESISTANCE in its hardware-enforced authorization list must render the key * permanently unusable. Keys without Tag::ROLLBACK_RESISTANCE may or may not be rendered * unusable. * * @param keyBlob The opaque descriptor returned by generateKey() or importKey(); * * @return error See the ErrorCode enum. */ deleteKey(vec keyBlob) generates (ErrorCode error); /** * Deletes all keys in the hardware keystore. Used when keystore is reset completely. After * this function is called all keys with Tag::ROLLBACK_RESISTANCE in their hardware-enforced * authorization lists must be rendered permanently unusable. Keys without * Tag::ROLLBACK_RESISTANCE may or may not be rendered unusable. * * @return error See the ErrorCode enum. */ deleteAllKeys() generates (ErrorCode error); /** * Destroys knowledge of the device's ids. This prevents all device id attestation in the * future. The destruction must be permanent so that not even a factory reset will restore the * device ids. * * Device id attestation may be provided only if this method is fully implemented, allowing the * user to permanently disable device id attestation. If this cannot be guaranteed, the device * must never attest any device ids. * * This is a NOP if device id attestation is not supported. * * @return error See the ErrorCode enum. */ destroyAttestationIds() generates (ErrorCode error); /** * Begins a cryptographic operation using the specified key. If all is well, begin() must * return ErrorCode::OK and create an operation handle which must be passed to subsequent calls * to update(), finish() or abort(). * * It is critical that each call to begin() be paired with a subsequent call to finish() or * abort(), to allow the Keymaster implementation to clean up any internal operation state. The * caller's failure to do this may leak internal state space or other internal resources and may * eventually cause begin() to return ErrorCode::TOO_MANY_OPERATIONS when it runs out of space * for operations. Any result other than ErrorCode::OK from begin(), update() or finish() * implicitly aborts the operation, in which case abort() need not be called (and must return * ErrorCode::INVALID_OPERATION_HANDLE if called). * * @param purpose The purpose of the operation, one of KeyPurpose::ENCRYPT, KeyPurpose::DECRYPT, * KeyPurpose::SIGN or KeyPurpose::VERIFY. Note that for AEAD modes, encryption and * decryption imply signing and verification, respectively, but must be specified as * KeyPurpose::ENCRYPT and KeyPurpose::DECRYPT. * * @param keyBlob The opaque key descriptor returned by generateKey() or importKey(). The key * must have a purpose compatible with purpose and all of its usage requirements must be * satisfied, or begin() must return an appropriate error code. * * @param inParams Additional parameters for the operation. If Tag::APPLICATION_ID or * Tag::APPLICATION_DATA were provided during generation, they must be provided here, or * the operation must fail with ErrorCode::INVALID_KEY_BLOB. For operations that require * a nonce or IV, on keys that were generated with Tag::CALLER_NONCE, inParams may * contain a tag Tag::NONCE. If Tag::NONCE is provided for a key without * Tag:CALLER_NONCE, ErrorCode::CALLER_NONCE_PROHIBITED must be returned. * * @param authToken Authentication token. Callers that provide no token must set all numeric * fields to zero and the MAC must be an empty vector. * * @return error See the ErrorCode enum in types.hal. * * @return outParams Output parameters. Used to return additional data from the operation * initialization, notably to return the IV or nonce from operations that generate an IV * or nonce. * * @return operationHandle The newly-created operation handle which must be passed to update(), * finish() or abort(). */ begin(KeyPurpose purpose, vec keyBlob, vec inParams, HardwareAuthToken authToken) generates (ErrorCode error, vec outParams, OperationHandle operationHandle); /** * Provides data to, and possibly receives output from, an ongoing cryptographic operation begun * with begin(). * * If operationHandle is invalid, update() must return ErrorCode::INVALID_OPERATION_HANDLE. * * update() may not consume all of the data provided in the data buffer. update() must return * the amount consumed in inputConsumed. The caller may provide the unconsumed data in a * subsequent call. * * @param operationHandle The operation handle returned by begin(). * * @param inParams Additional parameters for the operation. For AEAD modes, this is used to * specify Tag::ADDITIONAL_DATA. Note that additional data may be provided in multiple * calls to update(), but only until input data has been provided. * * @param input Data to be processed. Note that update() may or may not consume all of the data * provided. See inputConsumed. * * @param authToken Authentication token. Callers that provide no token must set all numeric * fields to zero and the MAC must be an empty vector. * * @param verificationToken Verification token, used to prove that another Keymaster HAL has * verified some parameters, and to deliver the other HAL's current timestamp, if needed. * If not provided, all fields must be initialized to zero and vectors empty. * * @return error See the ErrorCode enum in types.hal. * * @return inputConsumed Amount of data that was consumed by update(). If this is less than the * amount provided, the caller may provide the remainder in a subsequent call to * update() or finish(). Every call to update must consume at least one byte, and * implementations should consume as much data as reasonably possible for each call. * * @return outParams Output parameters, used to return additional data from the operation. * * @return output The output data, if any. */ update(OperationHandle operationHandle, vec inParams, vec input, HardwareAuthToken authToken, VerificationToken verificationToken) generates (ErrorCode error, uint32_t inputConsumed, vec outParams, vec output); /** * Finalizes a cryptographic operation begun with begin() and invalidates operationHandle. * * @param operationHandle The operation handle returned by begin(). This handle must be invalid * when finish() returns. * * @param inParams Additional parameters for the operation. For AEAD modes, this is used to * specify Tag::ADDITIONAL_DATA, but only if no input data was provided to update(). * * @param input Data to be processed, per the parameters established in the call to begin(). * finish() must consume all provided data or return ErrorCode::INVALID_INPUT_LENGTH. * * @param signature The signature to be verified if the purpose specified in the begin() call * was KeyPurpose::VERIFY. * * @param authToken Authentication token. Callers that provide no token must set all numeric * fields to zero and the MAC must be an empty vector. * * @param verificationToken Verification token, used to prove that another Keymaster HAL has * verified some parameters, and to deliver the other HAL's current timestamp, if needed. * If not provided, all fields must be initialized to zero and vectors empty. * * @return error See the ErrorCode enum in types.hal. * * @return outParams Any output parameters generated by finish(). * * @return output The output data, if any. */ finish(OperationHandle operationHandle, vec inParams, vec input, vec signature, HardwareAuthToken authToken, VerificationToken verificationToken) generates (ErrorCode error, vec outParams, vec output); /** * Aborts a cryptographic operation begun with begin(), freeing all internal resources and * invalidating operationHandle. * * @param operationHandle The operation handle returned by begin(). This handle must be * invalid when abort() returns. * * @return error See the ErrorCode enum in types.hal. */ abort(OperationHandle operationHandle) generates (ErrorCode error); };