• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <keymaster/key_blob_utils/ocb_utils.h>
18 
19 #include <assert.h>
20 
21 #include <openssl/aes.h>
22 #include <openssl/sha.h>
23 
24 #include <hardware/keymaster_defs.h>
25 
26 #include <keymaster/android_keymaster_utils.h>
27 #include <keymaster/authorization_set.h>
28 #include <keymaster/km_openssl/openssl_err.h>
29 
30 namespace keymaster {
31 
32 class AeCtx {
33   public:
AeCtx()34     AeCtx() : ctx_(ae_allocate(nullptr)) {}
~AeCtx()35     ~AeCtx() {
36         ae_clear(ctx_);
37         ae_free(ctx_);
38     }
39 
get()40     ae_ctx* get() { return ctx_; }
41 
42   private:
43     ae_ctx* ctx_;
44 };
45 
BuildDerivationData(const AuthorizationSet & hw_enforced,const AuthorizationSet & sw_enforced,const AuthorizationSet & hidden,UniquePtr<uint8_t[]> * derivation_data,size_t * derivation_data_length)46 static keymaster_error_t BuildDerivationData(const AuthorizationSet& hw_enforced,
47                                              const AuthorizationSet& sw_enforced,
48                                              const AuthorizationSet& hidden,
49                                              UniquePtr<uint8_t[]>* derivation_data,
50                                              size_t* derivation_data_length) {
51     *derivation_data_length =
52         hidden.SerializedSize() + hw_enforced.SerializedSize() + sw_enforced.SerializedSize();
53     derivation_data->reset(new (std::nothrow) uint8_t[*derivation_data_length]);
54     if (!derivation_data->get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
55 
56     uint8_t* buf = derivation_data->get();
57     uint8_t* end = derivation_data->get() + *derivation_data_length;
58     buf = hidden.Serialize(buf, end);
59     buf = hw_enforced.Serialize(buf, end);
60     buf = sw_enforced.Serialize(buf, end);
61 
62     return KM_ERROR_OK;
63 }
64 
InitializeKeyWrappingContext(const AuthorizationSet & hw_enforced,const AuthorizationSet & sw_enforced,const AuthorizationSet & hidden,const KeymasterKeyBlob & master_key,AeCtx * ctx)65 static keymaster_error_t InitializeKeyWrappingContext(const AuthorizationSet& hw_enforced,
66                                                       const AuthorizationSet& sw_enforced,
67                                                       const AuthorizationSet& hidden,
68                                                       const KeymasterKeyBlob& master_key,
69                                                       AeCtx* ctx) {
70     size_t derivation_data_length;
71     UniquePtr<uint8_t[]> derivation_data;
72     keymaster_error_t error = BuildDerivationData(hw_enforced, sw_enforced, hidden,
73                                                   &derivation_data, &derivation_data_length);
74     if (error != KM_ERROR_OK) return error;
75 
76     SHA256_CTX sha256_ctx;
77     UniquePtr<uint8_t[]> hash_buf(new (std::nothrow) uint8_t[SHA256_DIGEST_LENGTH]);
78     if (!hash_buf.get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
79     Eraser hash_eraser(hash_buf.get(), SHA256_DIGEST_LENGTH);
80     UniquePtr<uint8_t[]> derived_key(new (std::nothrow) uint8_t[AES_BLOCK_SIZE]);
81     if (!derived_key.get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
82     Eraser derived_key_eraser(derived_key.get(), AES_BLOCK_SIZE);
83 
84     if (!ctx->get() || !hash_buf.get() || !derived_key.get())
85         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
86 
87     // Hash derivation data.
88     Eraser sha256_ctx_eraser(sha256_ctx);
89     SHA256_Init(&sha256_ctx);
90     SHA256_Update(&sha256_ctx, derivation_data.get(), derivation_data_length);
91     SHA256_Final(hash_buf.get(), &sha256_ctx);
92 
93     // Encrypt hash with master key to build derived key.
94     AES_KEY aes_key;
95     Eraser aes_key_eraser(AES_KEY);
96     if (0 !=
97         AES_set_encrypt_key(master_key.key_material, master_key.key_material_size * 8, &aes_key))
98         return TranslateLastOpenSslError();
99 
100     AES_encrypt(hash_buf.get(), derived_key.get(), &aes_key);
101 
102     // Set up AES OCB context using derived key.
103     if (ae_init(ctx->get(), derived_key.get(), AES_BLOCK_SIZE /* key length */, OCB_NONCE_LENGTH,
104                 OCB_TAG_LENGTH) != AE_SUCCESS) {
105         memset_s(ctx->get(), 0, ae_ctx_sizeof());
106         return KM_ERROR_UNKNOWN_ERROR;
107     }
108 
109     return KM_ERROR_OK;
110 }
111 
OcbEncryptKey(const AuthorizationSet & hw_enforced,const AuthorizationSet & sw_enforced,const AuthorizationSet & hidden,const KeymasterKeyBlob & master_key,const KeymasterKeyBlob & plaintext,const Buffer & nonce,KeymasterKeyBlob * ciphertext,Buffer * tag)112 keymaster_error_t OcbEncryptKey(const AuthorizationSet& hw_enforced,
113                                 const AuthorizationSet& sw_enforced, const AuthorizationSet& hidden,
114                                 const KeymasterKeyBlob& master_key,
115                                 const KeymasterKeyBlob& plaintext, const Buffer& nonce,
116                                 KeymasterKeyBlob* ciphertext, Buffer* tag) {
117     assert(ciphertext && tag);
118 
119     if (nonce.available_read() != OCB_NONCE_LENGTH) return KM_ERROR_INVALID_ARGUMENT;
120     if (tag->available_write() != OCB_TAG_LENGTH) return KM_ERROR_INVALID_ARGUMENT;
121 
122     AeCtx ctx;
123     if (!ctx.get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
124 
125     keymaster_error_t error =
126         InitializeKeyWrappingContext(hw_enforced, sw_enforced, hidden, master_key, &ctx);
127     if (error != KM_ERROR_OK) return error;
128 
129     if (!ciphertext->Reset(plaintext.key_material_size)) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
130 
131     int ae_err = ae_encrypt(ctx.get(), nonce.peek_read(), plaintext.key_material,
132                             plaintext.key_material_size, nullptr /* additional data */,
133                             0 /* additional data length */, ciphertext->writable_data(),
134                             tag->peek_write(), 1 /* final */);
135     if (ae_err < 0) {
136         LOG_E("Error %d while encrypting key", ae_err);
137         return KM_ERROR_UNKNOWN_ERROR;
138     }
139     if (!tag->advance_write(OCB_TAG_LENGTH)) return KM_ERROR_UNKNOWN_ERROR;
140     assert(ae_err == static_cast<int>(plaintext.key_material_size));
141     return KM_ERROR_OK;
142 }
143 
OcbDecryptKey(const AuthorizationSet & hw_enforced,const AuthorizationSet & sw_enforced,const AuthorizationSet & hidden,const KeymasterKeyBlob & master_key,const KeymasterKeyBlob & ciphertext,const Buffer & nonce,const Buffer & tag,KeymasterKeyBlob * plaintext)144 keymaster_error_t OcbDecryptKey(const AuthorizationSet& hw_enforced,
145                                 const AuthorizationSet& sw_enforced, const AuthorizationSet& hidden,
146                                 const KeymasterKeyBlob& master_key,
147                                 const KeymasterKeyBlob& ciphertext, const Buffer& nonce,
148                                 const Buffer& tag, KeymasterKeyBlob* plaintext) {
149     assert(plaintext);
150 
151     if (nonce.available_read() != OCB_NONCE_LENGTH || tag.available_read() != OCB_TAG_LENGTH)
152         return KM_ERROR_INVALID_ARGUMENT;
153 
154     AeCtx ctx;
155     if (!ctx.get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
156 
157     keymaster_error_t error =
158         InitializeKeyWrappingContext(hw_enforced, sw_enforced, hidden, master_key, &ctx);
159     if (error != KM_ERROR_OK) return error;
160 
161     if (!plaintext->Reset(ciphertext.key_material_size)) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
162 
163     int ae_err = ae_decrypt(ctx.get(), nonce.peek_read(), ciphertext.key_material,
164                             ciphertext.key_material_size, nullptr /* additional data */,
165                             0 /* additional data length */, plaintext->writable_data(),
166                             tag.peek_read(), 1 /* final */);
167     if (ae_err == AE_INVALID) {
168         // Authentication failed!  Decryption probably succeeded(ish), but we don't want to return
169         // any data when the authentication fails, so clear it.
170         plaintext->Clear();
171         LOG_E("Failed to validate authentication tag during key decryption", 0);
172         return KM_ERROR_INVALID_KEY_BLOB;
173     } else if (ae_err < 0) {
174         LOG_E("Failed to decrypt key, error: %d", ae_err);
175         return KM_ERROR_UNKNOWN_ERROR;
176     }
177     assert(ae_err == static_cast<int>(ciphertext.key_material_size));
178     return KM_ERROR_OK;
179 }
180 
181 }  // namespace keymaster
182