1 /*
2  * Copyright (C) 2016 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 // TODO(154013771): this is copied from vold and modified to remove un-needed
18 // methods and use std::string instead of KeyBuffer. We should instead
19 // create a library to support both.
20 
21 #include "Keymaster.h"
22 
23 #include <android-base/logging.h>
24 
25 #include <aidl/android/hardware/security/keymint/SecurityLevel.h>
26 #include <aidl/android/system/keystore2/Domain.h>
27 #include <aidl/android/system/keystore2/EphemeralStorageKeyResponse.h>
28 #include <aidl/android/system/keystore2/KeyDescriptor.h>
29 
30 // Keep these in sync with system/security/keystore2/src/keystore2_main.rs
31 static constexpr const char keystore2_service_name[] =
32     "android.system.keystore2.IKeystoreService/default";
33 
34 // Keep this in sync with system/sepolicy/private/keystore2_key_contexts
35 static constexpr const int ROOT_NAMESPACE = 0;
36 
37 namespace android {
38 namespace kernel {
39 
zeroize_vector(std::vector<uint8_t> & vec)40 static void zeroize_vector(std::vector<uint8_t>& vec) {
41   // Not secure, but doesn't really matter since this is just test code.
42   memset(vec.data(), 0, vec.size());
43 }
44 
logKeystore2ExceptionIfPresent(::ndk::ScopedAStatus & rc,const std::string & func_name)45 static bool logKeystore2ExceptionIfPresent(::ndk::ScopedAStatus& rc,
46                                            const std::string& func_name) {
47   if (rc.isOk()) return false;
48 
49   auto exception_code = rc.getExceptionCode();
50   if (exception_code == EX_SERVICE_SPECIFIC) {
51     LOG(ERROR) << "keystore2 Keystore " << func_name
52                << " returned service specific error: "
53                << rc.getServiceSpecificError();
54   } else {
55     LOG(ERROR) << "keystore2 Communication with Keystore " << func_name
56                << " failed error: " << exception_code;
57   }
58   return true;
59 }
60 
Keymaster()61 Keymaster::Keymaster() {
62   ::ndk::SpAIBinder binder(
63       AServiceManager_waitForService(keystore2_service_name));
64   auto keystore2Service = ks2::IKeystoreService::fromBinder(binder);
65 
66   if (!keystore2Service) {
67     LOG(ERROR) << "Unable to connect to keystore2.";
68     return;
69   }
70 
71   /*
72    * There are only two options available to vold for the SecurityLevel:
73    * TRUSTED_ENVIRONMENT (TEE) and STRONGBOX. We don't use STRONGBOX because if
74    * a TEE is present it will have Weaver, which already strengthens CE, so
75    * there's no additional benefit from using StrongBox.
76    *
77    * The picture is slightly more complicated because Keystore2 reports a
78    * SOFTWARE instance as a TEE instance when there isn't a TEE instance
79    * available, but in that case, a STRONGBOX instance won't be available
80    * either, so we'll still be doing the best we can.
81    */
82   auto rc = keystore2Service->getSecurityLevel(
83       km::SecurityLevel::TRUSTED_ENVIRONMENT, &securityLevel);
84   if (logKeystore2ExceptionIfPresent(rc, "getSecurityLevel"))
85     LOG(ERROR) << "Unable to get security level from keystore2.";
86 }
87 
generateKey(const km::AuthorizationSet & inParams,std::string * key)88 bool Keymaster::generateKey(const km::AuthorizationSet& inParams,
89                             std::string* key) {
90   ks2::KeyDescriptor in_key = {
91       .domain = ks2::Domain::BLOB,
92       .nspace = ROOT_NAMESPACE,
93       .alias = std::nullopt,
94       .blob = std::nullopt,
95   };
96   ks2::KeyMetadata keyMetadata;
97   auto rc = securityLevel->generateKey(
98       in_key, std::nullopt, inParams.vector_data(), 0, {}, &keyMetadata);
99 
100   if (logKeystore2ExceptionIfPresent(rc, "generateKey")) return false;
101 
102   if (keyMetadata.key.blob == std::nullopt) {
103     LOG(ERROR) << "keystore2 generated key blob was null";
104     return false;
105   }
106   if (key)
107     *key =
108         std::string(keyMetadata.key.blob->begin(), keyMetadata.key.blob->end());
109 
110   zeroize_vector(keyMetadata.key.blob.value());
111   return true;
112 }
113 
importKey(const km::AuthorizationSet & inParams,const std::string & key,std::string * outKeyBlob)114 bool Keymaster::importKey(const km::AuthorizationSet& inParams,
115                           const std::string& key, std::string* outKeyBlob) {
116   ks2::KeyDescriptor key_desc = {
117       .domain = ks2::Domain::BLOB,
118       .nspace = ROOT_NAMESPACE,
119       .alias = std::nullopt,
120       .blob = std::nullopt,
121   };
122   std::vector<uint8_t> key_vec(key.begin(), key.end());
123   ks2::KeyMetadata keyMetadata;
124   auto rc = securityLevel->importKey(
125       key_desc, std::nullopt, inParams.vector_data(), 0, key_vec, &keyMetadata);
126 
127   if (logKeystore2ExceptionIfPresent(rc, "importKey")) return false;
128 
129   if (keyMetadata.key.blob == std::nullopt) {
130     LOG(ERROR) << "keystore2 imported key blob was null";
131     return false;
132   }
133 
134   if (outKeyBlob)
135     *outKeyBlob =
136         std::string(keyMetadata.key.blob->begin(), keyMetadata.key.blob->end());
137 
138   return true;
139 }
140 
exportKey(const std::string & kmKey,std::string * key)141 bool Keymaster::exportKey(const std::string& kmKey, std::string* key) {
142   bool ret = false;
143   ks2::KeyDescriptor storageKey = {
144       .domain = ks2::Domain::BLOB,
145       .nspace = ROOT_NAMESPACE,
146       .alias = std::nullopt,
147   };
148   storageKey.blob =
149       std::make_optional<std::vector<uint8_t>>(kmKey.begin(), kmKey.end());
150   ks2::EphemeralStorageKeyResponse ephemeral_key_response;
151   auto rc = securityLevel->convertStorageKeyToEphemeral(
152       storageKey, &ephemeral_key_response);
153 
154   if (logKeystore2ExceptionIfPresent(rc, "exportKey")) goto out;
155   if (key)
156     *key = std::string(ephemeral_key_response.ephemeralKey.begin(),
157                        ephemeral_key_response.ephemeralKey.end());
158 
159   ret = true;
160 out:
161   zeroize_vector(ephemeral_key_response.ephemeralKey);
162   zeroize_vector(storageKey.blob.value());
163   return ret;
164 }
165 
166 }  // namespace kernel
167 }  // namespace android
168