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