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 <mutex>
26 #include <string>
27 #include <unordered_map>
28 #include <unordered_set>
29 #include <utility>
30 
31 #include "absl/memory/memory.h"
32 #include "absl/strings/string_view.h"
33 #include "absl/synchronization/mutex.h"
34 #include "absl/time/time.h"
35 #include "absl/types/variant.h"
36 #include "asylo/enclave.pb.h" // IWYU pragma: export
37 #include "asylo/platform/core/enclave_client.h"
38 #include "asylo/platform/core/enclave_config_util.h"
39 #include "asylo/platform/core/shared_resource_manager.h"
40 #include "asylo/util/status.h" // IWYU pragma: export
41 #include "asylo/util/statusor.h"
42 
43 namespace asylo {
44 class EnclaveLoader;
45 
46 /// Enclave Manager configuration.
48  public:
49  /// Configuration server connection attributes.
50  ///
51  /// A part of an enclave's configuration is expected to be the same across all
52  /// enclaves running under a single instance of an OS. An Enclave manager can
53  /// obtain such configuration from the Asylo daemon running on the system.
54  /// Alternately, the creator of the enclave manager can directly provide such
55  /// configuration to the enclave manager. To this end, an
56  /// EnclaveManagerOptions instance either holds the information necessary for
57  /// connecting to the config server, or holds a HostConfig proto. If the
58  /// enclave manager is configured with an options object containing the
59  /// server-connection information, the enclave manager obtains the necessary
60  /// information by contacting the Asylo daemon. Else, the enclave manager
61  /// directly uses the HostConfig info stored within the options structure.
62  ///
63  /// The ConfigServerConnectionAttributes struct holds information necessary
64  /// for contacting the config server running inside the Asylo daemon.
66  ConfigServerConnectionAttributes(std::string address, absl::Duration timeout)
69 
70  std::string server_address;
72  };
73 
74  /// Constructs a default EnclaveManagerOptions object.
76 
77  /// Configures a connection to the config server.
78  ///
79  /// Sets the information necessary for contacting the config server within the
80  /// Asylo daemon.
81  ///
82  /// \return A reference to this EnclaveManagerOptions object.
84  std::string address, absl::Duration timeout);
85 
86  /// Sets the HostConfig proto within this object.
87  ///
88  /// \return A reference to this EnclaveManagerOptions object.
89  EnclaveManagerOptions &set_host_config(HostConfig config);
90 
91  /// Returns the address of the configuration server.
92  ///
93  /// \return The address of the server from which the HostConfig information
94  /// can be obtained. Returns an error if
95  /// ConfigServerConnectionAttributes are not set.
97 
98  /// Returns the configuration server connection timeout.
99  ///
100  /// \return The connection timeout for the server from which the HostConfig
101  /// information can be obtained, or an error if
102  /// ConfigServerConnectionAttributes are not set.
104 
105  /// Returns the embedded HostConfig object.
106  ///
107  /// \return The HostConfig information embedded within this object, or an
108  /// error if such information is not embedded within the object.
110 
111  /// Returns true if a HostConfig instance is embedded in this object.
112  bool holds_host_config() const;
113 
114  private:
115  // A variant that either holds information necessary for connecting to the
116  // config server or a HostConfig proto.
117  absl::variant<ConfigServerConnectionAttributes, HostConfig> host_config_info_;
118 };
119 
120 /// A manager object responsible for creating and managing enclave instances.
121 ///
122 /// EnclaveManager is a singleton class that tracks the status of enclaves
123 /// within a process. Users of this class first supply a configuration using the
124 /// static Configure() method, and then get a pointer to the singleton instance
125 /// as specified by this configuration by calling the static Instance() method.
126 /// Note that the EnclaveManager class must be configured before the instance
127 /// pointer can be obtained.
128 ///
129 /// The EnclaveManager::Configure() method takes an instance of the
130 /// EnclaveManagerOptions as its only input. This instance can be configured by
131 /// calling its public setter methods. Note that these setter methods return an
132 /// instance of the EnclaveManagerOptions() by reference so that the various
133 /// setters could be chained together.
134 ///
135 /// Example Usage:
136 /// ```
137 /// EnclaveManager::Configure(
138 /// EnclaveManagerOptions()
139 /// .set_config_server_address("[::]:8000")
140 /// .set_daemon_connection_timeout(absl::Milliseconds(100)));
141 /// auto manager_result = EnclaveManager::Instance();
142 /// if (!manager_result.ok()) {
143 /// LOG(QFATAL) << manager_result.status();
144 /// }
145 /// EnclaveManager *manager = manager_result.ValueOrDie();
146 /// ...
147 /// ```
148 ///
149 /// One of the responsibilities of the EnclaveManager class is to provide sane
150 /// initial configuration to the enclaves it launches. The contents of the
151 /// EnclaveManagerOptions instance control how the default values for the
152 /// configuration are chosen.
153 class EnclaveManager {
154  public:
155  /// Fetches the EnclaveManager singleton instance.
156  ///
157  /// \return A StatusOr containing either the global EnclaveManager instance or
158  /// an error describing why it could not be returned.
159  static StatusOr<EnclaveManager *> Instance();
160 
161  /// Configures the enclave manager.
162  ///
163  /// \param options Configuration options as described in
164  /// EnclaveManagerOptions.
166 
167  /// Loads an enclave.
168  ///
169  /// Loads a new enclave with default enclave config settings and binds it to a
170  /// name. The actual work of opening the enclave is delegated to the passed
171  /// loader object.
172  ///
173  /// It is an error to specify a name which is already bound to an enclave.
174  ///
175  /// Example:
176  /// ```
177  /// LoadEnclave("/EchoEnclave", SimLoader("echoService.so"));
178  /// ```
179  ///
180  /// \param name Name to bind the loaded enclave under.
181  /// \param loader Configured enclave loader to load from.
183 
184  /// Loads an enclave.
185  ///
186  /// Loads a new enclave with custom enclave config settings and binds it to a
187  /// name. The actual work of opening the enclave is delegated to the passed
188  /// loader object.
189  ///
190  /// It is an error to specify a name which is already bound to an enclave.
191  ///
192  /// Example:
193  ///
194  /// ```
195  /// EnclaveConfig config;
196  /// ... // populate config proto.
197  /// LoadEnclave("/EchoEnclave", SimLoader("echoService.so"), config);
198  /// ```
199  ///
200  /// \param name Name to bind the loaded enclave under.
201  /// \param loader Configured enclave loader to load from.
202  /// \param config Enclave configuration to launch the enclave with.
205 
206  /// Fetches a client to a loaded enclave.
207  ///
208  /// \param name The name of an EnclaveClient that may be registered in the
209  /// EnclaveManager.
210  /// \return A mutable pointer to the EnclaveClient if the name is
211  /// registered. Otherwise returns nullptr.
212  EnclaveClient *GetClient(const std::string &name) const;
213 
214  /// Returns the name of an enclave client.
215  ///
216  /// \param client A pointer to a client that may be registered in the
217  /// EnclaveManager.
218  /// \return The name of an enclave client. If no enclave matches `client` the
219  /// empty string will be returned.
220  const std::string GetName(const EnclaveClient *client) const;
221 
222  /// Destroys an enclave.
223  ///
224  /// Destroys an enclave. This method calls `client's` EnterAndFinalize entry
225  /// point with final_input unless `skip_finalize` is true, then calls
226  /// `client's` DestroyEnclave method, and then removes client's name from the
227  /// EnclaveManager client registry. The manager owns the client, so removing
228  /// it calls client's destructor and frees its memory.
229  ///
230  /// \param client A client attached to the enclave to destroy.
231  /// \param final_input Input to pass the enclave's finalizer.
232  /// \param skip_finalize If true, the enclave is destroyed without invoking
233  /// its Finalize method.
235  bool skip_finalize = false);
236 
237  /// Fetches the shared resource manager object.
238  ///
239  /// \return The SharedResourceManager instance.
241  return &shared_resource_manager_;
242  }
243 
244  /// Fetches the shared resource manager object.
245  ///
246  /// \return The SharedResourceManager instance.
248  return &shared_resource_manager_;
249  }
250 
251  private:
252  EnclaveManager() EXCLUSIVE_LOCKS_REQUIRED(mu_);
253  EnclaveManager(EnclaveManager const &) = delete;
254  EnclaveManager &operator=(EnclaveManager const &) = delete;
255 
256  // Retrieves and returns a HostConfig proto as specified by the
257  // EnclaveManagerOptions which the EnclaveManager was configured when its
258  // sngleton instance was created.
259  HostConfig GetHostConfig() EXCLUSIVE_LOCKS_REQUIRED(mu_);
260 
261  // Loads a new enclave with custom enclave config settings and binds it to a
262  // name. The actual work of opening the enclave is delegated to the passed
263  // loader object.
264  Status LoadEnclaveInternal(const std::string &name, const EnclaveLoader &loader,
265  const EnclaveConfig &config);
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(std::mutex *unlock_when_ready);
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  std::unordered_map<std::string, std::unique_ptr<EnclaveClient>> client_by_name_;
286  std::unordered_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 = 0;
322 };
323 
324 // Stores the mapping between signals and the enclave with a handler installed
325 // for that signal.
326 class EnclaveSignalDispatcher {
327  public:
328  static EnclaveSignalDispatcher *GetInstance();
329 
330  // Associates a signal with an enclave which registers a handler for it.
331  // It's not supported for multiple enclaves to register the same signal. In
332  // that case, the latter will overwrite the former.
333  //
334  // Returns the enclave client that previous registered |signum|, or nullptr if
335  // no enclave has registered |signum| yet.
337  LOCKS_EXCLUDED(signal_enclave_map_lock_);
338 
339  // Gets the enclave that registered a handler for |signum|.
341  LOCKS_EXCLUDED(signal_enclave_map_lock_);
342 
343  // Deregisters all the signals registered by |client|.
345  LOCKS_EXCLUDED(signal_enclave_map_lock_);
346 
347  // Looks for the enclave client that registered |signum|, and calls
348  // EnterAndHandleSignal() with that enclave client. |signum|, |info| and
349  // |ucontext| are passed into the enclave.
351  void *ucontext);
352 
353  private:
354  EnclaveSignalDispatcher() = default; // Private to enforce singleton.
355  EnclaveSignalDispatcher(EnclaveSignalDispatcher const &) = delete;
356  void operator=(EnclaveSignalDispatcher const &) = delete;
357 
358  // Mapping of signal number to the enclave client that registered it.
359  std::unordered_map<int, EnclaveClient *> signal_to_client_map_
360  GUARDED_BY(signal_enclave_map_lock_);
361 
362  // A mutex that guards signal_to_client_map_ and client_to_signal_map_.
363  mutable absl::Mutex signal_enclave_map_lock_;
364 };
365 
366 } // namespace asylo
367 
368 #endif // ASYLO_PLATFORM_CORE_ENCLAVE_MANAGER_H_
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:66
static StatusOr< EnclaveManager * > Instance()
Fetches the EnclaveManager singleton instance.
virtual StatusOr< std::unique_ptr< EnclaveClient > > LoadEnclave(const std::string &name) const =0
Configuration server connection attributes.
Definition: enclave_manager.h:65
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.
Status LoadEnclave(const std::string &name, const EnclaveLoader &loader, EnclaveConfig config)
Loads an enclave.
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:240
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:71
Enclave Manager configuration.
Definition: enclave_manager.h:47
const SharedResourceManager * shared_resources() const
Fetches the shared resource manager object.
Definition: enclave_manager.h:247
Status DestroyEnclave(EnclaveClient *client, const EnclaveFinal &final_input, bool skip_finalize=false)
Destroys an enclave.
Status LoadEnclave(const std::string &name, const EnclaveLoader &loader)
Loads an enclave.
EnclaveManagerOptions()
Constructs a default EnclaveManagerOptions object.
Definition: aes_gcm_siv.h:36
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:70