forked from confidential-containers/trustee
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
349 lines (299 loc) · 11.2 KB
/
lib.rs
File metadata and controls
349 lines (299 loc) · 11.2 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
// Copyright (c) 2023 by Alibaba.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! KBS client SDK.
use anyhow::{anyhow, bail, Result};
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use base64::Engine;
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use kbs_protocol::evidence_provider::NativeEvidenceProvider;
use kbs_protocol::token_provider::TestTokenProvider;
use kbs_protocol::KbsClientBuilder;
use kbs_protocol::KbsClientCapabilities;
use serde::Serialize;
use serde_json::json;
use std::time::{SystemTime, UNIX_EPOCH};
const KBS_URL_PREFIX: &str = "kbs/v0";
const ADMIN_TOKEN_EXPIRY_SECS: u64 = 7200;
#[derive(Serialize)]
struct AdminClaims {
exp: u64,
iat: u64,
}
fn sign_admin_token(auth_key: &str) -> Result<String> {
let encoding_key = EncodingKey::from_ed_pem(auth_key.as_bytes())?;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| anyhow!("System time error: {e}"))?
.as_secs();
let claims = AdminClaims {
iat: now,
exp: now + ADMIN_TOKEN_EXPIRY_SECS,
};
let token = encode(&Header::new(Algorithm::EdDSA), &claims, &encoding_key)?;
Ok(token)
}
/// Attestation and get a result token signed by attestation service
/// Input parameters:
/// - url: KBS server root URL.
/// - [tee_pubkey_pem]: Public key (PEM format) of the RSA key pair generated in TEE.
/// This public key will be contained in attestation results token.
/// - kbs_root_certs_pem: Custom HTTPS root certificate of KBS server. It can be left blank.
/// - init_data: Plaintext init-data; should correspond to init-data measured at boot time.
pub async fn attestation(
url: &str,
tee_key_pem: Option<String>,
kbs_root_certs_pem: Vec<String>,
init_data: Option<String>,
) -> Result<String> {
let evidence_provider = Box::new(NativeEvidenceProvider::new()?);
let mut client_builder = KbsClientBuilder::with_evidence_provider(evidence_provider, url);
if let Some(key) = tee_key_pem {
client_builder = client_builder.set_tee_key(&key)
}
for cert in kbs_root_certs_pem {
client_builder = client_builder.add_kbs_cert(&cert)
}
if let Some(init_data) = init_data {
client_builder = client_builder.add_initdata(init_data);
}
let mut client = client_builder.build()?;
let (token, _) = client.get_token().await?;
Ok(token.content)
}
/// Get secret resources with attestation results token
/// Input parameters:
/// - url: KBS server root URL.
/// - path: Resource path, format must be `<top>/<middle>/<tail>`, e.g. `alice/key/example`.
/// - tee_key_pem: TEE private key file path (PEM format). This key must consistent with the public key in `token` claims.
/// - token: Attestation Results Token file path.
/// - kbs_root_certs_pem: Custom HTTPS root certificate of KBS server. It can be left blank.
pub async fn get_resource_with_token(
url: &str,
path: &str,
tee_key_pem: String,
token: String,
kbs_root_certs_pem: Vec<String>,
) -> Result<Vec<u8>> {
let token_provider = Box::<TestTokenProvider>::default();
let mut client_builder =
KbsClientBuilder::with_token_provider(token_provider, url).set_token(&token);
client_builder = client_builder.set_tee_key(&tee_key_pem);
for cert in kbs_root_certs_pem {
client_builder = client_builder.add_kbs_cert(&cert)
}
let mut client = client_builder.build()?;
let resource_kbs_uri = format!("kbs:///{path}");
let resource_bytes = client
.get_resource(serde_json::from_str(&format!("\"{resource_kbs_uri}\""))?)
.await?;
Ok(resource_bytes)
}
/// Get secret resources with attestation
/// Input parameters:
/// - url: KBS server root URL.
/// - path: Resource path, format must be `<top>/<middle>/<tail>`, e.g. `alice/key/example`.
/// - [tee_pubkey_pem]: Public key (PEM format) of the RSA key pair generated in TEE.
/// - kbs_root_certs_pem: Custom HTTPS root certificate of KBS server. It can be left blank.
/// - init_data: Plaintext init-data; should correspond to init-data measured at boot time.
pub async fn get_resource_with_attestation(
url: &str,
path: &str,
tee_key_pem: Option<String>,
kbs_root_certs_pem: Vec<String>,
init_data: Option<String>,
) -> Result<Vec<u8>> {
let evidence_provider = Box::new(NativeEvidenceProvider::new()?);
let mut client_builder = KbsClientBuilder::with_evidence_provider(evidence_provider, url);
if let Some(key) = tee_key_pem {
client_builder = client_builder.set_tee_key(&key);
}
for cert in kbs_root_certs_pem {
client_builder = client_builder.add_kbs_cert(&cert)
}
if let Some(init_data) = init_data {
client_builder = client_builder.add_initdata(init_data);
}
let mut client = client_builder.build()?;
let resource_kbs_uri = format!("kbs:///{path}");
let resource_bytes = client
.get_resource(serde_json::from_str(&format!("\"{resource_kbs_uri}\""))?)
.await?;
Ok(resource_bytes)
}
#[derive(Serialize)]
pub struct SetPolicyInput {
pub r#type: String,
pub policy_id: String,
pub policy: String,
}
/// Set attestation policy
/// Input parameters:
/// - url: KBS server root URL.
/// - auth_key: KBS owner's authenticate private key (PEM string).
/// - policy_bytes: Policy file content in `Vec<u8>`.
/// - [policy_type]: Policy type. Default value is "rego".
/// - [policy_id]: Policy ID. Default value is "default".
/// - kbs_root_certs_pem: Custom HTTPS root certificate of KBS server. It can be left blank.
pub async fn set_attestation_policy(
url: &str,
auth_key: String,
policy_bytes: Vec<u8>,
policy_type: Option<String>,
policy_id: Option<String>,
kbs_root_certs_pem: Vec<String>,
) -> Result<()> {
let token = sign_admin_token(&auth_key)?;
let http_client = build_http_client(kbs_root_certs_pem)?;
let set_policy_url = format!("{}/{KBS_URL_PREFIX}/attestation-policy", url);
let post_input = SetPolicyInput {
r#type: policy_type.unwrap_or("rego".to_string()),
policy_id: policy_id.unwrap_or("default".to_string()),
policy: URL_SAFE_NO_PAD.encode(policy_bytes.clone()),
};
let res = http_client
.post(set_policy_url)
.header("Content-Type", "application/json")
.bearer_auth(token.clone())
.json::<SetPolicyInput>(&post_input)
.send()
.await?;
match res.status() {
reqwest::StatusCode::OK => Ok(()),
_ => {
bail!("Request Failed, Response: {:?}", res.text().await?)
}
}
}
#[derive(Clone, Serialize)]
struct ResourcePolicyData {
pub policy: String,
}
/// Set resource policy
/// Input parameters:
/// - url: KBS server root URL.
/// - auth_key: KBS owner's authenticate private key (PEM string).
/// - policy_bytes: Policy file content in `Vec<u8>`.
/// - kbs_root_certs_pem: Custom HTTPS root certificate of KBS server. It can be left blank.
pub async fn set_resource_policy(
url: &str,
auth_key: String,
policy_bytes: Vec<u8>,
kbs_root_certs_pem: Vec<String>,
) -> Result<()> {
let token = sign_admin_token(&auth_key)?;
let http_client = build_http_client(kbs_root_certs_pem)?;
let set_policy_url = format!("{}/{KBS_URL_PREFIX}/resource-policy", url);
let post_input = ResourcePolicyData {
policy: URL_SAFE_NO_PAD.encode(policy_bytes.clone()),
};
let res = http_client
.post(set_policy_url)
.header("Content-Type", "application/json")
.bearer_auth(token.clone())
.json::<ResourcePolicyData>(&post_input)
.send()
.await?;
if res.status() != reqwest::StatusCode::OK {
bail!("Request Failed, Response: {:?}", res.text().await?);
}
Ok(())
}
/// Set secret resource to KBS.
/// Input parameters:
/// - url: KBS server root URL.
/// - auth_key: KBS owner's authenticate private key (PEM string).
/// - resource_bytes: Resource data in `Vec<u8>`
/// - path: Resource path, format must be `<top>/<middle>/<tail>`, e.g. `alice/key/example`.
/// - kbs_root_certs_pem: Custom HTTPS root certificate of KBS server. It can be left blank.
pub async fn set_resource(
url: &str,
auth_key: String,
resource_bytes: Vec<u8>,
path: &str,
kbs_root_certs_pem: Vec<String>,
) -> Result<()> {
let token = sign_admin_token(&auth_key)?;
let http_client = build_http_client(kbs_root_certs_pem)?;
let resource_url = format!("{}/{KBS_URL_PREFIX}/resource/{}", url, path);
let res = http_client
.post(resource_url)
.header("Content-Type", "application/octet-stream")
.bearer_auth(token)
.body(resource_bytes.clone())
.send()
.await?;
match res.status() {
reqwest::StatusCode::OK => Ok(()),
_ => {
bail!("Request Failed, Response: {:?}", res.text().await?)
}
}
}
/// Set a reference value in the RVPS at <url>
/// RVPS must be configured with the non-secure sample extractor
/// The RVPS-tool should be used in production environments
pub async fn set_sample_rv(
url: String,
key: String,
value: serde_json::Value,
auth_key: String,
kbs_root_certs_pem: Vec<String>,
) -> Result<()> {
let token = sign_admin_token(&auth_key)?;
let http_client = build_http_client(kbs_root_certs_pem)?;
let reference_value_url = format!("{}/{KBS_URL_PREFIX}/reference-value", url);
let provenance = json!({key: value}).to_string();
let provenance = STANDARD.encode(provenance);
let message = json!({
"version": "0.1.0",
"type": "sample",
"payload": provenance
});
let res = http_client
.post(reference_value_url)
.header("Content-Type", "application/json")
.bearer_auth(token.clone())
.body(message.to_string())
.send()
.await?;
match res.status() {
reqwest::StatusCode::OK => Ok(()),
_ => {
bail!("Request Failed, Response: {:?}", res.text().await?)
}
}
}
pub async fn get_rv(
url: String,
auth_key: String,
kbs_root_certs_pem: Vec<String>,
reference_value_id: String,
) -> Result<String> {
let token = sign_admin_token(&auth_key)?;
let http_client = build_http_client(kbs_root_certs_pem)?;
let reference_value_url = format!("{}/{KBS_URL_PREFIX}/reference-value/{reference_value_id}", url);
let res = http_client
.get(reference_value_url)
.header("Content-Type", "application/json")
.bearer_auth(token.clone())
.send()
.await?;
match res.status() {
reqwest::StatusCode::OK => Ok(res.text().await?),
_ => {
bail!("Request Failed, Response: {:?}", res.text().await?)
}
}
}
fn build_http_client(kbs_root_certs_pem: Vec<String>) -> Result<reqwest::Client> {
let mut client_builder =
reqwest::Client::builder().user_agent(format!("kbs-client/{}", env!("CARGO_PKG_VERSION")));
for custom_root_cert in kbs_root_certs_pem.iter() {
let cert = reqwest::Certificate::from_pem(custom_root_cert.as_bytes())?;
client_builder = client_builder.add_root_certificate(cert);
}
client_builder
.build()
.map_err(|e| anyhow!("Build KBS http client failed: {:?}", e))
}