Skip to content

Commit 4fcc07c

Browse files
committed
Return a future from accept after the TCP accept completes
1 parent b3b15d9 commit 4fcc07c

3 files changed

Lines changed: 173 additions & 155 deletions

File tree

tls/examples/server.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,8 @@ async fn main() {
9393
.unwrap();
9494

9595
loop {
96-
let (stream, _) = server.accept(args.corpus.as_slice()).await.unwrap();
96+
let (stream, _) =
97+
server.accept(args.corpus.clone()).await.await.unwrap();
9798
let platform_id = stream.peer_platform_id().as_str().unwrap();
9899
info!(log, "connected to attested peer: {platform_id}");
99100
let (mut reader, mut writer) = split(stream);

tls/src/lib.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ mod tests {
388388
.unwrap();
389389

390390
let (mut stream, _) =
391-
server.accept(corpus.as_slice()).await.unwrap();
391+
server.accept(corpus.clone()).await.await.unwrap();
392392
let mut buf = String::new();
393393
stream.read_to_string(&mut buf).await.unwrap();
394394

@@ -475,7 +475,7 @@ mod tests {
475475
.unwrap();
476476

477477
let (mut stream, _) =
478-
server.accept(corpus.as_slice()).await.unwrap();
478+
server.accept(corpus.clone()).await.await.unwrap();
479479
let mut buf = String::new();
480480
stream.read_to_string(&mut buf).await.unwrap();
481481

@@ -563,7 +563,7 @@ mod tests {
563563
.unwrap();
564564

565565
// We never expect this to succeed
566-
let _ = match server.accept(corpus.as_slice()).await {
566+
let _ = match server.accept(corpus.clone()).await.await {
567567
Ok(_) => panic!("This should not succed"),
568568
Err(_) => done_tx.send(()),
569569
};

tls/src/server.rs

Lines changed: 168 additions & 151 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,11 @@ use rustls::{
2828
CipherSuite, ServerConfig, SignatureScheme,
2929
};
3030
use slog::{error, info};
31+
use std::future::Future;
3132
use std::net::SocketAddrV6;
3233
use std::sync::Arc;
3334
use tokio::net::{TcpListener, TcpStream};
34-
use tokio_rustls::TlsAcceptor;
35+
use tokio_rustls::{Accept as TlsAccept, TlsAcceptor};
3536
use x509_cert::{
3637
der::{Decode, DecodePem},
3738
Certificate,
@@ -250,157 +251,172 @@ impl Server {
250251

251252
pub async fn accept(
252253
&mut self,
253-
corpus: &[Utf8PathBuf],
254-
) -> Result<(Stream<TcpStream>, core::net::SocketAddr), Error> {
255-
// load corims into a set of ReferenceMeasurements
256-
let mut corims = Vec::new();
257-
for c in corpus {
258-
corims.push(Corim::from_file(c)?);
259-
}
260-
let corpus = ReferenceMeasurements::try_from(corims.as_slice())?;
261-
262-
let (stream, addr) = self.tcp_listener.accept().await?;
263-
let mut stream = self.tls_acceptor.clone().accept(stream).await?;
264-
265-
// get PlatformId from server TLS / Trust Quorum cert chain
266-
let (_, conn) = stream.get_ref();
267-
let tq_platform_id = if let Some(tls_certs) = conn.peer_certificates() {
268-
let mut pki_path = Vec::new();
269-
for der in tls_certs.iter() {
270-
pki_path.push(Certificate::from_der(der).map_err(|_| {
271-
rustls::Error::InvalidCertificate(
272-
rustls::CertificateError::BadEncoding,
273-
)
274-
})?)
254+
corpus: Vec<Utf8PathBuf>,
255+
) -> impl Future<
256+
Output = Result<(Stream<TcpStream>, core::net::SocketAddr), Error>,
257+
> + use<'_> {
258+
// This is where the actual socket accept occurs.
259+
//
260+
// Everything else takes a while and therefore we return a future that
261+
// can be awaited inside a spawned taks.
262+
let accept_res = self.tcp_listener.accept().await;
263+
async {
264+
let (stream, addr) = accept_res?;
265+
// load corims into a set of ReferenceMeasurements
266+
let mut corims = Vec::new();
267+
for c in corpus {
268+
corims.push(Corim::from_file(c)?);
275269
}
276-
dice_mfg_msgs::PlatformId::try_from(&pki_path)?
277-
} else {
278-
return Err(Error::NoTQCerts);
279-
};
280-
281-
// get version from the client
282-
let version_bytes = recv_msg(&mut stream).await?;
283-
let version =
284-
u32::from_le_bytes(version_bytes[..4].try_into().unwrap());
285-
286-
if version == CURRENT_PROTOCOL_VERSION {
287-
// we're good to go
288-
let mut buf = vec![0u8; ProtocolResult::MAX_SIZE];
289-
let resp: ProtocolResult = Ok(version);
290-
let resp_len = hubpack::serialize(&mut buf, &resp)?;
291-
send_msg(&mut stream, &buf[..resp_len]).await?;
292-
} else if version == PREVIOUS_PROTOCOL_VERSION {
293-
// We eventually want to support older protocol
294-
let mut buf = vec![0u8; ProtocolResult::MAX_SIZE];
295-
let resp: ProtocolResult = Ok(version);
296-
let resp_len = hubpack::serialize(&mut buf, &resp)?;
297-
send_msg(&mut stream, &buf[..resp_len]).await?;
298-
} else {
299-
// We can't deal with this
300-
// We eventually want to support older protocol
301-
let mut buf = vec![0u8; ProtocolResult::MAX_SIZE];
302-
let resp: ProtocolResult = Err(());
303-
let resp_len = hubpack::serialize(&mut buf, &resp)?;
304-
send_msg(&mut stream, &buf[..resp_len]).await?;
305-
// Client has given us something bad, time to give up
306-
return Err(Error::ProtocolVersion);
307-
}
270+
let corpus = ReferenceMeasurements::try_from(corims.as_slice())?;
271+
272+
let mut stream = self.tls_acceptor.clone().accept(stream).await?;
273+
274+
// get PlatformId from server TLS / Trust Quorum cert chain
275+
let (_, conn) = stream.get_ref();
276+
let tq_platform_id = if let Some(tls_certs) =
277+
conn.peer_certificates()
278+
{
279+
let mut pki_path = Vec::new();
280+
for der in tls_certs.iter() {
281+
pki_path.push(Certificate::from_der(der).map_err(|_| {
282+
rustls::Error::InvalidCertificate(
283+
rustls::CertificateError::BadEncoding,
284+
)
285+
})?)
286+
}
287+
dice_mfg_msgs::PlatformId::try_from(&pki_path)?
288+
} else {
289+
return Err(Error::NoTQCerts);
290+
};
308291

309-
// Wait for the protocol ACK
310-
let protocol_ack_bytes = recv_msg(&mut stream).await?;
311-
let (protocol_ack, _): (ProtocolRequestAck, _) =
312-
hubpack::deserialize(&protocol_ack_bytes)?;
292+
// get version from the client
293+
let version_bytes = recv_msg(&mut stream).await?;
294+
let version =
295+
u32::from_le_bytes(version_bytes[..4].try_into().unwrap());
296+
297+
if version == CURRENT_PROTOCOL_VERSION {
298+
// we're good to go
299+
let mut buf = vec![0u8; ProtocolResult::MAX_SIZE];
300+
let resp: ProtocolResult = Ok(version);
301+
let resp_len = hubpack::serialize(&mut buf, &resp)?;
302+
send_msg(&mut stream, &buf[..resp_len]).await?;
303+
} else if version == PREVIOUS_PROTOCOL_VERSION {
304+
// We eventually want to support older protocol
305+
let mut buf = vec![0u8; ProtocolResult::MAX_SIZE];
306+
let resp: ProtocolResult = Ok(version);
307+
let resp_len = hubpack::serialize(&mut buf, &resp)?;
308+
send_msg(&mut stream, &buf[..resp_len]).await?;
309+
} else {
310+
// We can't deal with this
311+
// We eventually want to support older protocol
312+
let mut buf = vec![0u8; ProtocolResult::MAX_SIZE];
313+
let resp: ProtocolResult = Err(());
314+
let resp_len = hubpack::serialize(&mut buf, &resp)?;
315+
send_msg(&mut stream, &buf[..resp_len]).await?;
316+
// Client has given us something bad, time to give up
317+
return Err(Error::ProtocolVersion);
318+
}
313319

314-
match protocol_ack {
315-
Ok(v) => {
316-
if v != version {
317-
// this isn't right...
318-
return Err(Error::ClientMismatch);
320+
// Wait for the protocol ACK
321+
let protocol_ack_bytes = recv_msg(&mut stream).await?;
322+
let (protocol_ack, _): (ProtocolRequestAck, _) =
323+
hubpack::deserialize(&protocol_ack_bytes)?;
324+
325+
match protocol_ack {
326+
Ok(v) => {
327+
if v != version {
328+
// this isn't right...
329+
return Err(Error::ClientMismatch);
330+
}
319331
}
332+
Err(_) => return Err(Error::ClientGaveUp),
320333
}
321-
Err(_) => return Err(Error::ClientGaveUp),
322-
}
323334

324-
// Right now all protocols are the same
325-
info!(self.log, "Running with protocol version {version}");
326-
327-
// get Nonce from client
328-
let client_nonce = recv_msg(&mut stream).await?;
329-
let client_nonce = Nonce::try_from(client_nonce)?;
330-
331-
// generate & send Nonce to client
332-
let nonce = Nonce::from_platform_rng()?;
333-
send_msg(&mut stream, nonce.as_ref()).await?;
334-
335-
// get attestation & verify it before sending it
336-
// The attesation protocol has an inherent race condition between
337-
// getting the log and the attestation. We verify our own attestation
338-
// before sending it to the challenger to fail as early as possible.
339-
let attest_data = get_attest_data(&self.attest_config, &client_nonce)?;
340-
dice_verifier::verify_attestation(
341-
&attest_data.certs[0],
342-
&attest_data.attestation,
343-
&attest_data.log,
344-
&client_nonce,
345-
)?;
346-
347-
// get & verify client attestation cert chain
348-
let client_cert_chain = recv_msg(&mut stream).await?;
349-
let client_cert_chain = certs_from_der(&client_cert_chain)?;
350-
let root = dice_verifier::verify_cert_chain(
351-
&client_cert_chain,
352-
Some(&self.roots),
353-
)?;
354-
let client_platform_id =
355-
dice_mfg_msgs::PlatformId::try_from(&client_cert_chain)?;
356-
info!(
357-
self.log,
358-
"Cert chain from peer \"{}\" verified against root \"{}\"",
359-
client_platform_id.as_str()?,
360-
root.tbs_certificate.subject,
361-
);
362-
363-
if tq_platform_id != client_platform_id {
364-
return Err(Error::PlatformIdMismatch);
365-
}
366-
info!(
367-
self.log,
368-
"TQ & attestation cert chains agree on platform id"
369-
);
370-
371-
// send server attestation cert chain to client
372-
let cert_chain_der = certs_to_der(&attest_data.certs)?;
373-
send_msg(&mut stream, &cert_chain_der).await?;
374-
375-
// get measurement log from client
376-
let client_log = recv_msg(&mut stream).await?;
377-
let (client_log, _): (Log, _) = hubpack::deserialize(&client_log)?;
378-
379-
// send server measurement log to client
380-
let mut buf = vec![0u8; Log::MAX_SIZE];
381-
let len = hubpack::serialize(&mut buf, &attest_data.log)?;
382-
send_msg(&mut stream, &buf[..len]).await?;
383-
384-
// get attestation from client
385-
let client_attestation = recv_msg(&mut stream).await?;
386-
let (client_attestation, _): (Attestation, _) =
387-
hubpack::deserialize(&client_attestation)?;
388-
389-
// verify client attestation
390-
dice_verifier::verify_attestation(
391-
&client_cert_chain[0],
392-
&client_attestation,
393-
&client_log,
394-
&nonce,
395-
)?;
396-
info!(self.log, "Peer attestation verified");
397-
398-
// appraise measurements from client attestation against reference
399-
// measurements
400-
let measurements =
401-
MeasurementSet::from_artifacts(&client_cert_chain, &client_log)?;
402-
let result =
403-
match dice_verifier::verify_measurements(&measurements, &corpus) {
335+
// Right now all protocols are the same
336+
info!(self.log, "Running with protocol version {version}");
337+
338+
// get Nonce from client
339+
let client_nonce = recv_msg(&mut stream).await?;
340+
let client_nonce = Nonce::try_from(client_nonce)?;
341+
342+
// generate & send Nonce to client
343+
let nonce = Nonce::from_platform_rng()?;
344+
send_msg(&mut stream, nonce.as_ref()).await?;
345+
346+
// get attestation & verify it before sending it
347+
// The attesation protocol has an inherent race condition between
348+
// getting the log and the attestation. We verify our own attestation
349+
// before sending it to the challenger to fail as early as possible.
350+
let attest_data =
351+
get_attest_data(&self.attest_config, &client_nonce)?;
352+
dice_verifier::verify_attestation(
353+
&attest_data.certs[0],
354+
&attest_data.attestation,
355+
&attest_data.log,
356+
&client_nonce,
357+
)?;
358+
359+
// get & verify client attestation cert chain
360+
let client_cert_chain = recv_msg(&mut stream).await?;
361+
let client_cert_chain = certs_from_der(&client_cert_chain)?;
362+
let root = dice_verifier::verify_cert_chain(
363+
&client_cert_chain,
364+
Some(&self.roots),
365+
)?;
366+
let client_platform_id =
367+
dice_mfg_msgs::PlatformId::try_from(&client_cert_chain)?;
368+
info!(
369+
self.log,
370+
"Cert chain from peer \"{}\" verified against root \"{}\"",
371+
client_platform_id.as_str()?,
372+
root.tbs_certificate.subject,
373+
);
374+
375+
if tq_platform_id != client_platform_id {
376+
return Err(Error::PlatformIdMismatch);
377+
}
378+
info!(
379+
self.log,
380+
"TQ & attestation cert chains agree on platform id"
381+
);
382+
383+
// send server attestation cert chain to client
384+
let cert_chain_der = certs_to_der(&attest_data.certs)?;
385+
send_msg(&mut stream, &cert_chain_der).await?;
386+
387+
// get measurement log from client
388+
let client_log = recv_msg(&mut stream).await?;
389+
let (client_log, _): (Log, _) = hubpack::deserialize(&client_log)?;
390+
391+
// send server measurement log to client
392+
let mut buf = vec![0u8; Log::MAX_SIZE];
393+
let len = hubpack::serialize(&mut buf, &attest_data.log)?;
394+
send_msg(&mut stream, &buf[..len]).await?;
395+
396+
// get attestation from client
397+
let client_attestation = recv_msg(&mut stream).await?;
398+
let (client_attestation, _): (Attestation, _) =
399+
hubpack::deserialize(&client_attestation)?;
400+
401+
// verify client attestation
402+
dice_verifier::verify_attestation(
403+
&client_cert_chain[0],
404+
&client_attestation,
405+
&client_log,
406+
&nonce,
407+
)?;
408+
info!(self.log, "Peer attestation verified");
409+
410+
// appraise measurements from client attestation against reference
411+
// measurements
412+
let measurements = MeasurementSet::from_artifacts(
413+
&client_cert_chain,
414+
&client_log,
415+
)?;
416+
let result = match dice_verifier::verify_measurements(
417+
&measurements,
418+
&corpus,
419+
) {
404420
Ok(()) => {
405421
info!(self.log, "Peer measurements appraised successfully");
406422
true
@@ -414,11 +430,12 @@ impl Server {
414430
}
415431
};
416432

417-
// hubpack the attestation and send to client
418-
let mut buf = vec![0u8; Attestation::MAX_SIZE];
419-
let len = hubpack::serialize(&mut buf, &attest_data.attestation)?;
420-
send_msg(&mut stream, &buf[..len]).await?;
433+
// hubpack the attestation and send to client
434+
let mut buf = vec![0u8; Attestation::MAX_SIZE];
435+
let len = hubpack::serialize(&mut buf, &attest_data.attestation)?;
436+
send_msg(&mut stream, &buf[..len]).await?;
421437

422-
Ok((Stream::new(stream.into(), client_platform_id, result), addr))
438+
Ok((Stream::new(stream.into(), client_platform_id, result), addr))
439+
}
423440
}
424441
}

0 commit comments

Comments
 (0)