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(AServiceManager_getService(keystore2_service_name));
63   auto keystore2Service = ks2::IKeystoreService::fromBinder(binder);
64 
65   if (!keystore2Service) {
66     LOG(ERROR) << "Vold unable to connect to keystore2.";
67     return;
68   }
69 
70   /*
71    * There are only two options available to vold for the SecurityLevel:
72    * TRUSTED_ENVIRONMENT (TEE) and STRONGBOX. We don't use STRONGBOX because if
73    * a TEE is present it will have Weaver, which already strengthens CE, so
74    * there's no additional benefit from using StrongBox.
75    *
76    * The picture is slightly more complicated because Keystore2 reports a
77    * SOFTWARE instance as a TEE instance when there isn't a TEE instance
78    * available, but in that case, a STRONGBOX instance won't be available
79    * either, so we'll still be doing the best we can.
80    */
81   auto rc = keystore2Service->getSecurityLevel(
82       km::SecurityLevel::TRUSTED_ENVIRONMENT, &securityLevel);
83   if (logKeystore2ExceptionIfPresent(rc, "getSecurityLevel"))
84     LOG(ERROR) << "Vold unable to get security level from keystore2.";
85 }
86 
generateKey(const km::AuthorizationSet & inParams,std::string * key)87 bool Keymaster::generateKey(const km::AuthorizationSet& inParams,
88                             std::string* key) {
89   ks2::KeyDescriptor in_key = {
90       .domain = ks2::Domain::BLOB,
91       .alias = std::nullopt,
92       .nspace = ROOT_NAMESPACE,
93       .blob = std::nullopt,
94   };
95   ks2::KeyMetadata keyMetadata;
96   auto rc = securityLevel->generateKey(
97       in_key, std::nullopt, inParams.vector_data(), 0, {}, &keyMetadata);
98 
99   if (logKeystore2ExceptionIfPresent(rc, "generateKey")) return false;
100 
101   if (keyMetadata.key.blob == std::nullopt) {
102     LOG(ERROR) << "keystore2 generated key blob was null";
103     return false;
104   }
105   if (key)
106     *key =
107         std::string(keyMetadata.key.blob->begin(), keyMetadata.key.blob->end());
108 
109   zeroize_vector(keyMetadata.key.blob.value());
110   return true;
111 }
112 
importKey(const km::AuthorizationSet & inParams,const std::string & key,std::string * outKeyBlob)113 bool Keymaster::importKey(const km::AuthorizationSet& inParams,
114                           const std::string& key, std::string* outKeyBlob) {
115   ks2::KeyDescriptor key_desc = {
116       .domain = ks2::Domain::BLOB,
117       .alias = std::nullopt,
118       .nspace = ROOT_NAMESPACE,
119       .blob = std::nullopt,
120   };
121   std::vector<uint8_t> key_vec(key.begin(), key.end());
122   ks2::KeyMetadata keyMetadata;
123   auto rc = securityLevel->importKey(
124       key_desc, std::nullopt, inParams.vector_data(), 0, key_vec, &keyMetadata);
125 
126   if (logKeystore2ExceptionIfPresent(rc, "importKey")) return false;
127 
128   if (keyMetadata.key.blob == std::nullopt) {
129     LOG(ERROR) << "keystore2 imported key blob was null";
130     return false;
131   }
132 
133   if (outKeyBlob)
134     *outKeyBlob =
135         std::string(keyMetadata.key.blob->begin(), keyMetadata.key.blob->end());
136 
137   return true;
138 }
139 
exportKey(const std::string & kmKey,std::string * key)140 bool Keymaster::exportKey(const std::string& kmKey, std::string* key) {
141   bool ret = false;
142   ks2::KeyDescriptor storageKey = {
143       .domain = ks2::Domain::BLOB,
144       .alias = std::nullopt,
145       .nspace = ROOT_NAMESPACE,
146   };
147   storageKey.blob =
148       std::make_optional<std::vector<uint8_t>>(kmKey.begin(), kmKey.end());
149   ks2::EphemeralStorageKeyResponse ephemeral_key_response;
150   auto rc = securityLevel->convertStorageKeyToEphemeral(
151       storageKey, &ephemeral_key_response);
152 
153   if (logKeystore2ExceptionIfPresent(rc, "exportKey")) goto out;
154   if (key)
155     *key = std::string(ephemeral_key_response.ephemeralKey.begin(),
156                        ephemeral_key_response.ephemeralKey.end());
157 
158   ret = true;
159 out:
160   zeroize_vector(ephemeral_key_response.ephemeralKey);
161   zeroize_vector(storageKey.blob.value());
162   return ret;
163 }
164 
165 }  // namespace kernel
166 }  // namespace android
167