blob: 8c52e4c67cb17f19ac69bdc31f34981c0d03165a [file] [log] [blame]
Joel Galensonca0efb12020-10-01 14:32:30 -07001/*
2 * Copyright (C) 2020 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#define LOG_TAG "keystore2"
18
19#include "crypto.hpp"
20
21#include <log/log.h>
22#include <openssl/aes.h>
23#include <openssl/evp.h>
24
25#include <vector>
26
27// Copied from system/security/keystore/blob.h.
28
29constexpr size_t kGcmTagLength = 128 / 8;
30constexpr size_t kAes128KeySizeBytes = 128 / 8;
31
32// Copied from system/security/keystore/blob.cpp.
33
34#if defined(__clang__)
35#define OPTNONE __attribute__((optnone))
36#elif defined(__GNUC__)
37#define OPTNONE __attribute__((optimize("O0")))
38#else
39#error Need a definition for OPTNONE
40#endif
41
42class ArrayEraser {
43 public:
44 ArrayEraser(uint8_t* arr, size_t size) : mArr(arr), mSize(size) {}
45 OPTNONE ~ArrayEraser() { std::fill(mArr, mArr + mSize, 0); }
46
47 private:
48 volatile uint8_t* mArr;
49 size_t mSize;
50};
51
52/**
53 * Returns a EVP_CIPHER appropriate for the given key size.
54 */
55const EVP_CIPHER* getAesCipherForKey(size_t key_size) {
56 const EVP_CIPHER* cipher = EVP_aes_256_gcm();
57 if (key_size == kAes128KeySizeBytes) {
58 cipher = EVP_aes_128_gcm();
59 }
60 return cipher;
61}
62
63/*
64 * Encrypt 'len' data at 'in' with AES-GCM, using 128-bit or 256-bit key at 'key', 96-bit IV at
65 * 'iv' and write output to 'out' (which may be the same location as 'in') and 128-bit tag to
66 * 'tag'.
67 */
68bool AES_gcm_encrypt(const uint8_t* in, uint8_t* out, size_t len, const uint8_t* key,
69 size_t key_size, const uint8_t* iv, uint8_t* tag) {
70
71 // There can be 128-bit and 256-bit keys
72 const EVP_CIPHER* cipher = getAesCipherForKey(key_size);
73
74 bssl::UniquePtr<EVP_CIPHER_CTX> ctx(EVP_CIPHER_CTX_new());
75
76 EVP_EncryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key, iv);
77 EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */);
78
79 std::vector<uint8_t> out_tmp(len);
80 uint8_t* out_pos = out_tmp.data();
81 int out_len;
82
83 EVP_EncryptUpdate(ctx.get(), out_pos, &out_len, in, len);
84 out_pos += out_len;
85 EVP_EncryptFinal_ex(ctx.get(), out_pos, &out_len);
86 out_pos += out_len;
87 if (out_pos - out_tmp.data() != static_cast<ssize_t>(len)) {
88 ALOGD("Encrypted ciphertext is the wrong size, expected %zu, got %zd", len,
89 out_pos - out_tmp.data());
90 return false;
91 }
92
93 std::copy(out_tmp.data(), out_pos, out);
94 EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, kGcmTagLength, tag);
95
96 return true;
97}
98
99/*
100 * Decrypt 'len' data at 'in' with AES-GCM, using 128-bit or 256-bit key at 'key', 96-bit IV at
101 * 'iv', checking 128-bit tag at 'tag' and writing plaintext to 'out'(which may be the same
102 * location as 'in').
103 */
104bool AES_gcm_decrypt(const uint8_t* in, uint8_t* out, size_t len, const uint8_t* key,
105 size_t key_size, const uint8_t* iv, const uint8_t* tag) {
106
107 // There can be 128-bit and 256-bit keys
108 const EVP_CIPHER* cipher = getAesCipherForKey(key_size);
109
110 bssl::UniquePtr<EVP_CIPHER_CTX> ctx(EVP_CIPHER_CTX_new());
111
112 EVP_DecryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key, iv);
113 EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */);
114 EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, kGcmTagLength, const_cast<uint8_t*>(tag));
115
116 std::vector<uint8_t> out_tmp(len);
117 ArrayEraser out_eraser(out_tmp.data(), len);
118 uint8_t* out_pos = out_tmp.data();
119 int out_len;
120
121 EVP_DecryptUpdate(ctx.get(), out_pos, &out_len, in, len);
122 out_pos += out_len;
123 if (!EVP_DecryptFinal_ex(ctx.get(), out_pos, &out_len)) {
124 ALOGE("Failed to decrypt blob; ciphertext or tag is likely corrupted");
125 return false;
126 }
127 out_pos += out_len;
128 if (out_pos - out_tmp.data() != static_cast<ssize_t>(len)) {
129 ALOGE("Encrypted plaintext is the wrong size, expected %zu, got %zd", len,
130 out_pos - out_tmp.data());
131 return false;
132 }
133
134 std::copy(out_tmp.data(), out_pos, out);
135
136 return true;
137}
138
139// Copied from system/security/keystore/keymaster_enforcement.cpp.
140
141class EvpMdCtx {
142 public:
143 EvpMdCtx() { EVP_MD_CTX_init(&ctx_); }
144 ~EvpMdCtx() { EVP_MD_CTX_cleanup(&ctx_); }
145
146 EVP_MD_CTX* get() { return &ctx_; }
147
148 private:
149 EVP_MD_CTX ctx_;
150};
151
152bool CreateKeyId(const uint8_t* key_blob, size_t len, km_id_t* out_id) {
153 EvpMdCtx ctx;
154
155 uint8_t hash[EVP_MAX_MD_SIZE];
156 unsigned int hash_len;
157 if (EVP_DigestInit_ex(ctx.get(), EVP_sha256(), nullptr /* ENGINE */) &&
158 EVP_DigestUpdate(ctx.get(), key_blob, len) &&
159 EVP_DigestFinal_ex(ctx.get(), hash, &hash_len)) {
160 assert(hash_len >= sizeof(*out_id));
161 memcpy(out_id, hash, sizeof(*out_id));
162 return true;
163 }
164
165 return false;
166}
167
168// Copied from system/security/keystore/user_state.h
169
170static constexpr size_t SALT_SIZE = 16;
171
172// Copied from system/security/keystore/user_state.cpp.
173
174void generateKeyFromPassword(uint8_t* key, size_t key_len, const char* pw, size_t pw_len,
175 uint8_t* salt) {
176 size_t saltSize;
177 if (salt != nullptr) {
178 saltSize = SALT_SIZE;
179 } else {
180 // Pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
181 salt = (uint8_t*)"keystore";
182 // sizeof = 9, not strlen = 8
183 saltSize = sizeof("keystore");
184 }
185
186 const EVP_MD* digest = EVP_sha256();
187
188 // SHA1 was used prior to increasing the key size
189 if (key_len == kAes128KeySizeBytes) {
190 digest = EVP_sha1();
191 }
192
193 PKCS5_PBKDF2_HMAC(pw, pw_len, salt, saltSize, 8192, digest, key_len, key);
194}