qos_core 0.10.0

Core components and logic for QuorumOS applications
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Logic for accessing read only QOS state.

use std::{
	fs,
	os::unix::fs::PermissionsExt,
	path::{Path, PathBuf},
};

use qos_p256::P256Pair;

use crate::protocol::{
	ProtocolError, services::boot::VersionedManifestEnvelope,
};

/// Handle for accessing the quorum key.
#[derive(Debug, Clone)]
pub struct QuorumKeyHandle {
	quorum: String,
}

impl QuorumKeyHandle {
	/// Create a new instance of [`Self`].
	#[must_use]
	pub fn new(quorum: String) -> Self {
		Self { quorum }
	}

	/// Get the Quorum Key pair.
	///
	/// # Errors
	///
	/// Errors if the Quorum Key has not been put.
	pub fn get_quorum_key(&self) -> Result<P256Pair, ProtocolError> {
		let pair = P256Pair::from_hex_file(&self.quorum)
			.map_err(ProtocolError::FailedToGetQuorumKey)?;
		Ok(pair)
	}
}

/// Handle for accessing the enclave ephemeral key.
#[derive(Debug, Clone, Copy)]
pub struct EphemeralKeyHandle<S = String> {
	ephemeral_key_path: S,
}

impl<P> EphemeralKeyHandle<P>
where
	P: AsRef<Path>,
{
	/// Create a new instance of [`Self`].
	#[must_use]
	pub fn new(ephemeral_key_path: P) -> Self {
		Self { ephemeral_key_path }
	}

	/// Get the Ephemeral Key Pair
	///
	/// # Errors
	///
	/// Errors if the Ephemeral key pair isn't present or can't be built.
	pub fn get_ephemeral_key(&self) -> Result<P256Pair, ProtocolError> {
		let pair = P256Pair::from_hex_file(&self.ephemeral_key_path)
			.map_err(ProtocolError::FailedToGetEphemeralKey)?;
		Ok(pair)
	}
}

/// Handles for read only state accessible to all of QOS.
///
/// All data here should be "put" once at some point in the boot flow. Once
/// "put", it can only be read.
#[derive(Debug, Clone)]
pub struct Handles {
	/// Path to the file containing the PEM encoded Ephemeral Key.
	ephemeral: EphemeralKeyHandle,
	/// Path to the file containing the PEM encoded Quorum Key.
	quorum: QuorumKeyHandle,
	/// Path to the file containing the Borsh encoded [`ManifestEnvelope`].
	manifest: String,
	/// Path to the file containing the pivot.
	pivot: String,
}

impl Handles {
	/// Create a new instance of [`Self`].
	#[must_use]
	pub fn new(
		ephemeral: String,
		quorum: String,
		manifest: String,
		pivot: String,
	) -> Self {
		Self {
			ephemeral: EphemeralKeyHandle::new(ephemeral),
			quorum: QuorumKeyHandle::new(quorum),
			manifest,
			pivot,
		}
	}

	/// Get the Ephemeral Key pair.
	///
	/// # Errors
	///
	/// Errors if the Ephemeral Key isn't present.
	pub fn get_ephemeral_key(&self) -> Result<P256Pair, ProtocolError> {
		self.ephemeral.get_ephemeral_key()
	}

	/// Put the Ephemeral Key pair.
	///
	/// # Errors
	///
	/// Errors if the Ephemeral Key has already been put.
	pub fn put_ephemeral_key(
		&self,
		pair: &P256Pair,
	) -> Result<(), ProtocolError> {
		Self::write_as_read_only(
			&self.ephemeral.ephemeral_key_path,
			&pair.to_master_seed_hex(),
			ProtocolError::FailedToPutEphemeralKey,
		)
	}

	/// Rotate the ephemeral key to a new key pair. This happens post-boot, to protect key material encrypted to it.
	/// QOS apps can then use this new ephemeral key without worrying about implications for boot flows.
	///
	/// # Errors
	///
	/// Errors if the Ephemeral key isn't present already, or if the delete fails, or if the new write fails.
	pub fn rotate_ephemeral_key(
		&self,
		new_pair: &P256Pair,
	) -> Result<(), ProtocolError> {
		let path = Path::new(&self.ephemeral.ephemeral_key_path);
		if !path.exists() {
			Err(ProtocolError::CannotRotateNonExistentEphemeralKey)?;
		}

		fs::remove_file(path).map_err(|e| {
			ProtocolError::CannotDeleteEphemeralKey(e.to_string())
		})?;

		Self::write_as_read_only(
			path,
			&new_pair.to_master_seed_hex(),
			ProtocolError::FailedToPutEphemeralKey,
		)
	}

	/// Get the Quorum Key pair.
	///
	/// # Errors
	///
	/// Errors if the Quorum Key has not been put.
	pub fn get_quorum_key(&self) -> Result<P256Pair, ProtocolError> {
		self.quorum.get_quorum_key()
	}

	/// Put the Quorum Key pair.
	///
	/// # Errors
	///
	/// Errors if the Quorum Key has already been put.
	pub fn put_quorum_key(&self, pair: &P256Pair) -> Result<(), ProtocolError> {
		Self::write_as_read_only(
			&self.quorum.quorum,
			&pair.to_master_seed_hex(),
			ProtocolError::FailedToPutQuorumKey,
		)
	}

	/// Returns true if the Quorum Key file exists.
	#[must_use]
	pub fn quorum_key_exists(&self) -> bool {
		Path::new(&self.quorum.quorum).exists()
	}

	/// Get the Manifest.
	///
	/// # Errors
	///
	/// Errors if the Manifest has not been put.
	pub fn get_manifest_envelope(
		&self,
	) -> Result<VersionedManifestEnvelope, ProtocolError> {
		let contents = fs::read(&self.manifest)
			.map_err(|_| ProtocolError::FailedToGetManifestEnvelope)?;
		let manifest =
			VersionedManifestEnvelope::try_from_slice_compat(&contents)
				.map_err(|_| ProtocolError::FailedToGetManifestEnvelope)?;

		Ok(manifest)
	}

	/// Put the Manifest.
	///
	/// # Errors
	///
	/// Errors if the Manifest has already been put.
	pub fn put_manifest_envelope<E>(
		&self,
		manifest_envelope: E,
	) -> Result<(), ProtocolError>
	where
		E: Into<VersionedManifestEnvelope>,
	{
		let manifest_envelope = manifest_envelope.into();
		Self::write_as_read_only(
			&self.manifest,
			&manifest_envelope
				.to_storage_vec()
				.map_err(|_| ProtocolError::FailedToPutManifestEnvelope)?,
			ProtocolError::FailedToPutManifestEnvelope,
		)
	}

	/// Put the Manifest, overwriting it if it already exists.
	///
	/// **Warning**: This should not be used after pivoting. It is only meant to
	/// be used when updating the manifest envelope while provisioning.
	pub(crate) fn mutate_manifest_envelope<
		F: FnOnce(VersionedManifestEnvelope) -> VersionedManifestEnvelope,
	>(
		&self,
		mutate: F,
	) -> Result<(), ProtocolError> {
		let manifest_envelope = self.get_manifest_envelope()?;

		let manifest_envelope = mutate(manifest_envelope);

		// Temporarily set permissions so we can write the manifest envelope
		fs::set_permissions(
			&self.manifest,
			std::fs::Permissions::from_mode(0o666),
		)?;
		fs::write(
			&self.manifest,
			manifest_envelope
				.to_storage_vec()
				.map_err(|_| ProtocolError::FailedToPutManifestEnvelope)?,
		)
		.map_err(|_| ProtocolError::FailedToPutManifestEnvelope)?;

		// Set the permissions back to read only
		fs::set_permissions(
			&self.manifest,
			std::fs::Permissions::from_mode(0o444),
		)?;

		Ok(())
	}

	/// Returns true if the Manifest file exists.
	#[must_use]
	pub fn manifest_envelope_exists(&self) -> bool {
		Path::new(&self.manifest).exists()
	}

	/// Get the path to the Pivot binary.
	#[must_use]
	pub fn pivot_path(&self) -> String {
		self.pivot.clone()
	}

	/// Put the Pivot binary, ensuring it is an executable.
	///
	/// # Errors
	///
	/// Returns [`ProtocolError`] if the pivot already exists, the
	/// directory cannot be created, or the file cannot be written.
	pub fn put_pivot(&self, pivot: &[u8]) -> Result<(), ProtocolError> {
		if Path::new(&self.pivot).exists() {
			Err(ProtocolError::CannotModifyPostPivotStatic)?;
		}

		if let Some(parent) = Path::new(&self.pivot).parent()
			&& !parent.exists()
		{
			fs::create_dir_all(parent)
				.map_err(|_| ProtocolError::FailedToPutPivot)?;
		}

		fs::write(&self.pivot, pivot)
			.map_err(|_| ProtocolError::FailedToPutPivot)?;
		fs::set_permissions(
			&self.pivot,
			std::fs::Permissions::from_mode(0o111),
		)
		.map_err(|_| ProtocolError::FailedToPutPivot)?;
		Ok(())
	}

	/// Returns true if the Pivot file exists.
	#[must_use]
	pub fn pivot_exists(&self) -> bool {
		Path::new(&self.pivot).exists()
	}

	/// Helper function for ready only writes that also ensures full write atomicity by renaming at the end.
	fn write_as_read_only<P: AsRef<Path>>(
		path: P,
		buf: &[u8],
		err: ProtocolError,
	) -> Result<(), ProtocolError> {
		if path.as_ref().exists() {
			Err(ProtocolError::CannotModifyPostPivotStatic)?;
		}

		if let Some(parent) = path.as_ref().parent()
			&& !parent.exists()
		{
			fs::create_dir_all(parent).map_err(|_| err.clone())?;
		}

		let tmp_path = PathBuf::from(path.as_ref()).with_extension("tmp");

		fs::write(&tmp_path, buf).map_err(|_| err.clone())?;

		// atomically move to destination once fully written to prevent partial reads
		fs::rename(&tmp_path, &path)?;

		fs::set_permissions(&path, fs::Permissions::from_mode(0o444))
			.map_err(|_| err)?;

		Ok(())
	}
}

#[cfg(test)]
mod test {

	use qos_crypto::sha_256;
	use qos_test_primitives::PathWrapper;

	use super::*;
	use crate::protocol::services::boot::{
		Manifest, ManifestEnvelope, ManifestSet, Namespace, NitroConfig,
		PatchSet, PivotConfig, RestartPolicy, ShareSet,
	};

	#[test]
	fn put_ephemeral_key_is_read_only_write() {
		let pivot_file =
			PathWrapper::from("put_ephemeral_key_is_read_only_write.pivot");
		let ephemeral_file = PathWrapper::from(
			"put_ephemeral_key_is_read_only_write_eph.secret",
		);
		let quorum_file = PathWrapper::from(
			"put_ephemeral_key_is_read_only_write_quor.secret",
		);
		let manifest_file =
			PathWrapper::from("put_ephemeral_key_is_read_only_write.manifest");

		let handles = Handles::new(
			ephemeral_file.display().to_string(),
			quorum_file.display().to_string(),
			manifest_file.display().to_string(),
			pivot_file.display().to_string(),
		);

		let ephemeral_key = P256Pair::generate().unwrap();
		let result = handles.put_ephemeral_key(&ephemeral_key);
		let error = handles.put_ephemeral_key(&ephemeral_key).unwrap_err();

		assert!(result.is_ok());
		assert_eq!(error, ProtocolError::CannotModifyPostPivotStatic);
		assert!(handles.get_ephemeral_key().unwrap() == ephemeral_key);
	}

	#[test]
	fn put_quorum_key_is_read_only_write() {
		let pivot_file =
			PathWrapper::from("put_quorum_key_is_read_only_write.pivot");
		let ephemeral_file =
			PathWrapper::from("put_quorum_key_is_read_only_write_eph.secret");
		let quorum_file =
			PathWrapper::from("put_quorum_key_is_read_only_write_quor.secret");
		let manifest_file =
			PathWrapper::from("put_quorum_key_is_read_only_write.manifest");

		let handles = Handles::new(
			ephemeral_file.display().to_string(),
			quorum_file.display().to_string(),
			manifest_file.display().to_string(),
			pivot_file.display().to_string(),
		);

		let quorum_key = P256Pair::generate().unwrap();
		let result = handles.put_quorum_key(&quorum_key);
		let error = handles.put_quorum_key(&quorum_key).unwrap_err();

		assert!(result.is_ok());
		assert_eq!(error, ProtocolError::CannotModifyPostPivotStatic);
		assert!(handles.quorum_key_exists());
		assert!(handles.get_quorum_key().unwrap() == quorum_key);
	}

	#[test]
	fn put_pivot_is_read_only_write() {
		let pivot_file =
			PathWrapper::from("put_pivot_is_read_only_write.pivot");
		let ephemeral_file =
			PathWrapper::from("put_pivot_is_read_only_write_eph.secret");
		let quorum_file =
			PathWrapper::from("put_pivot_is_read_only_write_quor.secret");

		let manifest_file =
			PathWrapper::from("put_pivot_is_read_only_write.manifest");

		let handles = Handles::new(
			ephemeral_file.display().to_string(),
			quorum_file.display().to_string(),
			manifest_file.display().to_string(),
			pivot_file.display().to_string(),
		);

		let pivot = b"this is a pivot binary".to_vec();
		let result = handles.put_pivot(&pivot);
		let error = handles.put_pivot(&pivot).unwrap_err();

		assert!(result.is_ok());
		assert_eq!(error, ProtocolError::CannotModifyPostPivotStatic);
		assert!(handles.pivot_exists());
	}

	#[test]
	fn put_manifest_is_read_only_write() {
		let pivot_file =
			PathWrapper::from("put_manifest_is_read_only_write.pivot");
		let ephemeral_file =
			PathWrapper::from("put_manifest_is_read_only_write_eph.secret");
		let quorum_file =
			PathWrapper::from("put_manifest_is_read_only_write_quor.secret");
		let manifest_file =
			PathWrapper::from("put_manifest_is_read_only_write.manifest");

		let handles = Handles::new(
			ephemeral_file.display().to_string(),
			quorum_file.display().to_string(),
			manifest_file.display().to_string(),
			pivot_file.display().to_string(),
		);

		let pivot = b"this is a pivot binary".to_vec();

		let manifest = Manifest {
			namespace: Namespace {
				nonce: 420,
				name: "vape lord".to_string(),
				quorum_key: P256Pair::generate()
					.unwrap()
					.public_key()
					.to_bytes(),
			},
			enclave: NitroConfig {
				pcr0: vec![4; 32],
				pcr1: vec![3; 32],
				pcr2: vec![2; 32],
				pcr3: vec![1; 32],
				aws_root_certificate: b"cert lord".to_vec(),
				qos_commit: "mock qos commit".to_string(),
			},
			pivot: PivotConfig {
				hash: sha_256(&pivot),
				restart: RestartPolicy::Always,
				args: vec![],
				..Default::default()
			},
			manifest_set: ManifestSet { threshold: 2, members: vec![] },
			share_set: ShareSet { threshold: 2, members: vec![] },
			patch_set: PatchSet::default(),
		};

		let manifest_envelope =
			VersionedManifestEnvelope::V1(ManifestEnvelope {
				manifest,
				manifest_set_approvals: vec![],
				share_set_approvals: vec![],
			});

		let result = handles.put_manifest_envelope(&manifest_envelope);
		let error =
			handles.put_manifest_envelope(&manifest_envelope).unwrap_err();

		assert!(result.is_ok());
		assert_eq!(error, ProtocolError::CannotModifyPostPivotStatic);
		assert!(handles.manifest_envelope_exists());
		assert_eq!(handles.get_manifest_envelope().unwrap(), manifest_envelope);
	}
}