1/*
2 * Copyright (C) 2009 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 "keystore"
18
19#include <android-base/logging.h>
20#include <android/hidl/manager/1.1/IServiceManager.h>
21#include <android/security/IKeystoreService.h>
22#include <android/system/wifi/keystore/1.0/IKeystore.h>
23#include <binder/IPCThreadState.h>
24#include <binder/IServiceManager.h>
25#include <hidl/HidlTransportSupport.h>
26#include <keymasterV4_0/Keymaster3.h>
27#include <keymasterV4_0/Keymaster4.h>
28#include <utils/StrongPointer.h>
29#include <wifikeystorehal/keystore.h>
30
31#include <keystore/keystore_hidl_support.h>
32#include <keystore/keystore_return_types.h>
33
34#include "KeyStore.h"
35#include "entropy.h"
36#include "key_store_service.h"
37#include "legacy_keymaster_device_wrapper.h"
38#include "permissions.h"
39
40/* KeyStore is a secured storage for key-value pairs. In this implementation,
41 * each file stores one key-value pair. Keys are encoded in file names, and
42 * values are encrypted with checksums. The encryption key is protected by a
43 * user-defined password. To keep things simple, buffers are always larger than
44 * the maximum space we needed, so boundary checks on buffers are omitted. */
45
46using ::android::sp;
47using ::android::hardware::configureRpcThreadpool;
48using ::android::system::wifi::keystore::V1_0::IKeystore;
49using ::android::system::wifi::keystore::V1_0::implementation::Keystore;
50using ::android::hidl::manager::V1_1::IServiceManager;
51using ::android::hardware::hidl_string;
52using ::android::hardware::hidl_vec;
53using ::android::hardware::keymaster::V4_0::SecurityLevel;
54using ::android::hardware::keymaster::V4_0::HmacSharingParameters;
55using ::android::hardware::keymaster::V4_0::ErrorCode;
56
57using ::keystore::keymaster::support::Keymaster;
58using ::keystore::keymaster::support::Keymaster3;
59using ::keystore::keymaster::support::Keymaster4;
60
61using keystore::KeymasterDevices;
62
63template <typename Wrapper>
64KeymasterDevices enumerateKeymasterDevices(IServiceManager* serviceManager) {
65    KeymasterDevices result;
66    serviceManager->listByInterface(
67        Wrapper::WrappedIKeymasterDevice::descriptor, [&](const hidl_vec<hidl_string>& names) {
68            auto try_get_device = [&](const auto& name, bool fail_silent) {
69                auto device = Wrapper::WrappedIKeymasterDevice::getService(name);
70                if (fail_silent && !device) return;
71                CHECK(device) << "Failed to get service for \""
72                              << Wrapper::WrappedIKeymasterDevice::descriptor
73                              << "\" with interface name \"" << name << "\"";
74
75                sp<Keymaster> kmDevice(new Wrapper(device, name));
76                auto halVersion = kmDevice->halVersion();
77                SecurityLevel securityLevel = halVersion.securityLevel;
78                LOG(INFO) << "found " << Wrapper::WrappedIKeymasterDevice::descriptor
79                          << " with interface name " << name << " and seclevel "
80                          << toString(securityLevel);
81                CHECK(static_cast<uint32_t>(securityLevel) < result.size())
82                    << "Security level of \"" << Wrapper::WrappedIKeymasterDevice::descriptor
83                    << "\" with interface name \"" << name << "\" out of range";
84                auto& deviceSlot = result[securityLevel];
85                if (deviceSlot) {
86                    if (!fail_silent) {
87                        LOG(WARNING) << "Implementation of \""
88                                     << Wrapper::WrappedIKeymasterDevice::descriptor
89                                     << "\" with interface name \"" << name
90                                     << "\" and security level: " << toString(securityLevel)
91                                     << " Masked by other implementation of Keymaster";
92                    }
93                } else {
94                    deviceSlot = kmDevice;
95                }
96            };
97            bool has_default = false;
98            for (auto& n : names) {
99                try_get_device(n, false);
100                if (n == "default") has_default = true;
101            }
102            // Make sure that we always check the default device. If we enumerate only what is
103            // known to hwservicemanager, we miss a possible passthrough HAL.
104            if (!has_default) {
105                try_get_device("default", true /* fail_silent */);
106            }
107        });
108    return result;
109}
110
111KeymasterDevices initializeKeymasters() {
112    auto serviceManager = android::hidl::manager::V1_1::IServiceManager::getService();
113    CHECK(serviceManager.get()) << "Failed to get ServiceManager";
114    auto result = enumerateKeymasterDevices<Keymaster4>(serviceManager.get());
115    auto softKeymaster = result[SecurityLevel::SOFTWARE];
116    if (!result[SecurityLevel::TRUSTED_ENVIRONMENT]) {
117        result = enumerateKeymasterDevices<Keymaster3>(serviceManager.get());
118    }
119    if (softKeymaster) result[SecurityLevel::SOFTWARE] = softKeymaster;
120    if (result[SecurityLevel::SOFTWARE] && !result[SecurityLevel::TRUSTED_ENVIRONMENT]) {
121        LOG(WARNING) << "No secure Keymaster implementation found, but device offers insecure"
122                        " Keymaster HAL. Using as default.";
123        result[SecurityLevel::TRUSTED_ENVIRONMENT] = result[SecurityLevel::SOFTWARE];
124        result[SecurityLevel::SOFTWARE] = nullptr;
125    }
126    if (!result[SecurityLevel::SOFTWARE]) {
127        auto fbdev = android::keystore::makeSoftwareKeymasterDevice();
128        CHECK(fbdev.get()) << "Unable to create Software Keymaster Device";
129        result[SecurityLevel::SOFTWARE] = new Keymaster3(fbdev, "Software");
130    }
131    return result;
132}
133
134int main(int argc, char* argv[]) {
135    using android::hardware::hidl_string;
136    CHECK(argc >= 2) << "A directory must be specified!";
137    CHECK(chdir(argv[1]) != -1) << "chdir: " << argv[1] << ": " << strerror(errno);
138
139    Entropy entropy;
140    CHECK(entropy.open()) << "Failed to open entropy source.";
141
142    auto kmDevices = initializeKeymasters();
143
144    CHECK(kmDevices[SecurityLevel::SOFTWARE]) << "Missing software Keymaster device";
145    CHECK(kmDevices[SecurityLevel::TRUSTED_ENVIRONMENT])
146        << "Error no viable keymaster device found";
147
148    CHECK(configure_selinux() != -1) << "Failed to configure SELinux.";
149
150    auto halVersion = kmDevices[SecurityLevel::TRUSTED_ENVIRONMENT]->halVersion();
151
152    // If the hardware is keymaster 2.0 or higher we will not allow the fallback device for import
153    // or generation of keys. The fallback device is only used for legacy keys present on the
154    // device.
155    SecurityLevel minimalAllowedSecurityLevelForNewKeys =
156        halVersion.majorVersion >= 2 ? SecurityLevel::TRUSTED_ENVIRONMENT : SecurityLevel::SOFTWARE;
157
158    keystore::KeyStore keyStore(&entropy, kmDevices, minimalAllowedSecurityLevelForNewKeys);
159    keyStore.initialize();
160    android::sp<android::IServiceManager> sm = android::defaultServiceManager();
161    android::sp<keystore::KeyStoreService> service = new keystore::KeyStoreService(&keyStore);
162    android::status_t ret = sm->addService(android::String16("android.security.keystore"), service);
163    CHECK(ret == android::OK) << "Couldn't register binder service!";
164
165    /**
166     * Register the wifi keystore HAL service to run in passthrough mode.
167     * This will spawn off a new thread which will service the HIDL
168     * transactions.
169     */
170    configureRpcThreadpool(1, false /* callerWillJoin */);
171    android::sp<IKeystore> wifiKeystoreHalService = new Keystore();
172    android::status_t err = wifiKeystoreHalService->registerAsService();
173    CHECK(ret == android::OK) << "Cannot register wifi keystore HAL service: " << err;
174
175    /*
176     * This thread is just going to process Binder transactions.
177     */
178    android::IPCThreadState::self()->joinThreadPool();
179    return 1;
180}
181