-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.rs
More file actions
627 lines (555 loc) · 19.9 KB
/
main.rs
File metadata and controls
627 lines (555 loc) · 19.9 KB
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use anyhow::{anyhow, Context, Result};
use attest_data::{Attestation, Log, Nonce, Nonce32};
use clap::{Parser, Subcommand, ValueEnum};
use dice_mfg_msgs::PlatformId;
#[cfg(feature = "ipcc")]
use dice_verifier::ipcc::AttestIpcc;
#[cfg(feature = "sled-agent")]
use dice_verifier::sled_agent::AttestSledAgent;
use dice_verifier::{
hiffy::{AttestHiffy, AttestTask},
Attest, MeasurementSet, ReferenceMeasurements,
};
use log::{info, warn};
use pem_rfc7468::LineEnding;
use rats_corim::Corim;
use slog::{Drain, FilterLevel, Logger};
use std::{
fmt::{self, Debug},
fs::{self, File},
io::{self, Write},
path::{Path, PathBuf},
};
use x509_cert::{
der::{DecodePem, EncodePem},
Certificate, PkiPath,
};
fn get_attest(interface: Interface, log: &Logger) -> Result<Box<dyn Attest>> {
slog::info!(log, "attesting via {interface:?}");
match interface {
#[cfg(feature = "ipcc")]
Interface::Ipcc => Ok(Box::new(AttestIpcc::new()?)),
Interface::Rot => Ok(Box::new(AttestHiffy::new(AttestTask::Rot))),
#[cfg(feature = "sled-agent")]
Interface::SledAgent(addr) => {
Ok(Box::new(AttestSledAgent::new(addr, log)))
}
Interface::Sprot => Ok(Box::new(AttestHiffy::new(AttestTask::Sprot))),
}
}
/// Execute HIF operations exposed by the RoT Attest task.
#[derive(Debug, Parser)]
#[clap(author, version, about, long_about = None)]
struct Args {
/// Interface used for communication with the Attest task.
#[clap(value_enum, long, env, default_value_t = InterfaceArg::Rot)]
interface: InterfaceArg,
#[cfg(feature = "sled-agent")]
#[clap(short, long, env, required_if_eq("interface", "sled-agent"))]
sled_addr: Option<std::net::SocketAddrV6>,
/// Attest task command to execute.
#[command(subcommand)]
command: AttestCommand,
/// verbosity
#[clap(long, env)]
verbose: bool,
}
/// An enum of the HIF operations supported by the `Attest` interface.
#[derive(Debug, Subcommand)]
enum AttestCommand {
/// Get an attestation, this is a signature over the serialized measurement log and the
/// provided nonce: `sha3_256(log | nonce)`.
Attest {
/// Path to file holding the nonce
#[clap(env)]
nonce: PathBuf,
},
/// Get the full cert chain from the RoT encoded per RFC 6066 (PKI path)
CertChain,
/// Get the log of measurements recorded by the RoT.
Log,
/// Get the PlatformId string from the provided PkiPath
PlatformId {
/// Path to file holding the certificate chain / PkiPath
#[clap(env)]
cert_chain: PathBuf,
},
Verify {
/// Path to file holding trust anchor for the associated PKI.
#[clap(
long,
env = "VERIFIER_CLI_CA_CERT",
conflicts_with = "self_signed"
)]
ca_cert: Option<PathBuf>,
/// Verify the final cert in the provided PkiPath against itself.
#[clap(long, env, conflicts_with = "ca_cert")]
self_signed: bool,
/// Caller provided directory where artifacts are stored. If this
/// option is provided it will be used by this tool to store
/// artifacts retrieved from the RoT as part of the attestation
/// process. If omitted a temp directory will be used instead.
#[clap(long, env = "VERIFIER_CLI_WORK_DIR")]
work_dir: Option<PathBuf>,
/// Skip measurement log appraisal.
#[clap(
long,
default_value_t = false,
env = "VERIFIER_CLI_SKIP_APPRAISAL"
)]
skip_appraisal: bool,
/// Path to file holding the reference measurement corpus
#[clap(env, env = "VERIFIER_CLI_CORPUS")]
corpus: Option<PathBuf>,
},
/// Verify signature over Attestation
VerifyAttestation {
/// Path to file holding the alias cert
#[clap(long, env)]
alias_cert: PathBuf,
/// Path to file holding the attestation
#[clap(env)]
attestation: PathBuf,
/// Path to file holding the log
#[clap(long, env)]
log: PathBuf,
/// Path to file holding the nonce
#[clap(long, env)]
nonce: PathBuf,
},
/// Walk the PkiPath formatted certificate chain verifying each link.
VerifyCertChain {
/// Path to file holding trust anchor for the associated PKI.
#[clap(long, env, conflicts_with = "self_signed")]
ca_cert: Option<PathBuf>,
/// Verify the final cert in the provided PkiPath against itself.
#[clap(long, env, conflicts_with = "ca_cert")]
self_signed: bool,
/// Path to file holding the certificate chain / PkiPath.
#[clap(env)]
cert_chain: PathBuf,
},
/// Verify the measurements from the log and cert chain against the
/// provided measurement corpus.
VerifyMeasurements {
/// Path to file holding the certificate chain / PkiPath.
#[clap(env)]
cert_chain: PathBuf,
/// Path to file holding the log
#[clap(env)]
log: PathBuf,
/// Path to file holding the reference measurement corpus
#[clap(env)]
corpus: PathBuf,
},
/// Show the set of measurements currently on the RoT. This includes
/// the cert chain and the measurement log
MeasurementSet,
}
#[derive(Clone, Debug)]
pub enum Interface {
#[cfg(feature = "ipcc")]
Ipcc,
Rot,
#[cfg(feature = "sled-agent")]
SledAgent(std::net::SocketAddrV6),
Sprot,
}
/// An enum of the possible routes to the `Attest` task.
#[derive(Clone, Debug, ValueEnum)]
pub enum InterfaceArg {
#[cfg(feature = "ipcc")]
Ipcc,
Rot,
#[cfg(feature = "sled-agent")]
SledAgent,
Sprot,
}
/// An enum of the possible certificate encodings.
#[derive(Clone, Debug, ValueEnum)]
enum Encoding {
Der,
Pem,
}
impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Encoding::Der => write!(f, "der"),
Encoding::Pem => write!(f, "pem"),
}
}
}
#[tokio::main]
async fn main() -> Result<()> {
let args = Args::parse();
let stderr_decorator = slog_term::TermDecorator::new().build();
let stderr_drain =
slog_term::FullFormat::new(stderr_decorator).build().fuse();
let drain = slog_envlogger::LogBuilder::new(stderr_drain)
.parse("RUST_LOG")
.filter(
None,
if args.verbose {
FilterLevel::Debug
} else {
FilterLevel::Warning
},
)
.build()
.fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let logger = Logger::root(drain, slog::o!());
let interface = match args.interface {
#[cfg(feature = "ipcc")]
InterfaceArg::Ipcc => Interface::Ipcc,
InterfaceArg::Rot => Interface::Rot,
#[cfg(feature = "sled-agent")]
InterfaceArg::SledAgent => {
Interface::SledAgent(args.sled_addr.unwrap())
}
InterfaceArg::Sprot => Interface::Sprot,
};
let attest = get_attest(interface, &logger)?;
match args.command {
AttestCommand::Attest { nonce } => {
let nonce = fs::read(&nonce)
.context(format!("Nonce bytes from: {}", nonce.display()))?;
let nonce =
Nonce::try_from(nonce).context("Nonce from file contents")?;
let attestation = attest
.attest(&nonce)
.await
.context("Getting attestation with provided Nonce")?;
// serialize attestation to json & write to file
let mut attestation = serde_json::to_string(&attestation)
.context("Attestation to JSON")?;
attestation.push('\n');
io::stdout()
.write_all(attestation.as_bytes())
.context("Write Attestation as JSON to stdout")?;
io::stdout().flush().context("Flush stdout")?;
}
AttestCommand::CertChain => {
let cert_chain = attest
.get_certificates()
.await
.context("Getting attestation certificate chain")?;
for cert in cert_chain {
let cert = cert
.to_pem(LineEnding::default())
.context("Encode certificate as PEM")?;
io::stdout()
.write_all(cert.as_bytes())
.context("Write cert chain to stdout")?;
}
io::stdout().flush().context("Flush stdout")?;
}
AttestCommand::Log => {
let log = attest
.get_measurement_log()
.await
.context("Getting attestation measurement log")?;
let mut log = serde_json::to_string(&log)
.context("Encode measurement log as JSON")?;
log.push('\n');
io::stdout()
.write_all(log.as_bytes())
.context("Write measurement log to stdout")?;
io::stdout().flush().context("Flush stdout")?;
}
AttestCommand::PlatformId { cert_chain } => {
let cert_chain = fs::read(&cert_chain).context(format!(
"Read attestation certificate chain bytes from file: {}",
cert_chain.display()
))?;
let cert_chain: PkiPath = Certificate::load_pem_chain(&cert_chain)
.context("Parse certificate chain")?;
let platform_id = PlatformId::try_from(&cert_chain)
.context("PlatformId from attestation cert chain")?;
let platform_id = platform_id.as_str();
println!("{platform_id}");
}
AttestCommand::Verify {
ca_cert,
corpus,
self_signed,
skip_appraisal,
work_dir,
} => {
// Use the directory provided by the caller to hold intermediate
// files, or fall back to a temp dir.
let platform_id = match work_dir {
Some(w) => {
verify(
attest.as_ref(),
ca_cert.as_deref(),
corpus.as_deref(),
self_signed,
&w,
)
.await?
}
None => {
if corpus.is_none() && !skip_appraisal {
return Err(anyhow!("no corpus provided but not instructed to skip measurement log appraisal"));
}
let work_dir = tempfile::tempdir()?;
verify(
attest.as_ref(),
ca_cert.as_deref(),
corpus.as_deref(),
self_signed,
work_dir.as_ref(),
)
.await?
}
};
println!("{platform_id}");
}
AttestCommand::VerifyAttestation {
alias_cert,
attestation,
log,
nonce,
} => {
verify_attestation(&alias_cert, &attestation, &log, &nonce)?;
}
AttestCommand::VerifyCertChain {
cert_chain,
ca_cert,
self_signed,
} => {
verify_cert_chain(ca_cert.as_deref(), &cert_chain, self_signed)?;
}
AttestCommand::VerifyMeasurements {
cert_chain,
log,
corpus,
} => {
verify_measurements(&cert_chain, &log, &corpus)?;
}
AttestCommand::MeasurementSet => {
let set = measurement_set(attest.as_ref()).await?;
for item in set.into_iter() {
println!("* {item}");
}
}
}
Ok(())
}
async fn measurement_set(attest: &dyn Attest) -> Result<MeasurementSet> {
info!("getting measurement log");
let log = attest
.get_measurement_log()
.await
.context("Get measurement log from attestor")?;
let mut cert_chain = Vec::new();
let certs = attest
.get_certificates()
.await
.context("Get certificate chain from attestor")?;
for (index, cert) in certs.iter().enumerate() {
info!("writing cert[{index}]");
let pem = cert
.to_pem(LineEnding::default())
.context(format!("Encode cert {index} as PEM"))?;
cert_chain
.write_all(pem.as_bytes())
.context(format!("Write cert {index}",))?;
}
let cert_chain: PkiPath = Certificate::load_pem_chain(&cert_chain)
.context("loading PkiPath from PEM cert chain")?;
MeasurementSet::from_artifacts(&cert_chain, &log)
.context("MeasurementSet from PkiPath")
}
// Check that the measurments in `cert_chain` and `log` are all present in
// the `corpus`.
// NOTE: The output of this function is only as trustworthy as its inputs.
// These must be verified independently.
fn verify_measurements(
cert_chain: &Path,
log: &Path,
corpus: &Path,
) -> Result<()> {
let corpus = Corim::from_file(corpus)
.context(format!("Corim from file path: {}", corpus.display()))?;
let corpus = ReferenceMeasurements::try_from(std::slice::from_ref(&corpus))
.context("ReferenceMeasurements from CoRIM")?;
let cert_chain = fs::read(cert_chain).context(format!(
"Read cert chain from file: {}",
cert_chain.display()
))?;
let cert_chain: PkiPath = Certificate::load_pem_chain(&cert_chain)
.context("loading PkiPath from PEM cert chain")?;
let log = fs::read_to_string(log).context(format!(
"Reading measurement log from file: {}",
log.display()
))?;
let log: Log =
serde_json::from_str(&log).context("Deserialize Log from JSON")?;
let measurements = MeasurementSet::from_artifacts(&cert_chain, &log)
.context("MeasurementSet from PkiPath")?;
dice_verifier::verify_measurements(&measurements, &corpus)
.context("Verify measurements")
}
async fn verify(
attest: &dyn Attest,
ca_cert: Option<&Path>,
corpus: Option<&Path>,
self_signed: bool,
work_dir: &Path,
) -> Result<PlatformId> {
// generate nonce from RNG
info!("getting Nonce from platform RNG");
let nonce = Nonce::from_platform_rng(Nonce32::LENGTH)
.context("Nonce from platform RNG")?;
// write nonce to temp dir
let nonce_path = work_dir.join("nonce.bin");
info!("writing nonce to: {}", nonce_path.display());
fs::write(&nonce_path, nonce)
.context(format!("Write nonce to file: {}", nonce_path.display()))?;
// get attestation
info!("getting attestation");
let attestation = attest
.attest(&nonce)
.await
.context("Get attestation with nonce")?;
// serialize attestation to json & write to file
let mut attestation = serde_json::to_string(&attestation)
.context("Serialize attestation to JSON")?;
attestation.push('\n');
let attestation_path = work_dir.join("attest.json");
info!("writing attestation to: {}", attestation_path.display());
fs::write(&attestation_path, &attestation).context(format!(
"Write attestation to file: {}",
attestation_path.display()
))?;
// get log
info!("getting measurement log");
let log = attest
.get_measurement_log()
.await
.context("Get measurement log from attestor")?;
let mut log = serde_json::to_string(&log)
.context("Serialize measurement log to JSON")?;
log.push('\n');
let log_path = work_dir.join("log.json");
info!("writing measurement log to: {}", log_path.display());
fs::write(&log_path, &log).context(format!(
"Write measurement log to file: {}",
log_path.display()
))?;
// get cert chain
info!("getting cert chain");
let cert_chain_path = work_dir.join("cert-chain.pem");
let mut cert_chain = File::create(&cert_chain_path).context(format!(
"Create file for cert chain: {}",
cert_chain_path.display()
))?;
let alias_cert_path = work_dir.join("alias.pem");
let certs = attest
.get_certificates()
.await
.context("Get certificate chain from attestor")?;
// the first cert in the chain / the leaf cert is the one
// used to sign attestations
info!("writing alias cert to: {}", alias_cert_path.display());
let pem = certs[0]
.to_pem(LineEnding::default())
.context("Encode alias cert as PEM")?;
fs::write(&alias_cert_path, pem)?;
for (index, cert) in certs.iter().enumerate() {
info!("writing cert[{}] to: {}", index, cert_chain_path.display());
let pem = cert
.to_pem(LineEnding::default())
.context(format!("Encode cert {index} as PEM"))?;
cert_chain.write_all(pem.as_bytes()).context(format!(
"Write cert {index} to file: {}",
cert_chain_path.display()
))?;
}
verify_cert_chain(ca_cert, &cert_chain_path, self_signed)?;
info!("cert chain verified");
verify_attestation(
&alias_cert_path,
&attestation_path,
&log_path,
&nonce_path,
)?;
info!("attestation verified");
if let Some(corpus) = corpus {
verify_measurements(&cert_chain_path, &log_path, corpus)?;
info!("measurements verified");
} else {
warn!("measurement corpus is None: skipping log appraisal");
}
let cert_chain = fs::read(&cert_chain_path).context(format!(
"read cert chain from path: {}",
cert_chain_path.display()
))?;
let cert_chain: PkiPath = Certificate::load_pem_chain(&cert_chain)
.context("Parse cert chain from PEM")?;
let platform_id = PlatformId::try_from(&cert_chain)
.context("PlatformId from attestation cert chain")?;
Ok(platform_id)
}
fn verify_attestation(
alias_cert: &Path,
attestation: &Path,
log: &Path,
nonce: &Path,
) -> Result<()> {
info!("verifying attestation");
let attestation = fs::read_to_string(attestation).context(format!(
"Read Attestation from file: {}",
attestation.display()
))?;
let attestation: Attestation = serde_json::from_str(&attestation)
.context("Deserialize Attestation from JSON")?;
let log = fs::read_to_string(log)
.context(format!("Read Log from file: {}", log.display()))?;
let log: Log =
serde_json::from_str(&log).context("Deserialize Log from JSON")?;
let nonce = fs::read(nonce)
.context(format!("Read Nonce from file: {}", nonce.display()))?;
let nonce =
Nonce::try_from(nonce).context("Deserialize Nonce from JSON")?;
let alias = fs::read(alias_cert).context(format!(
"Read alias cert from file: {}",
alias_cert.display()
))?;
let alias =
Certificate::from_pem(&alias).context("Parse alias cert from PEM")?;
dice_verifier::verify_attestation(&alias, &attestation, &log, &nonce)
.context("Verify attestation")
}
fn verify_cert_chain(
ca_cert: Option<&Path>,
cert_chain: &Path,
self_signed: bool,
) -> Result<()> {
info!("veryfying cert chain");
if !self_signed && ca_cert.is_none() {
return Err(anyhow!("`ca-cert` or `self-signed` is required"));
}
let cert_chain = fs::read(cert_chain).context(format!(
"Reading certs from file: {}",
cert_chain.display()
))?;
let cert_chain: PkiPath = Certificate::load_pem_chain(&cert_chain)
.context("Parsing certs from PEM")?;
let roots = if let Some(p) = ca_cert {
let cert = fs::read(p)?;
let cert = Certificate::from_pem(cert)?;
Some(vec![cert])
} else {
warn!("allowing self-signed cert chain");
None
};
let _ = dice_verifier::verify_cert_chain(&cert_chain, roots.as_deref())
.context("Verify cert chain")?;
Ok(())
}