-
Notifications
You must be signed in to change notification settings - Fork 126
/
enclave_manager.cc
343 lines (293 loc) · 9.96 KB
/
enclave_manager.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
*
* Copyright 2018 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "asylo/platform/core/enclave_manager.h"
#include <signal.h>
#include <stdint.h>
#include <time.h>
#include <thread>
#include "asylo/util/logging.h"
#include "asylo/platform/common/time_util.h"
namespace asylo {
namespace {
// Returns the value of a monotonic clock as a number of nanoseconds.
int64_t MonotonicClock() {
struct timespec ts;
CHECK(clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
<< "Could not read monotonic clock.";
return TimeSpecToNanoseconds(&ts);
}
// Returns the value of a realtime clock as a number of nanoseconds.
int64_t RealTimeClock() {
struct timespec ts;
CHECK(clock_gettime(CLOCK_REALTIME, &ts) == 0)
<< "Could not read realtime clock.";
return TimeSpecToNanoseconds(&ts);
}
// Sleeps for a interval specified in nanoseconds.
void Sleep(int64_t nanoseconds) {
struct timespec req;
nanosleep(NanosecondsToTimeSpec(&req, nanoseconds), nullptr);
}
// Sleeps until a deadline, specified a value of MonotonicClock().
void WaitUntil(int64_t deadline) {
int64_t delta;
while ((delta = deadline - MonotonicClock()) > 0) {
Sleep(delta);
}
}
} // namespace
absl::Mutex EnclaveManager::mu_;
bool EnclaveManager::configured_ = false;
EnclaveManagerOptions *EnclaveManager::options_ = nullptr;
EnclaveManager *EnclaveManager::instance_ = nullptr;
void donate(asylo::EnclaveClient *client) {
Status status = client->EnterAndDonateThread();
if (!status.ok()) {
LOG(ERROR) << "EnterAndDonateThread(): " << status.error_code();
}
}
// By default, the options object holds an empty HostConfig proto.
EnclaveManagerOptions::EnclaveManagerOptions()
: host_config_info_(absl::in_place_type_t<HostConfig>()) {}
EnclaveManagerOptions &
EnclaveManagerOptions::set_config_server_connection_attributes(
std::string address, absl::Duration timeout) {
host_config_info_.emplace<ConfigServerConnectionAttributes>(
std::move(address), timeout);
return *this;
}
EnclaveManagerOptions &EnclaveManagerOptions::set_host_config(
HostConfig config) {
host_config_info_.emplace<HostConfig>(std::move(config));
return *this;
}
StatusOr<std::string> EnclaveManagerOptions::get_config_server_address() const {
const ConfigServerConnectionAttributes *attributes =
absl::get_if<ConfigServerConnectionAttributes>(&host_config_info_);
if (!attributes) {
return Status(error::GoogleError::FAILED_PRECONDITION,
"Options object does not hold config-server address");
}
return attributes->server_address;
}
StatusOr<absl::Duration>
EnclaveManagerOptions::get_config_server_connection_timeout() const {
const ConfigServerConnectionAttributes *attributes =
absl::get_if<ConfigServerConnectionAttributes>(&host_config_info_);
if (!attributes) {
return Status(error::GoogleError::FAILED_PRECONDITION,
"Options object does not hold server-connection timeout");
}
return attributes->connection_timeout;
}
StatusOr<HostConfig> EnclaveManagerOptions::get_host_config() const {
const HostConfig *config = absl::get_if<HostConfig>(&host_config_info_);
if (!config) {
return Status(error::GoogleError::FAILED_PRECONDITION,
"Options object does not contain a HostConfig");
}
return *config;
}
bool EnclaveManagerOptions::holds_host_config() const {
return absl::holds_alternative<HostConfig>(host_config_info_);
}
HostConfig EnclaveManager::GetHostConfig() {
if (options_->holds_host_config()) {
StatusOr<HostConfig> config_result = options_->get_host_config();
if (!config_result.ok()) {
LOG(ERROR) << config_result.status();
return HostConfig();
}
return config_result.ValueOrDie();
}
HostConfig config;
LOG(ERROR) << "Not implemented";
return config;
}
EnclaveManager::EnclaveManager() : host_config_(GetHostConfig()) {
Status rc = shared_resource_manager_.RegisterUnmanagedResource(
SharedName::Address("clock_monotonic"), &clock_monotonic_);
if (!rc.ok()) {
LOG(FATAL) << "Could not register monotonic clock resource.";
}
rc = shared_resource_manager_.RegisterUnmanagedResource(
SharedName::Address("clock_realtime"), &clock_realtime_);
if (!rc.ok()) {
LOG(FATAL) << "Could not register realtime clock resource.";
}
SpawnWorkerThread();
}
Status EnclaveManager::DestroyEnclave(EnclaveClient *client,
const EnclaveFinal &final_input,
bool skip_finalize) {
if (!client) {
return Status::OkStatus();
}
Status status;
if (!skip_finalize) {
status = client->EnterAndFinalize(final_input);
if (!status.ok()) {
return status;
}
}
status = client->DestroyEnclave();
if (status.ok()) {
const auto &name = name_by_client_[client];
client_by_name_.erase(name);
name_by_client_.erase(client);
}
return status;
}
EnclaveClient *EnclaveManager::GetClient(const std::string &name) const {
auto it = client_by_name_.find(name);
if (it == client_by_name_.end()) {
return nullptr;
} else {
return it->second.get();
}
}
const std::string EnclaveManager::GetName(const EnclaveClient *client) const {
auto it = name_by_client_.find(client);
if (it == name_by_client_.end()) {
return "";
} else {
return it->second;
}
}
Status EnclaveManager::Configure(const EnclaveManagerOptions &options) {
absl::MutexLock lock(&mu_);
if (instance_) {
return Status(error::GoogleError::FAILED_PRECONDITION,
"Cannot configure the enclave manager after an instance has "
"been created");
}
if (options_) {
delete options_;
}
options_ = new EnclaveManagerOptions(options);
configured_ = true;
return Status::OkStatus();
}
StatusOr<EnclaveManager *> EnclaveManager::Instance() {
absl::MutexLock lock(&mu_);
if (instance_) {
return instance_;
}
if (!configured_) {
return Status(
error::GoogleError::FAILED_PRECONDITION,
"Cannot create enclave manager instance before it is configured");
}
instance_ = new EnclaveManager();
if (!instance_) {
return Status(error::GoogleError::RESOURCE_EXHAUSTED,
"Could not create an instance of the enclave manager");
}
return instance_;
}
Status EnclaveManager::LoadEnclave(const std::string &name,
const EnclaveLoader &loader) {
return LoadEnclaveInternal(name, loader,
CreateDefaultEnclaveConfig(host_config_));
}
Status EnclaveManager::LoadEnclave(const std::string &name,
const EnclaveLoader &loader,
EnclaveConfig config) {
EnclaveConfig sanitized_config = std::move(config);
SetEnclaveConfigDefaults(host_config_, &sanitized_config);
return LoadEnclaveInternal(name, loader, sanitized_config);
}
Status EnclaveManager::LoadEnclaveInternal(const std::string &name,
const EnclaveLoader &loader,
const EnclaveConfig &config) {
// Check whether a client with this name already exists.
if (client_by_name_.find(name) != client_by_name_.end()) {
Status status(error::GoogleError::ALREADY_EXISTS,
"Name already exists: " + name);
LOG(ERROR) << "LoadEnclave failed: " << status;
return status;
}
// Attempt to load the enclave.
StatusOr<std::unique_ptr<EnclaveClient>> result = loader.LoadEnclave(name);
if (!result.ok()) {
LOG(ERROR) << "LoadEnclave failed: " << result.status();
return result.status();
}
// Add the client to the lookup tables.
EnclaveClient *client = result.ValueOrDie().get();
client_by_name_.emplace(name, std::move(result).ValueOrDie());
name_by_client_.emplace(client, name);
Status status = client->EnterAndInitialize(config);
// If initialization fails, don't keep the enclave registered. GetClient will
// return a nullptr rather than an enclave in a bad state.
if (!status.ok()) {
Status destroy_status = client->DestroyEnclave();
if (!destroy_status.ok()) {
LOG(ERROR) << "DestroyEnclave failed after EnterAndInitialize failure: "
<< destroy_status;
}
client_by_name_.erase(name);
name_by_client_.erase(client);
}
return status;
}
void EnclaveManager::SpawnWorkerThread() {
std::mutex worker_init_lock;
worker_init_lock.lock();
std::thread worker(
[this, &worker_init_lock] { WorkerLoop(&worker_init_lock); });
worker.detach();
// Block until the worker loop is fully initialized and unlocks the passed
// mutex.
worker_init_lock.lock();
}
void EnclaveManager::Tick() {
clock_monotonic_ = MonotonicClock();
clock_realtime_ = RealTimeClock();
}
void EnclaveManager::WorkerLoop(std::mutex *unlock_when_ready) {
// Tick each 70us ~ 14.29kHz
const int64_t kClockPeriod = INT64_C(70000);
Tick();
unlock_when_ready->unlock();
unlock_when_ready = nullptr;
int64_t next_tick = MonotonicClock();
while (true) {
WaitUntil(next_tick);
Tick();
next_tick += kClockPeriod;
}
}
}; // namespace asylo
extern "C" {
int __asylo_donate_thread(const char *name) {
auto manager_result = ::asylo::EnclaveManager::Instance();
if (!manager_result.ok()) {
LOG(ERROR) << manager_result.status();
return -1;
}
asylo::EnclaveClient *client =
manager_result.ValueOrDie()->GetClient(name);
if (!client) {
return -1;
}
std::thread thread(asylo::donate, client);
thread.detach();
return 0;
}
} // extern "C"