Asylo
enclave_manager.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2018 Asylo authors
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #ifndef ASYLO_PLATFORM_CORE_ENCLAVE_MANAGER_H_
20 #define ASYLO_PLATFORM_CORE_ENCLAVE_MANAGER_H_
21 
22 // Declares the enclave client API, providing types and methods for loading,
23 // accessing, and finalizing enclaves.
24 
25 #include <string>
26 #include <utility>
27 
28 #include "absl/container/flat_hash_map.h"
29 #include "absl/memory/memory.h"
30 #include "absl/strings/string_view.h"
31 #include "absl/synchronization/mutex.h"
32 #include "absl/time/time.h"
33 #include "absl/types/variant.h"
34 #include "asylo/enclave.pb.h" // IWYU pragma: export
35 #include "asylo/platform/core/enclave_client.h"
36 #include "asylo/platform/core/enclave_config_util.h"
37 #include "asylo/platform/core/shared_resource_manager.h"
38 #include "asylo/util/status.h" // IWYU pragma: export
39 #include "asylo/util/statusor.h"
40 
41 namespace asylo {
42 class EnclaveLoader;
43 
44 /// Enclave Manager configuration.
46  public:
47  /// Configuration server connection attributes.
48  ///
49  /// A part of an enclave's configuration is expected to be the same across all
50  /// enclaves running under a single instance of an OS. An Enclave manager can
51  /// obtain such configuration from the Asylo daemon running on the system.
52  /// Alternately, the creator of the enclave manager can directly provide such
53  /// configuration to the enclave manager. To this end, an
54  /// EnclaveManagerOptions instance either holds the information necessary for
55  /// connecting to the config server, or holds a HostConfig proto. If the
56  /// enclave manager is configured with an options object containing the
57  /// server-connection information, the enclave manager obtains the necessary
58  /// information by contacting the Asylo daemon. Else, the enclave manager
59  /// directly uses the HostConfig info stored within the options structure.
60  ///
61  /// The ConfigServerConnectionAttributes struct holds information necessary
62  /// for contacting the config server running inside the Asylo daemon.
64  ConfigServerConnectionAttributes(std::string address, absl::Duration timeout)
67 
68  std::string server_address;
70  };
71 
72  /// Constructs a default EnclaveManagerOptions object.
74 
75  /// Configures a connection to the config server.
76  ///
77  /// Sets the information necessary for contacting the config server within the
78  /// Asylo daemon.
79  ///
80  /// \return A reference to this EnclaveManagerOptions object.
82  std::string address, absl::Duration timeout);
83 
84  /// Sets the HostConfig proto within this object.
85  ///
86  /// \return A reference to this EnclaveManagerOptions object.
87  EnclaveManagerOptions &set_host_config(HostConfig config);
88 
89  /// Returns the address of the configuration server.
90  ///
91  /// \return The address of the server from which the HostConfig information
92  /// can be obtained. Returns an error if
93  /// ConfigServerConnectionAttributes are not set.
95 
96  /// Returns the configuration server connection timeout.
97  ///
98  /// \return The connection timeout for the server from which the HostConfig
99  /// information can be obtained, or an error if
100  /// ConfigServerConnectionAttributes are not set.
102 
103  /// Returns the embedded HostConfig object.
104  ///
105  /// \return The HostConfig information embedded within this object, or an
106  /// error if such information is not embedded within the object.
108 
109  /// Returns true if a HostConfig instance is embedded in this object.
110  bool holds_host_config() const;
111 
112  private:
113  // A variant that either holds information necessary for connecting to the
114  // config server or a HostConfig proto.
115  absl::variant<ConfigServerConnectionAttributes, HostConfig> host_config_info_;
116 };
117 
118 /// A manager object responsible for creating and managing enclave instances.
119 ///
120 /// EnclaveManager is a singleton class that tracks the status of enclaves
121 /// within a process. Users of this class first supply a configuration using the
122 /// static Configure() method, and then get a pointer to the singleton instance
123 /// as specified by this configuration by calling the static Instance() method.
124 /// Note that the EnclaveManager class must be configured before the instance
125 /// pointer can be obtained.
126 ///
127 /// The EnclaveManager::Configure() method takes an instance of the
128 /// EnclaveManagerOptions as its only input. This instance can be configured by
129 /// calling its public setter methods. Note that these setter methods return an
130 /// instance of the EnclaveManagerOptions() by reference so that the various
131 /// setters could be chained together.
132 ///
133 /// Example Usage:
134 /// ```
135 /// EnclaveManager::Configure(
136 /// EnclaveManagerOptions()
137 /// .set_config_server_address("[::]:8000")
138 /// .set_daemon_connection_timeout(absl::Milliseconds(100)));
139 /// auto manager_result = EnclaveManager::Instance();
140 /// if (!manager_result.ok()) {
141 /// LOG(QFATAL) << manager_result.status();
142 /// }
143 /// EnclaveManager *manager = manager_result.ValueOrDie();
144 /// ...
145 /// ```
146 ///
147 /// One of the responsibilities of the EnclaveManager class is to provide sane
148 /// initial configuration to the enclaves it launches. The contents of the
149 /// EnclaveManagerOptions instance control how the default values for the
150 /// configuration are chosen.
151 class EnclaveManager {
152  public:
153  /// Fetches the EnclaveManager singleton instance.
154  ///
155  /// \return A StatusOr containing either the global EnclaveManager instance or
156  /// an error describing why it could not be returned.
157  static StatusOr<EnclaveManager *> Instance();
158 
159  /// Configures the enclave manager.
160  ///
161  /// \param options Configuration options as described in
162  /// EnclaveManagerOptions.
164 
165  /// Loads an enclave.
166  ///
167  /// Loads a new enclave with default enclave config settings and binds it to a
168  /// name. The actual work of opening the enclave is delegated to the passed
169  /// loader object.
170  ///
171  /// It is an error to specify a name which is already bound to an enclave.
172  ///
173  /// Example:
174  /// ```
175  /// LoadEnclave("/EchoEnclave", SgxLoader("echoService.so"));
176  /// ```
177  ///
178  /// \param name Name to bind the loaded enclave under.
179  /// \param loader Configured enclave loader to load from.
181  void *base_address = nullptr);
182 
183  /// Loads an enclave.
184  ///
185  /// Loads a new enclave with custom enclave config settings and binds it to a
186  /// name. The actual work of opening the enclave is delegated to the passed
187  /// loader object.
188  ///
189  /// It is an error to specify a name which is already bound to an enclave.
190  ///
191  /// Example:
192  ///
193  /// ```
194  /// EnclaveConfig config;
195  /// ... // populate config proto.
196  /// LoadEnclave("/EchoEnclave", SgxLoader("echoService.so"), config);
197  /// ```
198  ///
199  /// \param name Name to bind the loaded enclave under.
200  /// \param loader Configured enclave loader to load from.
201  /// \param config Enclave configuration to launch the enclave with.
203  EnclaveConfig config, void *base_address = nullptr);
204 
205  /// Fetches a client to a loaded enclave.
206  ///
207  /// \param name The name of an EnclaveClient that may be registered in the
208  /// EnclaveManager.
209  /// \return A mutable pointer to the EnclaveClient if the name is
210  /// registered. Otherwise returns nullptr.
211  EnclaveClient *GetClient(const std::string &name) const;
212 
213  /// Returns the name of an enclave client.
214  ///
215  /// \param client A pointer to a client that may be registered in the
216  /// EnclaveManager.
217  /// \return The name of an enclave client. If no enclave matches `client` the
218  /// empty string will be returned.
219  const std::string GetName(const EnclaveClient *client) const;
220 
221  /// Destroys an enclave.
222  ///
223  /// Destroys an enclave. This method calls `client's` EnterAndFinalize entry
224  /// point with final_input unless `skip_finalize` is true, then calls
225  /// `client's` DestroyEnclave method, and then removes client's name from the
226  /// EnclaveManager client registry. The manager owns the client, so removing
227  /// it calls client's destructor and frees its memory.
228  ///
229  /// \param client A client attached to the enclave to destroy.
230  /// \param final_input Input to pass the enclave's finalizer.
231  /// \param skip_finalize If true, the enclave is destroyed without invoking
232  /// its Finalize method.
234  bool skip_finalize = false);
235 
236  /// Fetches the shared resource manager object.
237  ///
238  /// \return The SharedResourceManager instance.
240  return &shared_resource_manager_;
241  }
242 
243  /// Fetches the shared resource manager object.
244  ///
245  /// \return The SharedResourceManager instance.
247  return &shared_resource_manager_;
248  }
249 
250  private:
251  EnclaveManager() EXCLUSIVE_LOCKS_REQUIRED(mu_);
252  EnclaveManager(EnclaveManager const &) = delete;
253  EnclaveManager &operator=(EnclaveManager const &) = delete;
254 
255  // Retrieves and returns a HostConfig proto as specified by the
256  // EnclaveManagerOptions which the EnclaveManager was configured when its
257  // sngleton instance was created.
258  HostConfig GetHostConfig() EXCLUSIVE_LOCKS_REQUIRED(mu_);
259 
260  // Loads a new enclave with custom enclave config settings and binds it to a
261  // name. The actual work of opening the enclave is delegated to the passed
262  // loader object.
263  Status LoadEnclaveInternal(const std::string &name, const EnclaveLoader &loader,
264  const EnclaveConfig &config,
265  void *base_address = nullptr);
266 
267  // Create a thread to periodically update logic.
268  void SpawnWorkerThread();
269 
270  // Top level loop run by the background worker thread.
271  void WorkerLoop();
272 
273  // Execute a single iteration of the work loop.
274  void Tick();
275 
276  // Manager object for untrusted resources shared with enclaves.
277  SharedResourceManager shared_resource_manager_;
278 
279  // Value synchronized to CLOCK_MONOTONIC by the worker loop.
280  std::atomic<int64_t> clock_monotonic_;
281 
282  // Value synchronized to CLOCK_REALTIME by the worker loop.
283  std::atomic<int64_t> clock_realtime_;
284 
285  absl::flat_hash_map<std::string, std::unique_ptr<EnclaveClient>> client_by_name_;
286  absl::flat_hash_map<const EnclaveClient *, std::string> name_by_client_;
287 
288  // A part of the configuration for enclaves launched by the enclave manager
289  // comes from the Asylo daemon. This member caches such configuration.
290  HostConfig host_config_;
291 
292  // Mutex guarding the static state of this class.
293  static absl::Mutex mu_;
294 
295  // Indication whether the class has been configured so that an instance could
296  // be created.
297  static bool configured_ GUARDED_BY(mu_);
298 
299  // Configuration options for this class.
300  static EnclaveManagerOptions *options_ GUARDED_BY(mu_);
301 
302  // Singleton instance of this class.
303  static EnclaveManager *instance_ GUARDED_BY(mu_);
304 };
305 
306 /// An abstract enclave loader.
307 ///
308 /// Host applications must load an enclave before using it. This is accomplished
309 /// via an architecture specific implementation of the EnclaveLoader interface.
311  public:
312  virtual ~EnclaveLoader() = default;
313 
314  protected:
315  // Only allow the enclave loading via the manager object.
316  friend class EnclaveManager;
317 
318  // Loads an enclave, returning a pointer to a client on success and a non-ok
319  // status on failure.
321  const std::string &name) const {
322  return LoadEnclave(name, nullptr);
323  }
324 
325  // Loads an enclave at the specified address, returning a pointer to a client
326  // on success and a non-ok status on failure.
328  const std::string &name, void *base_address) const = 0;
329 };
330 
331 // Stores the mapping between signals and the enclave with a handler installed
332 // for that signal.
333 class EnclaveSignalDispatcher {
334  public:
335  static EnclaveSignalDispatcher *GetInstance();
336 
337  // Associates a signal with an enclave which registers a handler for it.
338  // It's not supported for multiple enclaves to register the same signal. In
339  // that case, the latter will overwrite the former.
340  //
341  // Returns the enclave client that previous registered |signum|, or nullptr if
342  // no enclave has registered |signum| yet.
344  LOCKS_EXCLUDED(signal_enclave_map_lock_);
345 
346  // Gets the enclave that registered a handler for |signum|.
348  LOCKS_EXCLUDED(signal_enclave_map_lock_);
349 
350  // Deregisters all the signals registered by |client|.
352  LOCKS_EXCLUDED(signal_enclave_map_lock_);
353 
354  // Looks for the enclave client that registered |signum|, and calls
355  // EnterAndHandleSignal() with that enclave client. |signum|, |info| and
356  // |ucontext| are passed into the enclave.
358  void *ucontext);
359 
360  private:
361  EnclaveSignalDispatcher() = default; // Private to enforce singleton.
362  EnclaveSignalDispatcher(EnclaveSignalDispatcher const &) = delete;
363  void operator=(EnclaveSignalDispatcher const &) = delete;
364 
365  // Mapping of signal number to the enclave client that registered it.
366  absl::flat_hash_map<int, EnclaveClient *> signal_to_client_map_
367  GUARDED_BY(signal_enclave_map_lock_);
368 
369  // A mutex that guards signal_to_client_map_ and client_to_signal_map_.
370  mutable absl::Mutex signal_enclave_map_lock_;
371 };
372 
373 } // namespace asylo
374 
375 #endif // ASYLO_PLATFORM_CORE_ENCLAVE_MANAGER_H_
Status LoadEnclave(const std::string &name, const EnclaveLoader &loader, EnclaveConfig config, void *base_address=nullptr)
Loads an enclave.
virtual StatusOr< std::unique_ptr< EnclaveClient > > LoadEnclave(const std::string &name, void *base_address) const =0
Status LoadEnclave(const std::string &name, const EnclaveLoader &loader, void *base_address=nullptr)
Loads an enclave.
Status EnterEnclaveAndHandleSignal(int signum, siginfo_t *info, void *ucontext)
const std::string GetName(const EnclaveClient *client) const
Returns the name of an enclave client.
ConfigServerConnectionAttributes(std::string address, absl::Duration timeout)
Definition: enclave_manager.h:64
static StatusOr< EnclaveManager * > Instance()
Fetches the EnclaveManager singleton instance.
Configuration server connection attributes.
Definition: enclave_manager.h:63
EnclaveManagerOptions & set_host_config(HostConfig config)
Sets the HostConfig proto within this object.
bool holds_host_config() const
Returns true if a HostConfig instance is embedded in this object.
StatusOr< absl::Duration > get_config_server_connection_timeout() const
Returns the configuration server connection timeout.
StatusOr< EnclaveClient * > GetClientForSignal(int signum) const LOCKS_EXCLUDED(signal_enclave_map_lock_)
StatusOr< std::string > get_config_server_address() const
Returns the address of the configuration server.
static Status Configure(const EnclaveManagerOptions &options)
Configures the enclave manager.
virtual ~EnclaveLoader()=default
static EnclaveSignalDispatcher * GetInstance()
SharedResourceManager * shared_resources()
Fetches the shared resource manager object.
Definition: enclave_manager.h:239
EnclaveManagerOptions & set_config_server_connection_attributes(std::string address, absl::Duration timeout)
Configures a connection to the config server.
const EnclaveClient * RegisterSignal(int signum, EnclaveClient *client) LOCKS_EXCLUDED(signal_enclave_map_lock_)
absl::Duration connection_timeout
Definition: enclave_manager.h:69
Enclave Manager configuration.
Definition: enclave_manager.h:45
const SharedResourceManager * shared_resources() const
Fetches the shared resource manager object.
Definition: enclave_manager.h:246
Status DestroyEnclave(EnclaveClient *client, const EnclaveFinal &final_input, bool skip_finalize=false)
Destroys an enclave.
EnclaveManagerOptions()
Constructs a default EnclaveManagerOptions object.
Definition: aes_gcm_siv.h:37
Status DeregisterAllSignalsForClient(EnclaveClient *client) LOCKS_EXCLUDED(signal_enclave_map_lock_)
EnclaveClient * GetClient(const std::string &name) const
Fetches a client to a loaded enclave.
StatusOr< HostConfig > get_host_config() const
Returns the embedded HostConfig object.
std::string server_address
Definition: enclave_manager.h:68