Skip to content

Commit df1e7c8

Browse files
committed
Make remote_attestation crate no_std compatible
1 parent 6e43737 commit df1e7c8

File tree

12 files changed

+269
-143
lines changed

12 files changed

+269
-143
lines changed

Cargo.lock

Lines changed: 2 additions & 14 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

grpc_attestation/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ oak_remote_attestation = { path = "../remote_attestation/rust/" }
1313
oak_functions_abi = { path = "../oak_functions/abi/" }
1414
prost = "*"
1515
prost-types = "*"
16+
serde = { version = "*", features = ["derive"] }
1617
tokio = { version = "*", features = [
1718
"fs",
1819
"macros",

remote_attestation/rust/Cargo.toml

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,17 @@ authors = ["Ivan Petrov <[email protected]>"]
55
edition = "2021"
66
license = "Apache-2.0"
77

8+
[features]
9+
default = ["alloc"]
10+
std = ["anyhow/std", "prost/std"]
11+
alloc = []
12+
813
[dependencies]
9-
anyhow = "*"
10-
bincode = "*"
14+
anyhow = { version = "*", default-features = false }
15+
bytes = { version = "*", default-features = false }
1116
log = "*"
12-
prost = "*"
17+
prost = { version = "*", default-features = false, features = ["prost-derive"] }
1318
ring = "*"
14-
serde = { version = "*", features = ["derive"] }
15-
serde-big-array = { version = "*", features = ["const-generics"] }
16-
sha2 = "*"
1719

1820
[build-dependencies]
1921
prost-build = "*"

remote_attestation/rust/build.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,10 @@
1414
// limitations under the License.
1515
//
1616

17-
fn main() -> Result<(), Box<dyn std::error::Error>> {
17+
fn main() {
1818
prost_build::compile_protos(
1919
&["remote_attestation/proto/remote_attestation.proto"],
2020
&["../.."],
2121
)
2222
.expect("Proto compilation failed");
23-
Ok(())
2423
}

remote_attestation/rust/src/crypto.rs

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,17 @@
2020
// protocol.
2121

2222
use crate::message::EncryptedData;
23+
use alloc::vec::Vec;
2324
use anyhow::{anyhow, Context};
25+
use core::convert::TryInto;
2426
use ring::{
2527
aead::{self, BoundKey},
2628
agreement,
29+
digest::{digest, SHA256},
2730
hkdf::{Salt, HKDF_SHA256},
2831
rand::{SecureRandom, SystemRandom},
2932
signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, EcdsaVerificationAlgorithm, KeyPair},
3033
};
31-
use sha2::{digest::Digest, Sha256};
32-
use std::convert::TryInto;
3334

3435
/// Length of the encryption nonce.
3536
/// `ring::aead` uses 96-bit (12-byte) nonces.
@@ -193,7 +194,7 @@ impl KeyNegotiator {
193194
.map_err(|error| anyhow!("Couldn't get public key: {:?}", error))?
194195
.as_ref()
195196
.to_vec();
196-
public_key.as_slice().try_into().context(format!(
197+
public_key.as_slice().try_into().context(alloc::format!(
197198
"Incorrect public key length, expected {}, found {}",
198199
KEY_AGREEMENT_ALGORITHM_KEY_LENGTH,
199200
public_key.len()
@@ -234,7 +235,7 @@ impl KeyNegotiator {
234235
&agreement::UnparsedPublicKey::new(KEY_AGREEMENT_ALGORITHM, peer_public_key),
235236
anyhow!("Couldn't derive session keys"),
236237
|key_material| {
237-
let key_material = key_material.try_into().context(format!(
238+
let key_material = key_material.try_into().context(alloc::format!(
238239
"Incorrect key material length, expected {}, found {}",
239240
KEY_AGREEMENT_ALGORITHM_KEY_LENGTH,
240241
key_material.len()
@@ -298,7 +299,7 @@ impl KeyNegotiator {
298299
client_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
299300
) -> anyhow::Result<[u8; AEAD_ALGORITHM_KEY_LENGTH]> {
300301
// Session key is derived from a purpose string and two public keys.
301-
let info = vec![key_purpose.as_bytes(), server_public_key, client_public_key];
302+
let info = alloc::vec![key_purpose.as_bytes(), server_public_key, client_public_key];
302303

303304
// Initialize key derivation function.
304305
let salt = Salt::new(HKDF_SHA256, KEY_DERIVATION_SALT.as_bytes());
@@ -339,6 +340,7 @@ pub struct Signer {
339340

340341
impl Signer {
341342
pub fn create() -> anyhow::Result<Self> {
343+
// TODO(#2557): Ensure SystemRandom work when building for x86_64 UEFI targets.
342344
let rng = ring::rand::SystemRandom::new();
343345
let key_pair_pkcs8 = EcdsaKeyPair::generate_pkcs8(SIGNING_ALGORITHM, &rng)
344346
.map_err(|error| anyhow!("Couldn't generate PKCS#8 key pair: {:?}", error))?;
@@ -350,7 +352,7 @@ impl Signer {
350352

351353
pub fn public_key(&self) -> anyhow::Result<[u8; SIGNING_ALGORITHM_KEY_LENGTH]> {
352354
let public_key = self.key_pair.public_key().as_ref().to_vec();
353-
public_key.as_slice().try_into().context(format!(
355+
public_key.as_slice().try_into().context(alloc::format!(
354356
"Incorrect public key length, expected {}, found {}",
355357
SIGNING_ALGORITHM_KEY_LENGTH,
356358
public_key.len()
@@ -365,7 +367,7 @@ impl Signer {
365367
.map_err(|error| anyhow!("Couldn't sign input: {:?}", error))?
366368
.as_ref()
367369
.to_vec();
368-
signature.as_slice().try_into().context(format!(
370+
signature.as_slice().try_into().context(alloc::format!(
369371
"Incorrect signature length, expected {}, found {}",
370372
SIGNATURE_LENGTH,
371373
signature.len()
@@ -397,11 +399,8 @@ impl SignatureVerifier {
397399

398400
/// Computes a SHA-256 digest of `input` and returns it in a form of raw bytes.
399401
pub fn get_sha256(input: &[u8]) -> [u8; SHA256_HASH_LENGTH] {
400-
let mut hasher = Sha256::new();
401-
hasher.update(&input);
402-
hasher
403-
.finalize()
404-
.as_slice()
402+
digest(&SHA256, input)
403+
.as_ref()
405404
.try_into()
406405
.expect("Incorrect SHA-256 hash length")
407406
}

remote_attestation/rust/src/handshaker.rs

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ use crate::{
3434
},
3535
proto::{AttestationInfo, AttestationReport},
3636
};
37+
use alloc::{boxed::Box, vec::Vec};
3738
use anyhow::{anyhow, Context};
3839
use prost::Message;
3940

@@ -54,8 +55,8 @@ impl Default for ClientHandshakerState {
5455
}
5556
}
5657

57-
impl std::fmt::Debug for ClientHandshakerState {
58-
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
58+
impl core::fmt::Debug for ClientHandshakerState {
59+
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
5960
match self {
6061
Self::Initializing => write!(f, "Initializing"),
6162
Self::ExpectingServerIdentity(_) => write!(f, "ExpectingServerIdentity"),
@@ -81,8 +82,8 @@ impl Default for ServerHandshakerState {
8182
}
8283
}
8384

84-
impl std::fmt::Debug for ServerHandshakerState {
85-
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
85+
impl core::fmt::Debug for ServerHandshakerState {
86+
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
8687
match self {
8788
Self::ExpectingClientHello => write!(f, "ExpectingClientHello"),
8889
Self::ExpectingClientIdentity(_) => write!(f, "ExpectingClientIdentity"),
@@ -131,7 +132,7 @@ impl ClientHandshaker {
131132
deserialize_message(message).context("Couldn't deserialize message")?;
132133
match deserialized_message {
133134
MessageWrapper::ServerIdentity(server_identity) => {
134-
match std::mem::take(&mut self.state) {
135+
match core::mem::take(&mut self.state) {
135136
ClientHandshakerState::ExpectingServerIdentity(key_negotiator) => {
136137
let client_identity = self
137138
.process_server_identity(server_identity, key_negotiator)
@@ -303,7 +304,7 @@ impl ClientHandshaker {
303304
// Signing public key.
304305
[Default::default(); SIGNING_ALGORITHM_KEY_LENGTH],
305306
// Attestation info.
306-
vec![],
307+
alloc::vec![],
307308
)
308309
};
309310

@@ -380,7 +381,7 @@ impl ServerHandshaker {
380381
)),
381382
},
382383
MessageWrapper::ClientIdentity(client_identity) => {
383-
match std::mem::take(&mut self.state) {
384+
match core::mem::take(&mut self.state) {
384385
ServerHandshakerState::ExpectingClientIdentity(key_negotiator) => {
385386
self.process_client_identity(client_identity, key_negotiator)
386387
.context("Couldn't process client identity message")?;
@@ -484,9 +485,9 @@ impl ServerHandshaker {
484485
// Signing public key.
485486
[Default::default(); SIGNING_ALGORITHM_KEY_LENGTH],
486487
// Attestation info.
487-
vec![],
488+
alloc::vec![],
488489
// Additional info.
489-
vec![],
490+
alloc::vec![],
490491
)
491492
};
492493

@@ -602,8 +603,8 @@ pub struct AttestationBehavior {
602603
signer: Option<Signer>,
603604
}
604605

605-
impl std::fmt::Debug for AttestationBehavior {
606-
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
606+
impl core::fmt::Debug for AttestationBehavior {
607+
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
607608
match (
608609
self.contains_peer_attestation(),
609610
self.contains_self_attestation(),
@@ -680,7 +681,9 @@ struct Transcript {
680681

681682
impl Transcript {
682683
pub fn new() -> Self {
683-
Self { value: vec![] }
684+
Self {
685+
value: alloc::vec![],
686+
}
684687
}
685688

686689
/// Appends a serialized `message` to the end of [`Transcript::value`].
@@ -732,6 +735,7 @@ pub fn verify_attestation_info(
732735
expected_tee_measurement: &[u8],
733736
) -> anyhow::Result<()> {
734737
let attestation_info = AttestationInfo::decode(attestation_info_bytes)
738+
.map_err(anyhow::Error::msg)
735739
.context("Couldn't decode attestation info Protobuf message")?;
736740

737741
// TODO(#1867): Add remote attestation support, use real TEE reports and check that
@@ -760,6 +764,7 @@ pub fn serialize_protobuf<M: prost::Message>(message: &M) -> anyhow::Result<Vec<
760764
let mut message_bytes = Vec::new();
761765
message
762766
.encode(&mut message_bytes)
767+
.map_err(anyhow::Error::msg)
763768
.context("Couldn't serialize Protobuf message to bytes")?;
764769
Ok(message_bytes)
765770
}

remote_attestation/rust/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@
1414
// limitations under the License.
1515
//
1616

17+
#![cfg_attr(not(feature = "std"), no_std)]
18+
#![feature(exclusive_range_pattern)]
19+
20+
extern crate alloc;
21+
1722
pub mod proto {
1823
#![allow(clippy::return_self_not_must_use)]
1924
include!(concat!(env!("OUT_DIR"), "/oak.remote_attestation.rs"));

0 commit comments

Comments
 (0)